WPILibC++ 2024.3.2
mpack.h
Go to the documentation of this file.
1/**
2 * The MIT License (MIT)
3 *
4 * Copyright (c) 2015-2021 Nicholas Fraser and the MPack authors
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 *
24 */
25
26/*
27 * This is the MPack 1.1.1 amalgamation package.
28 *
29 * http://github.com/ludocode/mpack
30 */
31
32#ifndef MPACK_H
33#define MPACK_H 1
34
35#define MPACK_AMALGAMATED 1
36
37#if defined(MPACK_HAS_CONFIG) && MPACK_HAS_CONFIG
38#include "mpack-config.h"
39#endif
40
41/**
42 * @defgroup mpack MPack
43 * MPack is a C implementation of an encoder and decoder for the MessagePack
44 * serialization format.
45 */
46
47/* mpack/mpack-platform.h.h */
48
49/**
50 * @file
51 *
52 * Abstracts all platform-specific code from MPack and handles configuration
53 * options.
54 *
55 * This verifies the configuration and sets defaults based on the platform,
56 * contains implementations of standard C functions when libc is not available,
57 * and provides wrappers to all library functions.
58 *
59 * Documentation for configuration options is available here:
60 *
61 * https://ludocode.github.io/mpack/group__config.html
62 */
63
64#ifndef MPACK_PLATFORM_H
65#define MPACK_PLATFORM_H 1
66
67
68
69/**
70 * @defgroup mpack_config Configuration Options
71 * @ingroup mpack
72 *
73 * Defines the MPack configuration options.
74 *
75 * Custom configuration of MPack is not usually necessary. In almost all
76 * cases you can ignore this and use the defaults.
77 *
78 * If you do want to configure MPack, you can define the below options as part
79 * of your build system or project settings. This will override the below
80 * defaults.
81 *
82 * If you'd like to use a file for configuration instead, define
83 * @ref MPACK_HAS_CONFIG to 1 in your build system or project settings.
84 * This will cause MPack to include a file you create called @c mpack-config.h
85 * in which you can define your configuration. This is useful if you need to
86 * include specific headers (such as a custom allocator) in order to configure
87 * MPack to use it.
88 *
89 * @warning The value of all configuration options must be the same in
90 * all translation units of your project, as well as in the mpack source
91 * itself. These configuration options affect the layout of structs, among
92 * other things, which cannot be different in source files that are linked
93 * together.
94 *
95 * @note MPack does not contain defaults for building inside the Linux kernel.
96 * There is a <a href="https://github.com/ludocode/mpack-linux-kernel">
97 * configuration file for the Linux kernel</a> that can be used instead.
98 *
99 * @{
100 */
101
102
103
104/*
105 * Pre-include checks
106 *
107 * These need to come before the user's mpack-config.h because they might be
108 * including headers in it.
109 */
110
111/** @cond */
112#if defined(_MSC_VER) && _MSC_VER < 1800 && !defined(__cplusplus)
113 #error "In Visual Studio 2012 and earlier, MPack must be compiled as C++. Enable the /Tp compiler flag."
114#endif
115
116#if defined(_WIN32) && MPACK_INTERNAL
117 #define _CRT_SECURE_NO_WARNINGS 1
118#endif
119
120#ifndef __STDC_LIMIT_MACROS
121 #define __STDC_LIMIT_MACROS 1
122#endif
123#ifndef __STDC_FORMAT_MACROS
124 #define __STDC_FORMAT_MACROS 1
125#endif
126#ifndef __STDC_CONSTANT_MACROS
127 #define __STDC_CONSTANT_MACROS 1
128#endif
129/** @endcond */
130
131
132
133/**
134 * @name File Configuration
135 * @{
136 */
137
138/**
139 * @def MPACK_HAS_CONFIG
140 *
141 * Causes MPack to include a file you create called @c mpack-config.h .
142 *
143 * The file is included before MPack sets any defaults for undefined
144 * configuration options. You can use it to configure MPack.
145 *
146 * This is off by default.
147 */
148#if defined(MPACK_HAS_CONFIG)
149 #if MPACK_HAS_CONFIG
150 #include "mpack-config.h"
151 #endif
152#else
153 #define MPACK_HAS_CONFIG 0
154#endif
155
156/**
157 * @}
158 */
159
160// this needs to come first since some stuff depends on it
161/** @cond */
162#ifndef MPACK_NO_BUILTINS
163 #define MPACK_NO_BUILTINS 0
164#endif
165/** @endcond */
166
167
168
169/**
170 * @name Features
171 * @{
172 */
173
174/**
175 * @def MPACK_READER
176 *
177 * Enables compilation of the base Tag Reader.
178 */
179#ifndef MPACK_READER
180#define MPACK_READER 1
181#endif
182
183/**
184 * @def MPACK_EXPECT
185 *
186 * Enables compilation of the static Expect API.
187 */
188#ifndef MPACK_EXPECT
189#define MPACK_EXPECT 1
190#endif
191
192/**
193 * @def MPACK_NODE
194 *
195 * Enables compilation of the dynamic Node API.
196 */
197#ifndef MPACK_NODE
198#define MPACK_NODE 1
199#endif
200
201/**
202 * @def MPACK_WRITER
203 *
204 * Enables compilation of the Writer.
205 */
206#ifndef MPACK_WRITER
207#define MPACK_WRITER 1
208#endif
209
210/**
211 * @def MPACK_BUILDER
212 *
213 * Enables compilation of the Builder.
214 *
215 * The Builder API provides additional functions to the Writer for
216 * automatically determining the element count of compound elements so you do
217 * not have to specify them up-front.
218 *
219 * This requires a @c malloc(). It is enabled by default if MPACK_WRITER is
220 * enabled and MPACK_MALLOC is defined.
221 *
222 * @see mpack_build_map()
223 * @see mpack_build_array()
224 * @see mpack_complete_map()
225 * @see mpack_complete_array()
226 */
227// This is defined furthur below after we've resolved whether we have malloc().
228
229/**
230 * @def MPACK_COMPATIBILITY
231 *
232 * Enables compatibility features for reading and writing older
233 * versions of MessagePack.
234 *
235 * This is disabled by default. When disabled, the behaviour is equivalent to
236 * using the default version, @ref mpack_version_current.
237 *
238 * Enable this if you need to interoperate with applications or data that do
239 * not support the new (v5) MessagePack spec. See the section on v4
240 * compatibility in @ref docs/protocol.md for more information.
241 */
242#ifndef MPACK_COMPATIBILITY
243#define MPACK_COMPATIBILITY 0
244#endif
245
246/**
247 * @def MPACK_EXTENSIONS
248 *
249 * Enables the use of extension types.
250 *
251 * This is disabled by default. Define it to 1 to enable it. If disabled,
252 * functions to read and write extensions will not exist, and any occurrence of
253 * extension types in parsed messages will flag @ref mpack_error_invalid.
254 *
255 * MPack discourages the use of extension types. See the section on extension
256 * types in @ref docs/protocol.md for more information.
257 */
258#ifndef MPACK_EXTENSIONS
259#define MPACK_EXTENSIONS 0
260#endif
261
262/**
263 * @}
264 */
265
266
267
268// workarounds for Doxygen
269#if defined(MPACK_DOXYGEN)
270#if MPACK_DOXYGEN
271// We give these their default values of 0 here even though they are defined to
272// 1 in the doxyfile. Doxygen will show this as the value in the docs, even
273// though it ignores it when parsing the rest of the source. This is what we
274// want, since we want the documentation to show these defaults but still
275// generate documentation for the functions they add when they're on.
276#define MPACK_COMPATIBILITY 0
277#define MPACK_EXTENSIONS 0
278#endif
279#endif
280
281
282
283/**
284 * @name Dependencies
285 * @{
286 */
287
288/**
289 * @def MPACK_CONFORMING
290 *
291 * Enables the inclusion of basic C headers to define standard types and
292 * macros.
293 *
294 * This causes MPack to include headers required for conforming implementations
295 * of C99 even in freestanding, in particular <stddef.h>, <stdint.h>,
296 * <stdbool.h> and <limits.h>. It also includes <inttypes.h>; this is
297 * technically not required for freestanding but MPack needs it to detect
298 * integer limits.
299 *
300 * You can disable this if these headers are unavailable or if they do not
301 * define the standard types and macros (for example inside the Linux kernel.)
302 * If this is disabled, MPack will include no headers and will assume a 32-bit
303 * int. You will probably also want to define @ref MPACK_HAS_CONFIG to 1 and
304 * include your own headers in the config file. You must provide definitions
305 * for standard types such as @c size_t, @c bool, @c int32_t and so on.
306 *
307 * @see <a href="https://en.cppreference.com/w/c/language/conformance">
308 * cppreference.com documentation on Conformance</a>
309 */
310#ifndef MPACK_CONFORMING
311 #define MPACK_CONFORMING 1
312#endif
313
314/**
315 * @def MPACK_STDLIB
316 *
317 * Enables the use of the C stdlib.
318 *
319 * This allows the library to use basic functions like @c memcmp() and @c
320 * strlen(), as well as @c malloc() for debugging and in allocation helpers.
321 *
322 * If this is disabled, allocation helper functions will not be defined, and
323 * MPack will attempt to detect compiler intrinsics for functions like @c
324 * memcmp() (assuming @ref MPACK_NO_BUILTINS is not set.) It will fallback to
325 * its own (slow) implementations if it cannot use builtins. You may want to
326 * define @ref MPACK_MEMCMP and friends if you disable this.
327 *
328 * @see MPACK_MEMCMP
329 * @see MPACK_MEMCPY
330 * @see MPACK_MEMMOVE
331 * @see MPACK_MEMSET
332 * @see MPACK_STRLEN
333 * @see MPACK_MALLOC
334 * @see MPACK_REALLOC
335 * @see MPACK_FREE
336 */
337#ifndef MPACK_STDLIB
338 #if !MPACK_CONFORMING
339 // If we don't even have a proper <limits.h> we assume we won't have
340 // malloc() either.
341 #define MPACK_STDLIB 0
342 #else
343 #define MPACK_STDLIB 1
344 #endif
345#endif
346
347/**
348 * @def MPACK_STDIO
349 *
350 * Enables the use of C stdio. This adds helpers for easily
351 * reading/writing C files and makes debugging easier.
352 */
353#ifndef MPACK_STDIO
354 #if !MPACK_STDLIB || defined(__AVR__)
355 #define MPACK_STDIO 0
356 #else
357 #define MPACK_STDIO 1
358 #endif
359#endif
360
361/**
362 * Whether the 'float' type and floating point operations are supported.
363 *
364 * If @ref MPACK_FLOAT is disabled, floats are read and written as @c uint32_t
365 * instead. This way messages with floats do not result in errors and you can
366 * still perform manual float parsing yourself.
367 */
368#ifndef MPACK_FLOAT
369 #define MPACK_FLOAT 1
370#endif
371
372/**
373 * Whether the 'double' type is supported. This requires support for 'float'.
374 *
375 * If @ref MPACK_DOUBLE is disabled, doubles are read and written as @c
376 * uint32_t instead. This way messages with doubles do not result in errors and
377 * you can still perform manual doubles parsing yourself.
378 *
379 * If @ref MPACK_FLOAT is enabled but @ref MPACK_DOUBLE is not, doubles can be
380 * read as floats using the shortening conversion functions, e.g. @ref
381 * mpack_expect_float() or @ref mpack_node_float().
382 */
383#ifndef MPACK_DOUBLE
384 #if !MPACK_FLOAT || defined(__AVR__)
385 // AVR supports only float, not double.
386 #define MPACK_DOUBLE 0
387 #else
388 #define MPACK_DOUBLE 1
389 #endif
390#endif
391
392/**
393 * @}
394 */
395
396
397
398/**
399 * @name Allocation Functions
400 * @{
401 */
402
403/**
404 * @def MPACK_MALLOC
405 *
406 * Defines the memory allocation function used by MPack. This is used by
407 * helpers for automatically allocating data the correct size, and for
408 * debugging functions. If this macro is undefined, the allocation helpers
409 * will not be compiled.
410 *
411 * Set this to use a custom @c malloc() function. Your function must have the
412 * signature:
413 *
414 * @code
415 * void* malloc(size_t size);
416 * @endcode
417 *
418 * The default is @c malloc() if @ref MPACK_STDLIB is enabled.
419 */
420/**
421 * @def MPACK_FREE
422 *
423 * Defines the memory free function used by MPack. This is used by helpers
424 * for automatically allocating data the correct size. If this macro is
425 * undefined, the allocation helpers will not be compiled.
426 *
427 * Set this to use a custom @c free() function. Your function must have the
428 * signature:
429 *
430 * @code
431 * void free(void* p);
432 * @endcode
433 *
434 * The default is @c free() if @ref MPACK_MALLOC has not been customized and
435 * @ref MPACK_STDLIB is enabled.
436 */
437/**
438 * @def MPACK_REALLOC
439 *
440 * Defines the realloc function used by MPack. It is used by growable
441 * buffers to resize more efficiently.
442 *
443 * The default is @c realloc() if @ref MPACK_MALLOC has not been customized and
444 * @ref MPACK_STDLIB is enabled.
445 *
446 * Set this to use a custom @c realloc() function. Your function must have the
447 * signature:
448 *
449 * @code
450 * void* realloc(void* p, size_t new_size);
451 * @endcode
452 *
453 * This is optional, even when @ref MPACK_MALLOC is used. If @ref MPACK_MALLOC is
454 * set and @ref MPACK_REALLOC is not, @ref MPACK_MALLOC is used with a simple copy
455 * to grow buffers.
456 */
457
458#if defined(MPACK_MALLOC) && !defined(MPACK_FREE)
459 #error "MPACK_MALLOC requires MPACK_FREE."
460#endif
461#if !defined(MPACK_MALLOC) && defined(MPACK_FREE)
462 #error "MPACK_FREE requires MPACK_MALLOC."
463#endif
464
465// These were never configurable in lowercase but we check anyway.
466#ifdef mpack_malloc
467 #error "Define MPACK_MALLOC, not mpack_malloc."
468#endif
469#ifdef mpack_realloc
470 #error "Define MPACK_REALLOC, not mpack_realloc."
471#endif
472#ifdef mpack_free
473 #error "Define MPACK_FREE, not mpack_free."
474#endif
475
476// We don't use calloc() at all.
477#ifdef MPACK_CALLOC
478 #error "Don't define MPACK_CALLOC. MPack does not use calloc()."
479#endif
480#ifdef mpack_calloc
481 #error "Don't define mpack_calloc. MPack does not use calloc()."
482#endif
483
484// Use defaults in stdlib if we have them. Without it we don't use malloc.
485#if defined(MPACK_STDLIB)
486 #if MPACK_STDLIB && !defined(MPACK_MALLOC)
487 #define MPACK_MALLOC malloc
488 #define MPACK_REALLOC realloc
489 #define MPACK_FREE free
490 #endif
491#endif
492
493/**
494 * @}
495 */
496
497
498
499// This needs to be defined after we've decided whether we have malloc().
500#ifndef MPACK_BUILDER
501 #if defined(MPACK_MALLOC) && MPACK_WRITER
502 #define MPACK_BUILDER 1
503 #else
504 #define MPACK_BUILDER 0
505 #endif
506#endif
507
508
509
510/**
511 * @name System Functions
512 * @{
513 */
514
515/**
516 * @def MPACK_MEMCMP
517 *
518 * The function MPack will use to provide @c memcmp().
519 *
520 * Set this to use a custom @c memcmp() function. Your function must have the
521 * signature:
522 *
523 * @code
524 * int memcmp(const void* left, const void* right, size_t count);
525 * @endcode
526 */
527/**
528 * @def MPACK_MEMCPY
529 *
530 * The function MPack will use to provide @c memcpy().
531 *
532 * Set this to use a custom @c memcpy() function. Your function must have the
533 * signature:
534 *
535 * @code
536 * void* memcpy(void* restrict dest, const void* restrict src, size_t count);
537 * @endcode
538 */
539/**
540 * @def MPACK_MEMMOVE
541 *
542 * The function MPack will use to provide @c memmove().
543 *
544 * Set this to use a custom @c memmove() function. Your function must have the
545 * signature:
546 *
547 * @code
548 * void* memmove(void* dest, const void* src, size_t count);
549 * @endcode
550 */
551/**
552 * @def MPACK_MEMSET
553 *
554 * The function MPack will use to provide @c memset().
555 *
556 * Set this to use a custom @c memset() function. Your function must have the
557 * signature:
558 *
559 * @code
560 * void* memset(void* p, int c, size_t count);
561 * @endcode
562 */
563/**
564 * @def MPACK_STRLEN
565 *
566 * The function MPack will use to provide @c strlen().
567 *
568 * Set this to use a custom @c strlen() function. Your function must have the
569 * signature:
570 *
571 * @code
572 * size_t strlen(const char* str);
573 * @endcode
574 */
575
576// These were briefly configurable in lowercase in an unreleased version. Just
577// to make sure no one is doing this, we make sure these aren't already defined.
578#ifdef mpack_memcmp
579 #error "Define MPACK_MEMCMP, not mpack_memcmp."
580#endif
581#ifdef mpack_memcpy
582 #error "Define MPACK_MEMCPY, not mpack_memcpy."
583#endif
584#ifdef mpack_memmove
585 #error "Define MPACK_MEMMOVE, not mpack_memmove."
586#endif
587#ifdef mpack_memset
588 #error "Define MPACK_MEMSET, not mpack_memset."
589#endif
590#ifdef mpack_strlen
591 #error "Define MPACK_STRLEN, not mpack_strlen."
592#endif
593
594// If the standard library is available, we prefer to use its functions.
595#if MPACK_STDLIB
596 #ifndef MPACK_MEMCMP
597 #define MPACK_MEMCMP memcmp
598 #endif
599 #ifndef MPACK_MEMCPY
600 #define MPACK_MEMCPY memcpy
601 #endif
602 #ifndef MPACK_MEMMOVE
603 #define MPACK_MEMMOVE memmove
604 #endif
605 #ifndef MPACK_MEMSET
606 #define MPACK_MEMSET memset
607 #endif
608 #ifndef MPACK_STRLEN
609 #define MPACK_STRLEN strlen
610 #endif
611#endif
612
613#if !MPACK_NO_BUILTINS
614 #ifdef __has_builtin
615 #if !defined(MPACK_MEMCMP) && __has_builtin(__builtin_memcmp)
616 #define MPACK_MEMCMP __builtin_memcmp
617 #endif
618 #if !defined(MPACK_MEMCPY) && __has_builtin(__builtin_memcpy)
619 #define MPACK_MEMCPY __builtin_memcpy
620 #endif
621 #if !defined(MPACK_MEMMOVE) && __has_builtin(__builtin_memmove)
622 #define MPACK_MEMMOVE __builtin_memmove
623 #endif
624 #if !defined(MPACK_MEMSET) && __has_builtin(__builtin_memset)
625 #define MPACK_MEMSET __builtin_memset
626 #endif
627 #if !defined(MPACK_STRLEN) && __has_builtin(__builtin_strlen)
628 #define MPACK_STRLEN __builtin_strlen
629 #endif
630 #elif defined(__GNUC__)
631 #ifndef MPACK_MEMCMP
632 #define MPACK_MEMCMP __builtin_memcmp
633 #endif
634 #ifndef MPACK_MEMCPY
635 #define MPACK_MEMCPY __builtin_memcpy
636 #endif
637 // There's not always a builtin memmove for GCC. If we can't test for
638 // it with __has_builtin above, we don't use it. It's been around for
639 // much longer under clang, but then so has __has_builtin, so we let
640 // the block above handle it.
641 #ifndef MPACK_MEMSET
642 #define MPACK_MEMSET __builtin_memset
643 #endif
644 #ifndef MPACK_STRLEN
645 #define MPACK_STRLEN __builtin_strlen
646 #endif
647 #endif
648#endif
649
650/**
651 * @}
652 */
653
654
655
656/**
657 * @name Debugging Options
658 * @{
659 */
660
661/**
662 * @def MPACK_DEBUG
663 *
664 * Enables debug features. You may want to wrap this around your
665 * own debug preprocs. By default, this is enabled if @c DEBUG or @c _DEBUG
666 * are defined. (@c NDEBUG is not used since it is allowed to have
667 * different values in different translation units.)
668 */
669#if !defined(MPACK_DEBUG)
670 #if defined(DEBUG) || defined(_DEBUG)
671 #define MPACK_DEBUG 1
672 #else
673 #define MPACK_DEBUG 0
674 #endif
675#endif
676
677/**
678 * @def MPACK_STRINGS
679 *
680 * Enables descriptive error and type strings.
681 *
682 * This can be turned off (by defining it to 0) to maximize space savings
683 * on embedded devices. If this is disabled, string functions such as
684 * mpack_error_to_string() and mpack_type_to_string() return an empty string.
685 */
686#ifndef MPACK_STRINGS
687 #ifdef __AVR__
688 #define MPACK_STRINGS 0
689 #else
690 #define MPACK_STRINGS 1
691 #endif
692#endif
693
694/**
695 * Set this to 1 to implement a custom @ref mpack_assert_fail() function.
696 * See the documentation on @ref mpack_assert_fail() for details.
697 *
698 * Asserts are only used when @ref MPACK_DEBUG is enabled, and can be
699 * triggered by bugs in MPack or bugs due to incorrect usage of MPack.
700 */
701#ifndef MPACK_CUSTOM_ASSERT
702#define MPACK_CUSTOM_ASSERT 0
703#endif
704
705/**
706 * @def MPACK_READ_TRACKING
707 *
708 * Enables compound type size tracking for readers. This ensures that the
709 * correct number of elements or bytes are read from a compound type.
710 *
711 * This is enabled by default in debug builds (provided a @c malloc() is
712 * available.)
713 */
714#if !defined(MPACK_READ_TRACKING)
715 #if MPACK_DEBUG && MPACK_READER && defined(MPACK_MALLOC)
716 #define MPACK_READ_TRACKING 1
717 #else
718 #define MPACK_READ_TRACKING 0
719 #endif
720#endif
721#if MPACK_READ_TRACKING && !MPACK_READER
722 #error "MPACK_READ_TRACKING requires MPACK_READER."
723#endif
724
725/**
726 * @def MPACK_WRITE_TRACKING
727 *
728 * Enables compound type size tracking for writers. This ensures that the
729 * correct number of elements or bytes are written in a compound type.
730 *
731 * Note that without write tracking enabled, it is possible for buggy code
732 * to emit invalid MessagePack without flagging an error by writing the wrong
733 * number of elements or bytes in a compound type. With tracking enabled,
734 * MPack will catch such errors and break on the offending line of code.
735 *
736 * This is enabled by default in debug builds (provided a @c malloc() is
737 * available.)
738 */
739#if !defined(MPACK_WRITE_TRACKING)
740 #if MPACK_DEBUG && MPACK_WRITER && defined(MPACK_MALLOC)
741 #define MPACK_WRITE_TRACKING 1
742 #else
743 #define MPACK_WRITE_TRACKING 0
744 #endif
745#endif
746#if MPACK_WRITE_TRACKING && !MPACK_WRITER
747 #error "MPACK_WRITE_TRACKING requires MPACK_WRITER."
748#endif
749
750/**
751 * @}
752 */
753
754
755
756
757/**
758 * @name Miscellaneous Options
759 * @{
760 */
761
762/**
763 * Whether to optimize for size or speed.
764 *
765 * Optimizing for size simplifies some parsing and encoding algorithms
766 * at the expense of speed and saves a few kilobytes of space in the
767 * resulting executable.
768 *
769 * This automatically detects -Os with GCC/Clang. Unfortunately there
770 * doesn't seem to be a macro defined for /Os under MSVC.
771 */
772#ifndef MPACK_OPTIMIZE_FOR_SIZE
773 #ifdef __OPTIMIZE_SIZE__
774 #define MPACK_OPTIMIZE_FOR_SIZE 1
775 #else
776 #define MPACK_OPTIMIZE_FOR_SIZE 0
777 #endif
778#endif
779
780/**
781 * Stack space in bytes to use when initializing a reader or writer
782 * with a stack-allocated buffer.
783 *
784 * @warning Make sure you have sufficient stack space. Some libc use relatively
785 * small stacks even on desktop platforms, e.g. musl.
786 */
787#ifndef MPACK_STACK_SIZE
788#define MPACK_STACK_SIZE 4096
789#endif
790
791/**
792 * Buffer size to use for allocated buffers (such as for a file writer.)
793 *
794 * Starting with a single page and growing as needed seems to
795 * provide the best performance with minimal memory waste.
796 * Increasing this does not improve performance even when writing
797 * huge messages.
798 */
799#ifndef MPACK_BUFFER_SIZE
800#define MPACK_BUFFER_SIZE 4096
801#endif
802
803/**
804 * Minimum size for paged allocations in bytes.
805 *
806 * This is the value used by default for MPACK_NODE_PAGE_SIZE and
807 * MPACK_BUILDER_PAGE_SIZE.
808 */
809#ifndef MPACK_PAGE_SIZE
810#define MPACK_PAGE_SIZE 4096
811#endif
812
813/**
814 * Minimum size of an allocated node page in bytes.
815 *
816 * The children for a given compound element must be contiguous, so
817 * larger pages than this may be allocated as needed. (Safety checks
818 * exist to prevent malicious data from causing too large allocations.)
819 *
820 * See @ref mpack_node_data_t for the size of nodes.
821 *
822 * Using as many nodes fit in one memory page seems to provide the
823 * best performance, and has very little waste when parsing small
824 * messages.
825 */
826#ifndef MPACK_NODE_PAGE_SIZE
827#define MPACK_NODE_PAGE_SIZE MPACK_PAGE_SIZE
828#endif
829
830/**
831 * Minimum size of an allocated builder page in bytes.
832 *
833 * Builder writes are deferred to the allocated builder buffer which is
834 * composed of a list of buffer pages. This defines the size of those pages.
835 */
836#ifndef MPACK_BUILDER_PAGE_SIZE
837#define MPACK_BUILDER_PAGE_SIZE MPACK_PAGE_SIZE
838#endif
839
840/**
841 * @def MPACK_BUILDER_INTERNAL_STORAGE
842 *
843 * Enables a small amount of internal storage within the writer to avoid some
844 * allocations when using builders.
845 *
846 * This is disabled by default. Enable it to potentially improve performance at
847 * the expense of a larger writer.
848 *
849 * @see MPACK_BUILDER_INTERNAL_STORAGE_SIZE to configure its size.
850 */
851#ifndef MPACK_BUILDER_INTERNAL_STORAGE
852#define MPACK_BUILDER_INTERNAL_STORAGE 0
853#endif
854
855/**
856 * Amount of space reserved inside @ref mpack_writer_t for the Builders. This
857 * can allow small messages to be built with the Builder API without incurring
858 * an allocation.
859 *
860 * Builder metadata is placed in this space in addition to the literal
861 * MessagePack data. It needs to be big enough to be useful, but not so big as
862 * to overflow the stack. If more space is needed, pages are allocated.
863 *
864 * This is only used if MPACK_BUILDER_INTERNAL_STORAGE is enabled.
865 *
866 * @see MPACK_BUILDER_PAGE_SIZE
867 * @see MPACK_BUILDER_INTERNAL_STORAGE
868 *
869 * @warning Writers are typically placed on the stack so make sure you have
870 * sufficient stack space. Some libc use relatively small stacks even on
871 * desktop platforms, e.g. musl.
872 */
873#ifndef MPACK_BUILDER_INTERNAL_STORAGE_SIZE
874#define MPACK_BUILDER_INTERNAL_STORAGE_SIZE 256
875#endif
876
877/**
878 * The initial depth for the node parser. When MPACK_MALLOC is available,
879 * the node parser has no practical depth limit, and it is not recursive
880 * so there is no risk of overflowing the call stack.
881 */
882#ifndef MPACK_NODE_INITIAL_DEPTH
883#define MPACK_NODE_INITIAL_DEPTH 8
884#endif
885
886/**
887 * The maximum depth for the node parser if @ref MPACK_MALLOC is not available.
888 */
889#ifndef MPACK_NODE_MAX_DEPTH_WITHOUT_MALLOC
890#define MPACK_NODE_MAX_DEPTH_WITHOUT_MALLOC 32
891#endif
892
893/**
894 * @def MPACK_NO_BUILTINS
895 *
896 * Whether to disable compiler intrinsics and other built-in functions.
897 *
898 * If this is enabled, MPack won't use `__attribute__`, `__declspec`, any
899 * function starting with `__builtin`, or pretty much anything else that isn't
900 * standard C.
901 */
902#if defined(MPACK_DOXYGEN)
903#if MPACK_DOXYGEN
904 #define MPACK_NO_BUILTINS 0
905#endif
906#endif
907
908/**
909 * @}
910 */
911
912
913
914#if MPACK_DEBUG
915/**
916 * @name Debug Functions
917 * @{
918 */
919/**
920 * Implement this and define @ref MPACK_CUSTOM_ASSERT to use a custom
921 * assertion function.
922 *
923 * This function should not return. If it does, MPack will @c abort().
924 *
925 * If you use C++, make sure you include @c mpack.h where you define
926 * this to get the correct linkage (or define it <code>extern "C"</code>.)
927 *
928 * Asserts are only used when @ref MPACK_DEBUG is enabled, and can be
929 * triggered by bugs in MPack or bugs due to incorrect usage of MPack.
930 */
931void mpack_assert_fail(const char* message);
932/**
933 * @}
934 */
935#endif
936
937
938
939// The rest of this file shouldn't show up in Doxygen docs.
940/** @cond */
941
942
943
944/*
945 * All remaining pseudo-configuration options that have not yet been set must
946 * be defined here in order to support -Wundef.
947 *
948 * These aren't real configuration options; they are implementation details of
949 * MPack.
950 */
951#ifndef MPACK_CUSTOM_BREAK
952#define MPACK_CUSTOM_BREAK 0
953#endif
954#ifndef MPACK_EMIT_INLINE_DEFS
955#define MPACK_EMIT_INLINE_DEFS 0
956#endif
957#ifndef MPACK_AMALGAMATED
958#define MPACK_AMALGAMATED 0
959#endif
960#ifndef MPACK_RELEASE_VERSION
961#define MPACK_RELEASE_VERSION 0
962#endif
963#ifndef MPACK_INTERNAL
964#define MPACK_INTERNAL 0
965#endif
966
967
968
969/* System headers (based on configuration) */
970
971#if MPACK_CONFORMING
972 #include <stddef.h>
973 #include <stdint.h>
974 #include <stdbool.h>
975 #include <inttypes.h>
976 #include <limits.h>
977#endif
978
979#if MPACK_STDLIB
980 #include <string.h>
981 #include <stdlib.h>
982#endif
983
984#if MPACK_STDIO
985 #include <stdio.h>
986 #include <errno.h>
987 #if MPACK_DEBUG
988 #include <stdarg.h>
989 #endif
990#endif
991
992
993
994/*
995 * Integer Constants and Limits
996 */
997
998#if MPACK_CONFORMING
999 #define MPACK_INT64_C INT64_C
1000 #define MPACK_UINT64_C UINT64_C
1001
1002 #define MPACK_INT8_MIN INT8_MIN
1003 #define MPACK_INT16_MIN INT16_MIN
1004 #define MPACK_INT32_MIN INT32_MIN
1005 #define MPACK_INT64_MIN INT64_MIN
1006 #define MPACK_INT_MIN INT_MIN
1007
1008 #define MPACK_INT8_MAX INT8_MAX
1009 #define MPACK_INT16_MAX INT16_MAX
1010 #define MPACK_INT32_MAX INT32_MAX
1011 #define MPACK_INT64_MAX INT64_MAX
1012 #define MPACK_INT_MAX INT_MAX
1013
1014 #define MPACK_UINT8_MAX UINT8_MAX
1015 #define MPACK_UINT16_MAX UINT16_MAX
1016 #define MPACK_UINT32_MAX UINT32_MAX
1017 #define MPACK_UINT64_MAX UINT64_MAX
1018 #define MPACK_UINT_MAX UINT_MAX
1019#else
1020 // For a non-conforming implementation we assume int is 32 bits.
1021
1022 #define MPACK_INT64_C(x) ((int64_t)(x##LL))
1023 #define MPACK_UINT64_C(x) ((uint64_t)(x##LLU))
1024
1025 #define MPACK_INT8_MIN ((int8_t)(0x80))
1026 #define MPACK_INT16_MIN ((int16_t)(0x8000))
1027 #define MPACK_INT32_MIN ((int32_t)(0x80000000))
1028 #define MPACK_INT64_MIN MPACK_INT64_C(0x8000000000000000)
1029 #define MPACK_INT_MIN MPACK_INT32_MIN
1030
1031 #define MPACK_INT8_MAX ((int8_t)(0x7f))
1032 #define MPACK_INT16_MAX ((int16_t)(0x7fff))
1033 #define MPACK_INT32_MAX ((int32_t)(0x7fffffff))
1034 #define MPACK_INT64_MAX MPACK_INT64_C(0x7fffffffffffffff)
1035 #define MPACK_INT_MAX MPACK_INT32_MAX
1036
1037 #define MPACK_UINT8_MAX ((uint8_t)(0xffu))
1038 #define MPACK_UINT16_MAX ((uint16_t)(0xffffu))
1039 #define MPACK_UINT32_MAX ((uint32_t)(0xffffffffu))
1040 #define MPACK_UINT64_MAX MPACK_UINT64_C(0xffffffffffffffff)
1041 #define MPACK_UINT_MAX MPACK_UINT32_MAX
1042#endif
1043
1044
1045
1046/*
1047 * Floating point support
1048 */
1049
1050#if MPACK_DOUBLE && !MPACK_FLOAT
1051 #error "MPACK_DOUBLE requires MPACK_FLOAT."
1052#endif
1053
1054// If we don't have support for float or double, we poison the identifiers to
1055// make sure we don't define anything related to them.
1056#if MPACK_INTERNAL
1057 #ifdef __GNUC__
1058 #if !MPACK_FLOAT
1059 #pragma GCC poison float
1060 #endif
1061 #if !MPACK_DOUBLE
1062 #pragma GCC poison double
1063 #endif
1064 #endif
1065#endif
1066
1067
1068
1069/*
1070 * extern C
1071 */
1072
1073#ifdef __cplusplus
1074 #define MPACK_EXTERN_C_BEGIN namespace mpack {
1075 #define MPACK_EXTERN_C_END }
1076#else
1077 #define MPACK_EXTERN_C_BEGIN /*nothing*/
1078 #define MPACK_EXTERN_C_END /*nothing*/
1079#endif
1080
1081
1082
1083/*
1084 * Warnings
1085 */
1086
1087#if defined(__GNUC__)
1088 // Diagnostic push is not supported before GCC 4.6.
1089 #if defined(__clang__) || __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
1090 #define MPACK_SILENCE_WARNINGS_PUSH _Pragma ("GCC diagnostic push")
1091 #define MPACK_SILENCE_WARNINGS_POP _Pragma ("GCC diagnostic pop")
1092 #endif
1093#elif defined(_MSC_VER)
1094 // To support VS2017 and earlier we need to use __pragma and not _Pragma
1095 #define MPACK_SILENCE_WARNINGS_PUSH __pragma(warning(push))
1096 #define MPACK_SILENCE_WARNINGS_POP __pragma(warning(pop))
1097#endif
1098
1099#if defined(_MSC_VER)
1100 // These are a bunch of mostly useless warnings emitted under MSVC /W4,
1101 // some as a result of the expansion of macros.
1102 #define MPACK_SILENCE_WARNINGS_MSVC_W4 \
1103 __pragma(warning(disable:4996)) /* _CRT_SECURE_NO_WARNINGS */ \
1104 __pragma(warning(disable:4127)) /* comparison is constant */ \
1105 __pragma(warning(disable:4702)) /* unreachable code */ \
1106 __pragma(warning(disable:4310)) /* cast truncates constant value */
1107#else
1108 #define MPACK_SILENCE_WARNINGS_MSVC_W4 /*nothing*/
1109#endif
1110
1111/* GCC versions before 5.1 warn about defining a C99 non-static inline function
1112 * before declaring it (see issue #20). */
1113#if defined(__GNUC__) && !defined(__clang__)
1114 #if __GNUC__ < 5 || (__GNUC__ == 5 && __GNUC_MINOR__ < 1)
1115 #ifdef __cplusplus
1116 #define MPACK_SILENCE_WARNINGS_MISSING_PROTOTYPES \
1117 _Pragma ("GCC diagnostic ignored \"-Wmissing-declarations\"")
1118 #else
1119 #define MPACK_SILENCE_WARNINGS_MISSING_PROTOTYPES \
1120 _Pragma ("GCC diagnostic ignored \"-Wmissing-prototypes\"")
1121 #endif
1122 #endif
1123#endif
1124#ifndef MPACK_SILENCE_WARNINGS_MISSING_PROTOTYPES
1125 #define MPACK_SILENCE_WARNINGS_MISSING_PROTOTYPES /*nothing*/
1126#endif
1127
1128/* GCC versions before 4.8 warn about shadowing a function with a variable that
1129 * isn't a function or function pointer (like "index"). */
1130#if defined(__GNUC__) && !defined(__clang__)
1131 #if __GNUC__ == 4 && __GNUC_MINOR__ < 8
1132 #define MPACK_SILENCE_WARNINGS_SHADOW \
1133 _Pragma ("GCC diagnostic ignored \"-Wshadow\"")
1134 #endif
1135#endif
1136#ifndef MPACK_SILENCE_WARNINGS_SHADOW
1137 #define MPACK_SILENCE_WARNINGS_SHADOW /*nothing*/
1138#endif
1139
1140// On platforms with small size_t (e.g. AVR) we get type limits warnings where
1141// we compare a size_t to e.g. MPACK_UINT32_MAX.
1142#ifdef __AVR__
1143 #define MPACK_SILENCE_WARNINGS_TYPE_LIMITS \
1144 _Pragma ("GCC diagnostic ignored \"-Wtype-limits\"")
1145#else
1146 #define MPACK_SILENCE_WARNINGS_TYPE_LIMITS /*nothing*/
1147#endif
1148
1149// MPack uses declarations after statements. This silences warnings about it
1150// (e.g. when using MPack in a Linux kernel module.)
1151#if defined(__GNUC__) && !defined(__cplusplus)
1152 #define MPACK_SILENCE_WARNINGS_DECLARATION_AFTER_STATEMENT \
1153 _Pragma ("GCC diagnostic ignored \"-Wdeclaration-after-statement\"")
1154#else
1155 #define MPACK_SILENCE_WARNINGS_DECLARATION_AFTER_STATEMENT /*nothing*/
1156#endif
1157
1158#ifdef MPACK_SILENCE_WARNINGS_PUSH
1159 // We only silence warnings if push/pop is supported, that way we aren't
1160 // silencing warnings in code that uses MPack. If your compiler doesn't
1161 // support push/pop silencing of warnings, you'll have to turn off
1162 // conflicting warnings manually.
1163
1164 #define MPACK_SILENCE_WARNINGS_BEGIN \
1165 MPACK_SILENCE_WARNINGS_PUSH \
1166 MPACK_SILENCE_WARNINGS_MSVC_W4 \
1167 MPACK_SILENCE_WARNINGS_MISSING_PROTOTYPES \
1168 MPACK_SILENCE_WARNINGS_SHADOW \
1169 MPACK_SILENCE_WARNINGS_TYPE_LIMITS \
1170 MPACK_SILENCE_WARNINGS_DECLARATION_AFTER_STATEMENT
1171
1172 #define MPACK_SILENCE_WARNINGS_END \
1173 MPACK_SILENCE_WARNINGS_POP
1174#else
1175 #define MPACK_SILENCE_WARNINGS_BEGIN /*nothing*/
1176 #define MPACK_SILENCE_WARNINGS_END /*nothing*/
1177#endif
1178
1179MPACK_SILENCE_WARNINGS_BEGIN
1180MPACK_EXTERN_C_BEGIN
1181
1182
1183
1184/* Miscellaneous helper macros */
1185
1186#define MPACK_UNUSED(var) ((void)(var))
1187
1188#define MPACK_STRINGIFY_IMPL(arg) #arg
1189#define MPACK_STRINGIFY(arg) MPACK_STRINGIFY_IMPL(arg)
1190
1191// This is a workaround for MSVC's incorrect expansion of __VA_ARGS__. It
1192// treats __VA_ARGS__ as a single preprocessor token when passed in the
1193// argument list of another macro unless we use an outer wrapper to expand it
1194// lexically first. (For safety/consistency we use this in all variadic macros
1195// that don't ignore the variadic arguments regardless of whether __VA_ARGS__
1196// is passed to another macro.)
1197// https://stackoverflow.com/a/32400131
1198#define MPACK_EXPAND(x) x
1199
1200// Extracts the first argument of a variadic macro list, where there might only
1201// be one argument.
1202#define MPACK_EXTRACT_ARG0_IMPL(first, ...) first
1203#define MPACK_EXTRACT_ARG0(...) MPACK_EXPAND(MPACK_EXTRACT_ARG0_IMPL( __VA_ARGS__ , ignored))
1204
1205// Stringifies the first argument of a variadic macro list, where there might
1206// only be one argument.
1207#define MPACK_STRINGIFY_ARG0_impl(first, ...) #first
1208#define MPACK_STRINGIFY_ARG0(...) MPACK_EXPAND(MPACK_STRINGIFY_ARG0_impl( __VA_ARGS__ , ignored))
1209
1210
1211
1212/*
1213 * Definition of inline macros.
1214 *
1215 * MPack does not use static inline in header files; only one non-inline definition
1216 * of each function should exist in the final build. This can reduce the binary size
1217 * in cases where the compiler cannot or chooses not to inline a function.
1218 * The addresses of functions should also compare equal across translation units
1219 * regardless of whether they are declared inline.
1220 *
1221 * The above requirements mean that the declaration and definition of non-trivial
1222 * inline functions must be separated so that the definitions will only
1223 * appear when necessary. In addition, three different linkage models need
1224 * to be supported:
1225 *
1226 * - The C99 model, where a standalone function is emitted only if there is any
1227 * `extern inline` or non-`inline` declaration (including the definition itself)
1228 *
1229 * - The GNU model, where an `inline` definition emits a standalone function and an
1230 * `extern inline` definition does not, regardless of other declarations
1231 *
1232 * - The C++ model, where `inline` emits a standalone function with special
1233 * (COMDAT) linkage
1234 *
1235 * The macros below wrap up everything above. All inline functions defined in header
1236 * files have a single non-inline definition emitted in the compilation of
1237 * mpack-platform.c. All inline declarations and definitions use the same MPACK_INLINE
1238 * specification to simplify the rules on when standalone functions are emitted.
1239 * Inline functions in source files are defined MPACK_STATIC_INLINE.
1240 *
1241 * Additional reading:
1242 * http://www.greenend.org.uk/rjk/tech/inline.html
1243 */
1244
1245#if defined(__cplusplus)
1246 // C++ rules
1247 // The linker will need COMDAT support to link C++ object files,
1248 // so we don't need to worry about emitting definitions from C++
1249 // translation units. If mpack-platform.c (or the amalgamation)
1250 // is compiled as C, its definition will be used, otherwise a
1251 // C++ definition will be used, and no other C files will emit
1252 // a definition.
1253 #define MPACK_INLINE inline
1254
1255#elif defined(_MSC_VER)
1256 // MSVC 2013 always uses COMDAT linkage, but it doesn't treat 'inline' as a
1257 // keyword in C99 mode. (This appears to be fixed in a later version of
1258 // MSVC but we don't bother detecting it.)
1259 #define MPACK_INLINE __inline
1260 #define MPACK_STATIC_INLINE static __inline
1261
1262#elif defined(__GNUC__) && (defined(__GNUC_GNU_INLINE__) || \
1263 (!defined(__GNUC_STDC_INLINE__) && !defined(__GNUC_GNU_INLINE__)))
1264 // GNU rules
1265 #if MPACK_EMIT_INLINE_DEFS
1266 #define MPACK_INLINE inline
1267 #else
1268 #define MPACK_INLINE extern inline
1269 #endif
1270
1271#elif defined(__TINYC__)
1272 // tcc ignores the inline keyword, so we have to use static inline. We
1273 // issue a warning to make sure you are aware. You can define the below
1274 // macro to disable the warning. Hopefully this will be fixed soon:
1275 // https://lists.nongnu.org/archive/html/tinycc-devel/2019-06/msg00000.html
1276 #ifndef MPACK_DISABLE_TINYC_INLINE_WARNING
1277 #warning "Single-definition inline is not supported by tcc. All inlines will be static. Define MPACK_DISABLE_TINYC_INLINE_WARNING to disable this warning."
1278 #endif
1279 #define MPACK_INLINE static inline
1280
1281#else
1282 // C99 rules
1283 #if MPACK_EMIT_INLINE_DEFS
1284 #define MPACK_INLINE extern inline
1285 #else
1286 #define MPACK_INLINE inline
1287 #endif
1288#endif
1289
1290#ifndef MPACK_STATIC_INLINE
1291#define MPACK_STATIC_INLINE static inline
1292#endif
1293
1294#ifdef MPACK_OPTIMIZE_FOR_SPEED
1295 #error "You should define MPACK_OPTIMIZE_FOR_SIZE, not MPACK_OPTIMIZE_FOR_SPEED."
1296#endif
1297
1298
1299
1300/*
1301 * Prevent inlining
1302 *
1303 * When a function is only used once, it is almost always inlined
1304 * automatically. This can cause poor instruction cache usage because a
1305 * function that should rarely be called (such as buffer exhaustion handling)
1306 * will get inlined into the middle of a hot code path.
1307 */
1308
1309#if !MPACK_NO_BUILTINS
1310 #if defined(_MSC_VER)
1311 #define MPACK_NOINLINE __declspec(noinline)
1312 #elif defined(__GNUC__) || defined(__clang__)
1313 #define MPACK_NOINLINE __attribute__((__noinline__))
1314 #endif
1315#endif
1316#ifndef MPACK_NOINLINE
1317 #define MPACK_NOINLINE /* nothing */
1318#endif
1319
1320
1321
1322/* restrict */
1323
1324// We prefer the builtins even though e.g. MSVC's __restrict may not have
1325// exactly the same behaviour as the proper C99 restrict keyword because the
1326// builtins work in C++, so using the same keyword in both C and C++ prevents
1327// any incompatibilities when using MPack compiled as C in C++ code.
1328#if !MPACK_NO_BUILTINS
1329 #if defined(__GNUC__)
1330 #define MPACK_RESTRICT __restrict__
1331 #elif defined(_MSC_VER)
1332 #define MPACK_RESTRICT __restrict
1333 #endif
1334#endif
1335
1336#ifndef MPACK_RESTRICT
1337 #ifdef __cplusplus
1338 #define MPACK_RESTRICT /* nothing, unavailable in C++ */
1339 #endif
1340#endif
1341
1342#ifndef MPACK_RESTRICT
1343 #ifdef _MSC_VER
1344 // MSVC 2015 apparently doesn't properly support the restrict keyword
1345 // in C. We're using builtins above which do work on 2015, but when
1346 // MPACK_NO_BUILTINS is enabled we can't use it.
1347 #if _MSC_VER < 1910
1348 #define MPACK_RESTRICT /*nothing*/
1349 #endif
1350 #endif
1351#endif
1352
1353#ifndef MPACK_RESTRICT
1354 #define MPACK_RESTRICT restrict /* required in C99 */
1355#endif
1356
1357
1358
1359/* Some compiler-specific keywords and builtins */
1360
1361#if !MPACK_NO_BUILTINS
1362 #if defined(__GNUC__) || defined(__clang__)
1363 #define MPACK_UNREACHABLE __builtin_unreachable()
1364 #define MPACK_NORETURN(fn) fn __attribute__((__noreturn__))
1365 #elif defined(_MSC_VER)
1366 #define MPACK_UNREACHABLE __assume(0)
1367 #define MPACK_NORETURN(fn) __declspec(noreturn) fn
1368 #endif
1369#endif
1370
1371#ifndef MPACK_UNREACHABLE
1372#define MPACK_UNREACHABLE ((void)0)
1373#endif
1374#ifndef MPACK_NORETURN
1375#define MPACK_NORETURN(fn) fn
1376#endif
1377
1378
1379
1380/*
1381 * Likely/unlikely
1382 *
1383 * These should only really be used when a branch is taken (or not taken) less
1384 * than 1/1000th of the time. Buffer flush checks when writing very small
1385 * elements are a good example.
1386 */
1387
1388#if !MPACK_NO_BUILTINS
1389 #if defined(__GNUC__) || defined(__clang__)
1390 #ifndef MPACK_LIKELY
1391 #define MPACK_LIKELY(x) __builtin_expect((x),1)
1392 #endif
1393 #ifndef MPACK_UNLIKELY
1394 #define MPACK_UNLIKELY(x) __builtin_expect((x),0)
1395 #endif
1396 #endif
1397#endif
1398
1399#ifndef MPACK_LIKELY
1400 #define MPACK_LIKELY(x) (x)
1401#endif
1402#ifndef MPACK_UNLIKELY
1403 #define MPACK_UNLIKELY(x) (x)
1404#endif
1405
1406
1407
1408/* alignof */
1409
1410#ifndef MPACK_ALIGNOF
1411 #if defined(__STDC_VERSION__)
1412 #if __STDC_VERSION__ >= 201112L
1413 #define MPACK_ALIGNOF(T) (_Alignof(T))
1414 #endif
1415 #endif
1416#endif
1417
1418#ifndef MPACK_ALIGNOF
1419 #if defined(__cplusplus)
1420 #if __cplusplus >= 201103L
1421 #define MPACK_ALIGNOF(T) (alignof(T))
1422 #endif
1423 #endif
1424#endif
1425
1426#ifndef MPACK_ALIGNOF
1427 #if defined(__GNUC__) && !defined(MPACK_NO_BUILTINS)
1428 #if defined(__clang__) || __GNUC__ >= 4
1429 #define MPACK_ALIGNOF(T) (__alignof__(T))
1430 #endif
1431 #endif
1432#endif
1433
1434#ifndef MPACK_ALIGNOF
1435 #ifdef _MSC_VER
1436 #define MPACK_ALIGNOF(T) __alignof(T)
1437 #endif
1438#endif
1439
1440// MPACK_ALIGNOF may not exist, in which case a workaround is used.
1441
1442
1443
1444/* Static assert */
1445
1446#ifndef MPACK_STATIC_ASSERT
1447 #if defined(__cplusplus)
1448 #if __cplusplus >= 201103L
1449 #define MPACK_STATIC_ASSERT static_assert
1450 #endif
1451 #elif defined(__STDC_VERSION__)
1452 #if __STDC_VERSION__ >= 201112L
1453 #define MPACK_STATIC_ASSERT _Static_assert
1454 #endif
1455 #endif
1456#endif
1457
1458#if !MPACK_NO_BUILTINS
1459 #ifndef MPACK_STATIC_ASSERT
1460 #if defined(__has_feature)
1461 #if __has_feature(cxx_static_assert)
1462 #define MPACK_STATIC_ASSERT static_assert
1463 #elif __has_feature(c_static_assert)
1464 #define MPACK_STATIC_ASSERT _Static_assert
1465 #endif
1466 #endif
1467 #endif
1468
1469 #ifndef MPACK_STATIC_ASSERT
1470 #if defined(__GNUC__)
1471 /* Diagnostic push is not supported before GCC 4.6. */
1472 #if defined(__clang__) || __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
1473 #ifndef __cplusplus
1474 #if defined(__clang__) || __GNUC__ >= 5
1475 #define MPACK_IGNORE_PEDANTIC "GCC diagnostic ignored \"-Wpedantic\""
1476 #else
1477 #define MPACK_IGNORE_PEDANTIC "GCC diagnostic ignored \"-pedantic\""
1478 #endif
1479 #define MPACK_STATIC_ASSERT(expr, str) do { \
1480 _Pragma ("GCC diagnostic push") \
1481 _Pragma (MPACK_IGNORE_PEDANTIC) \
1482 _Pragma ("GCC diagnostic ignored \"-Wc++-compat\"") \
1483 _Static_assert(expr, str); \
1484 _Pragma ("GCC diagnostic pop") \
1485 } while (0)
1486 #endif
1487 #endif
1488 #endif
1489 #endif
1490
1491 #ifndef MPACK_STATIC_ASSERT
1492 #ifdef _MSC_VER
1493 #if _MSC_VER >= 1600
1494 #define MPACK_STATIC_ASSERT static_assert
1495 #endif
1496 #endif
1497 #endif
1498#endif
1499
1500#ifndef MPACK_STATIC_ASSERT
1501 #define MPACK_STATIC_ASSERT(expr, str) (MPACK_UNUSED(sizeof(char[1 - 2*!(expr)])))
1502#endif
1503
1504
1505
1506/* _Generic */
1507
1508#ifndef MPACK_HAS_GENERIC
1509 #if defined(__clang__) && defined(__has_feature)
1510 // With Clang we can test for _Generic support directly
1511 // and ignore C/C++ version
1512 #if __has_feature(c_generic_selections)
1513 #define MPACK_HAS_GENERIC 1
1514 #else
1515 #define MPACK_HAS_GENERIC 0
1516 #endif
1517 #endif
1518#endif
1519
1520#ifndef MPACK_HAS_GENERIC
1521 #if defined(__STDC_VERSION__)
1522 #if __STDC_VERSION__ >= 201112L
1523 #if defined(__GNUC__) && !defined(__clang__)
1524 // GCC does not have full C11 support in GCC 4.7 and 4.8
1525 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9)
1526 #define MPACK_HAS_GENERIC 1
1527 #endif
1528 #else
1529 // We hope other compilers aren't lying about C11/_Generic support
1530 #define MPACK_HAS_GENERIC 1
1531 #endif
1532 #endif
1533 #endif
1534#endif
1535
1536#ifndef MPACK_HAS_GENERIC
1537 #define MPACK_HAS_GENERIC 0
1538#endif
1539
1540
1541
1542/*
1543 * Finite Math
1544 *
1545 * -ffinite-math-only, included in -ffast-math, breaks functions that
1546 * that check for non-finite real values such as isnan() and isinf().
1547 *
1548 * We should use this to trap errors when reading data that contains
1549 * non-finite reals. This isn't currently implemented.
1550 */
1551
1552#ifndef MPACK_FINITE_MATH
1553#if defined(__FINITE_MATH_ONLY__) && __FINITE_MATH_ONLY__
1554#define MPACK_FINITE_MATH 1
1555#endif
1556#endif
1557
1558#ifndef MPACK_FINITE_MATH
1559#define MPACK_FINITE_MATH 0
1560#endif
1561
1562
1563
1564/*
1565 * Endianness checks
1566 *
1567 * These define MPACK_NHSWAP*() which swap network<->host byte
1568 * order when needed.
1569 *
1570 * We leave them undefined if we can't determine the endianness
1571 * at compile-time, in which case we fall back to bit-shifts.
1572 *
1573 * See the notes in mpack-common.h.
1574 */
1575
1576#if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && defined(__ORDER_BIG_ENDIAN__)
1577 #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1578 #define MPACK_NHSWAP16(x) (x)
1579 #define MPACK_NHSWAP32(x) (x)
1580 #define MPACK_NHSWAP64(x) (x)
1581 #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1582
1583 #if !MPACK_NO_BUILTINS
1584 #if defined(__clang__)
1585 #ifdef __has_builtin
1586 // Unlike the GCC builtins, the bswap builtins in Clang
1587 // significantly improve ARM performance.
1588 #if __has_builtin(__builtin_bswap16)
1589 #define MPACK_NHSWAP16(x) __builtin_bswap16(x)
1590 #endif
1591 #if __has_builtin(__builtin_bswap32)
1592 #define MPACK_NHSWAP32(x) __builtin_bswap32(x)
1593 #endif
1594 #if __has_builtin(__builtin_bswap64)
1595 #define MPACK_NHSWAP64(x) __builtin_bswap64(x)
1596 #endif
1597 #endif
1598
1599 #elif defined(__GNUC__)
1600
1601 // The GCC bswap builtins are apparently poorly optimized on older
1602 // versions of GCC, so we set a minimum version here just in case.
1603 // http://hardwarebug.org/2010/01/14/beware-the-builtins/
1604
1605 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)
1606 #define MPACK_NHSWAP64(x) __builtin_bswap64(x)
1607 #endif
1608
1609 // __builtin_bswap16() was not implemented on all platforms
1610 // until GCC 4.8.0:
1611 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52624
1612 //
1613 // The 16- and 32-bit versions in GCC significantly reduce performance
1614 // on ARM with little effect on code size so we don't use them.
1615
1616 #endif
1617 #endif
1618 #endif
1619
1620#elif defined(_MSC_VER) && defined(_WIN32) && MPACK_STDLIB && !MPACK_NO_BUILTINS
1621
1622 // On Windows, we assume x86 and x86_64 are always little-endian.
1623 // We make no assumptions about ARM even though all current
1624 // Windows Phone devices are little-endian in case Microsoft's
1625 // compiler is ever used with a big-endian ARM device.
1626
1627 // These are functions in <stdlib.h> so we depend on MPACK_STDLIB.
1628 // It's not clear if these are actually faster than just doing the
1629 // swap manually; maybe we shouldn't bother with this.
1630
1631 #if defined(_M_IX86) || defined(_M_X64) || defined(_M_AMD64)
1632 #define MPACK_NHSWAP16(x) _byteswap_ushort(x)
1633 #define MPACK_NHSWAP32(x) _byteswap_ulong(x)
1634 #define MPACK_NHSWAP64(x) _byteswap_uint64(x)
1635 #endif
1636
1637#endif
1638
1639#if defined(__FLOAT_WORD_ORDER__) && defined(__BYTE_ORDER__)
1640
1641 // We check where possible that the float byte order matches the
1642 // integer byte order. This is extremely unlikely to fail, but
1643 // we check anyway just in case.
1644 //
1645 // (The static assert is placed in float/double encoders instead
1646 // of here because our static assert fallback doesn't work at
1647 // file scope)
1648
1649 #define MPACK_CHECK_FLOAT_ORDER() \
1650 MPACK_STATIC_ASSERT(__FLOAT_WORD_ORDER__ == __BYTE_ORDER__, \
1651 "float byte order does not match int byte order! float/double " \
1652 "encoding is not properly implemented on this platform.")
1653
1654#endif
1655
1656#ifndef MPACK_CHECK_FLOAT_ORDER
1657 #define MPACK_CHECK_FLOAT_ORDER() /* nothing */
1658#endif
1659
1660
1661/*
1662 * Here we define mpack_assert() and mpack_break(). They both work like a normal
1663 * assertion function in debug mode, causing a trap or abort. However, on some platforms
1664 * you can safely resume execution from mpack_break(), whereas mpack_assert() is
1665 * always fatal.
1666 *
1667 * In release mode, mpack_assert() is converted to an assurance to the compiler
1668 * that the expression cannot be false (via e.g. __assume() or __builtin_unreachable())
1669 * to improve optimization where supported. There is thus no point in "safely" handling
1670 * the case of this being false. Writing mpack_assert(0) rarely makes sense (except
1671 * possibly as a default handler in a switch) since the compiler will throw away any
1672 * code after it. If at any time an mpack_assert() is not true, the behaviour is
1673 * undefined. This also means the expression is evaluated even in release.
1674 *
1675 * mpack_break() on the other hand is compiled to nothing in release. It is
1676 * used in situations where we want to highlight a programming error as early as
1677 * possible (in the debugger), but we still handle the situation safely if it
1678 * happens in release to avoid producing incorrect results (such as in
1679 * MPACK_WRITE_TRACKING.) It does not take an expression to test because it
1680 * belongs in a safe-handling block after its failing condition has been tested.
1681 *
1682 * If stdio is available, we can add a format string describing the error, and
1683 * on some compilers we can declare it noreturn to get correct results from static
1684 * analysis tools. Note that the format string and arguments are not evaluated unless
1685 * the assertion is hit.
1686 *
1687 * Note that any arguments to mpack_assert() beyond the first are only evaluated
1688 * if the expression is false (and are never evaluated in release.)
1689 *
1690 * mpack_assert_fail() and mpack_break_hit() are defined separately
1691 * because assert is noreturn and break isn't. This distinction is very
1692 * important for static analysis tools to give correct results.
1693 */
1694
1695#if MPACK_DEBUG
1696 MPACK_NORETURN(void mpack_assert_fail_wrapper(const char* message));
1697 #if MPACK_STDIO
1698 MPACK_NORETURN(void mpack_assert_fail_format(const char* format, ...));
1699 #define mpack_assert_fail_at(line, file, exprstr, format, ...) \
1700 MPACK_EXPAND(mpack_assert_fail_format("mpack assertion failed at " file ":" #line "\n%s\n" format, exprstr, __VA_ARGS__))
1701 #else
1702 #define mpack_assert_fail_at(line, file, exprstr, format, ...) \
1703 mpack_assert_fail_wrapper("mpack assertion failed at " file ":" #line "\n" exprstr "\n")
1704 #endif
1705
1706 #define mpack_assert_fail_pos(line, file, exprstr, expr, ...) \
1707 MPACK_EXPAND(mpack_assert_fail_at(line, file, exprstr, __VA_ARGS__))
1708
1709 // This contains a workaround to the pedantic C99 requirement of having at
1710 // least one argument to a variadic macro. The first argument is the
1711 // boolean expression, the optional second argument (if provided) must be a
1712 // literal format string, and any additional arguments are the format
1713 // argument list.
1714 //
1715 // Unfortunately this means macros are expanded in the expression before it
1716 // gets stringified. I haven't found a workaround to this.
1717 //
1718 // This adds two unused arguments to the format argument list when a
1719 // format string is provided, so this would complicate the use of
1720 // -Wformat and __attribute__((__format__)) on mpack_assert_fail_format()
1721 // if we ever bothered to implement it.
1722 #define mpack_assert(...) \
1723 MPACK_EXPAND(((!(MPACK_EXTRACT_ARG0(__VA_ARGS__))) ? \
1724 mpack_assert_fail_pos(__LINE__, __FILE__, MPACK_STRINGIFY_ARG0(__VA_ARGS__) , __VA_ARGS__ , "", NULL) : \
1725 (void)0))
1726
1727 void mpack_break_hit(const char* message);
1728 #if MPACK_STDIO
1729 void mpack_break_hit_format(const char* format, ...);
1730 #define mpack_break_hit_at(line, file, ...) \
1731 MPACK_EXPAND(mpack_break_hit_format("mpack breakpoint hit at " file ":" #line "\n" __VA_ARGS__))
1732 #else
1733 #define mpack_break_hit_at(line, file, ...) \
1734 mpack_break_hit("mpack breakpoint hit at " file ":" #line )
1735 #endif
1736 #define mpack_break_hit_pos(line, file, ...) MPACK_EXPAND(mpack_break_hit_at(line, file, __VA_ARGS__))
1737 #define mpack_break(...) MPACK_EXPAND(mpack_break_hit_pos(__LINE__, __FILE__, __VA_ARGS__))
1738#else
1739 #define mpack_assert(...) \
1740 (MPACK_EXPAND((!(MPACK_EXTRACT_ARG0(__VA_ARGS__))) ? \
1741 (MPACK_UNREACHABLE, (void)0) : \
1742 (void)0))
1743 #define mpack_break(...) ((void)0)
1744#endif
1745
1746
1747
1748// make sure we don't use the stdlib directly during development
1749#if MPACK_STDLIB && defined(MPACK_UNIT_TESTS) && MPACK_INTERNAL && defined(__GNUC__)
1750 #undef memcmp
1751 #undef memcpy
1752 #undef memmove
1753 #undef memset
1754 #undef strlen
1755 #undef malloc
1756 #undef calloc
1757 #undef realloc
1758 #undef free
1759 #pragma GCC poison memcmp
1760 #pragma GCC poison memcpy
1761 #pragma GCC poison memmove
1762 #pragma GCC poison memset
1763 #pragma GCC poison strlen
1764 #pragma GCC poison malloc
1765 #pragma GCC poison calloc
1766 #pragma GCC poison realloc
1767 #pragma GCC poison free
1768#endif
1769
1770
1771
1772// If we don't have these stdlib functions, we need to define them ourselves.
1773// Either way we give them a lowercase name to make the code a bit nicer.
1774
1775#ifdef MPACK_MEMCMP
1776 #define mpack_memcmp MPACK_MEMCMP
1777#else
1778 int mpack_memcmp(const void* s1, const void* s2, size_t n);
1779#endif
1780
1781#ifdef MPACK_MEMCPY
1782 #define mpack_memcpy MPACK_MEMCPY
1783#else
1784 void* mpack_memcpy(void* MPACK_RESTRICT s1, const void* MPACK_RESTRICT s2, size_t n);
1785#endif
1786
1787#ifdef MPACK_MEMMOVE
1788 #define mpack_memmove MPACK_MEMMOVE
1789#else
1790 void* mpack_memmove(void* s1, const void* s2, size_t n);
1791#endif
1792
1793#ifdef MPACK_MEMSET
1794 #define mpack_memset MPACK_MEMSET
1795#else
1796 void* mpack_memset(void* s, int c, size_t n);
1797#endif
1798
1799#ifdef MPACK_STRLEN
1800 #define mpack_strlen MPACK_STRLEN
1801#else
1802 size_t mpack_strlen(const char* s);
1803#endif
1804
1805
1806
1807#if MPACK_STDIO
1808 #if defined(WIN32)
1809 #define mpack_snprintf _snprintf
1810 #else
1811 #define mpack_snprintf snprintf
1812 #endif
1813#endif
1814
1815
1816
1817/* Debug logging */
1818#if 0
1819 #include <stdio.h>
1820 #define mpack_log(...) (MPACK_EXPAND(printf(__VA_ARGS__)), fflush(stdout))
1821#else
1822 #define mpack_log(...) ((void)0)
1823#endif
1824
1825
1826
1827/* Make sure our configuration makes sense */
1828#ifndef MPACK_MALLOC
1829 #if MPACK_STDIO
1830 #error "MPACK_STDIO requires preprocessor definitions for MPACK_MALLOC and MPACK_FREE."
1831 #endif
1832 #if MPACK_READ_TRACKING
1833 #error "MPACK_READ_TRACKING requires preprocessor definitions for MPACK_MALLOC and MPACK_FREE."
1834 #endif
1835 #if MPACK_WRITE_TRACKING
1836 #error "MPACK_WRITE_TRACKING requires preprocessor definitions for MPACK_MALLOC and MPACK_FREE."
1837 #endif
1838#endif
1839
1840
1841
1842/* Implement realloc if unavailable */
1843#ifdef MPACK_MALLOC
1844 #ifdef MPACK_REALLOC
1845 MPACK_INLINE void* mpack_realloc(void* old_ptr, size_t used_size, size_t new_size) {
1846 MPACK_UNUSED(used_size);
1847 return MPACK_REALLOC(old_ptr, new_size);
1848 }
1849 #else
1850 void* mpack_realloc(void* old_ptr, size_t used_size, size_t new_size);
1851 #endif
1852#endif
1853
1854
1855
1856/** @endcond */
1857/**
1858 * @}
1859 */
1860
1861MPACK_EXTERN_C_END
1862MPACK_SILENCE_WARNINGS_END
1863
1864#endif
1865
1866/* mpack/mpack-common.h.h */
1867
1868/**
1869 * @file
1870 *
1871 * Defines types and functions shared by the MPack reader and writer.
1872 */
1873
1874#ifndef MPACK_COMMON_H
1875#define MPACK_COMMON_H 1
1876
1877/* #include "mpack-platform.h" */
1878
1879#ifndef MPACK_PRINT_BYTE_COUNT
1880#define MPACK_PRINT_BYTE_COUNT 12
1881#endif
1882
1883MPACK_SILENCE_WARNINGS_BEGIN
1884MPACK_EXTERN_C_BEGIN
1885
1886
1887
1888/**
1889 * @defgroup mpack_common Tags and Common Elements
1890 * @ingroup mpack
1891 *
1892 * Contains types, constants and functions shared by both the encoding
1893 * and decoding portions of MPack.
1894 *
1895 * @{
1896 */
1897
1898/* Version information */
1899
1900#define MPACK_VERSION_MAJOR 1 /**< The major version number of MPack. */
1901#define MPACK_VERSION_MINOR 1 /**< The minor version number of MPack. */
1902#define MPACK_VERSION_PATCH 1 /**< The patch version number of MPack. */
1903
1904/** A number containing the version number of MPack for comparison purposes. */
1905#define MPACK_VERSION ((MPACK_VERSION_MAJOR * 10000) + \
1906 (MPACK_VERSION_MINOR * 100) + MPACK_VERSION_PATCH)
1907
1908/** A macro to test for a minimum version of MPack. */
1909#define MPACK_VERSION_AT_LEAST(major, minor, patch) \
1910 (MPACK_VERSION >= (((major) * 10000) + ((minor) * 100) + (patch)))
1911
1912/** @cond */
1913#if (MPACK_VERSION_PATCH > 0)
1914#define MPACK_VERSION_STRING_BASE \
1915 MPACK_STRINGIFY(MPACK_VERSION_MAJOR) "." \
1916 MPACK_STRINGIFY(MPACK_VERSION_MINOR) "." \
1917 MPACK_STRINGIFY(MPACK_VERSION_PATCH)
1918#else
1919#define MPACK_VERSION_STRING_BASE \
1920 MPACK_STRINGIFY(MPACK_VERSION_MAJOR) "." \
1921 MPACK_STRINGIFY(MPACK_VERSION_MINOR)
1922#endif
1923/** @endcond */
1924
1925/**
1926 * @def MPACK_VERSION_STRING
1927 * @hideinitializer
1928 *
1929 * A string containing the MPack version.
1930 */
1931#if MPACK_RELEASE_VERSION
1932#define MPACK_VERSION_STRING MPACK_VERSION_STRING_BASE
1933#else
1934#define MPACK_VERSION_STRING MPACK_VERSION_STRING_BASE "dev"
1935#endif
1936
1937/**
1938 * @def MPACK_LIBRARY_STRING
1939 * @hideinitializer
1940 *
1941 * A string describing MPack, containing the library name, version and debug mode.
1942 */
1943#if MPACK_DEBUG
1944#define MPACK_LIBRARY_STRING "MPack " MPACK_VERSION_STRING "-debug"
1945#else
1946#define MPACK_LIBRARY_STRING "MPack " MPACK_VERSION_STRING
1947#endif
1948
1949/** @cond */
1950/**
1951 * @def MPACK_MAXIMUM_TAG_SIZE
1952 *
1953 * The maximum encoded size of a tag in bytes.
1954 */
1955#define MPACK_MAXIMUM_TAG_SIZE 9
1956/** @endcond */
1957
1958#if MPACK_EXTENSIONS
1959/**
1960 * @def MPACK_TIMESTAMP_NANOSECONDS_MAX
1961 *
1962 * The maximum value of nanoseconds for a timestamp.
1963 *
1964 * @note This requires @ref MPACK_EXTENSIONS.
1965 */
1966#define MPACK_TIMESTAMP_NANOSECONDS_MAX 999999999
1967#endif
1968
1969
1970
1971#if MPACK_COMPATIBILITY
1972/**
1973 * Versions of the MessagePack format.
1974 *
1975 * A reader, writer, or tree can be configured to serialize in an older
1976 * version of the MessagePack spec. This is necessary to interface with
1977 * older MessagePack libraries that do not support new MessagePack features.
1978 *
1979 * @note This requires @ref MPACK_COMPATIBILITY.
1980 */
1981typedef enum mpack_version_t {
1982
1983 /**
1984 * Version 1.0/v4, supporting only the @c raw type without @c str8.
1985 */
1986 mpack_version_v4 = 4,
1987
1988 /**
1989 * Version 2.0/v5, supporting the @c str8, @c bin and @c ext types.
1990 */
1991 mpack_version_v5 = 5,
1992
1993 /**
1994 * The most recent supported version of MessagePack. This is the default.
1995 */
1996 mpack_version_current = mpack_version_v5,
1997
1998} mpack_version_t;
1999#endif
2000
2001/**
2002 * Error states for MPack objects.
2003 *
2004 * When a reader, writer, or tree is in an error state, all subsequent calls
2005 * are ignored and their return values are nil/zero. You should check whether
2006 * the source is in an error state before using such values.
2007 */
2008typedef enum mpack_error_t {
2009 mpack_ok = 0, /**< No error. */
2010 mpack_error_io = 2, /**< The reader or writer failed to fill or flush, or some other file or socket error occurred. */
2011 mpack_error_invalid, /**< The data read is not valid MessagePack. */
2012 mpack_error_unsupported, /**< The data read is not supported by this configuration of MPack. (See @ref MPACK_EXTENSIONS.) */
2013 mpack_error_type, /**< The type or value range did not match what was expected by the caller. */
2014 mpack_error_too_big, /**< A read or write was bigger than the maximum size allowed for that operation. */
2015 mpack_error_memory, /**< An allocation failure occurred. */
2016 mpack_error_bug, /**< The MPack API was used incorrectly. (This will always assert in debug mode.) */
2017 mpack_error_data, /**< The contained data is not valid. */
2018 mpack_error_eof, /**< The reader failed to read because of file or socket EOF */
2020
2021/**
2022 * Converts an MPack error to a string. This function returns an empty
2023 * string when MPACK_DEBUG is not set.
2024 */
2026
2027/**
2028 * Defines the type of a MessagePack tag.
2029 *
2030 * Note that extension types, both user defined and built-in, are represented
2031 * in tags as @ref mpack_type_ext. The value for an extension type is stored
2032 * separately.
2033 */
2034typedef enum mpack_type_t {
2035 mpack_type_missing = 0, /**< Special type indicating a missing optional value. */
2036 mpack_type_nil, /**< A null value. */
2037 mpack_type_bool, /**< A boolean (true or false.) */
2038 mpack_type_int, /**< A 64-bit signed integer. */
2039 mpack_type_uint, /**< A 64-bit unsigned integer. */
2040 mpack_type_float, /**< A 32-bit IEEE 754 floating point number. */
2041 mpack_type_double, /**< A 64-bit IEEE 754 floating point number. */
2042 mpack_type_str, /**< A string. */
2043 mpack_type_bin, /**< A chunk of binary data. */
2044 mpack_type_array, /**< An array of MessagePack objects. */
2045 mpack_type_map, /**< An ordered map of key/value pairs of MessagePack objects. */
2046
2047 #if MPACK_EXTENSIONS
2048 /**
2049 * A typed MessagePack extension object containing a chunk of binary data.
2050 *
2051 * @note This requires @ref MPACK_EXTENSIONS.
2052 */
2053 mpack_type_ext,
2054 #endif
2056
2057/**
2058 * Converts an MPack type to a string. This function returns an empty
2059 * string when MPACK_DEBUG is not set.
2060 */
2062
2063#if MPACK_EXTENSIONS
2064/**
2065 * A timestamp.
2066 *
2067 * @note This requires @ref MPACK_EXTENSIONS.
2068 */
2069typedef struct mpack_timestamp_t {
2070 int64_t seconds; /*< The number of seconds (signed) since 1970-01-01T00:00:00Z. */
2071 uint32_t nanoseconds; /*< The number of additional nanoseconds, between 0 and 999,999,999. */
2072} mpack_timestamp_t;
2073#endif
2074
2075/**
2076 * An MPack tag is a MessagePack object header. It is a variant type
2077 * representing any kind of object, and includes the length of compound types
2078 * (e.g. map, array, string) or the value of non-compound types (e.g. boolean,
2079 * integer, float.)
2080 *
2081 * If the type is compound (str, bin, ext, array or map), the contained
2082 * elements or bytes are stored separately.
2083 *
2084 * This structure is opaque; its fields should not be accessed outside
2085 * of MPack.
2086 */
2088
2089/* Hide internals from documentation */
2090/** @cond */
2091struct mpack_tag_t {
2092 mpack_type_t type; /*< The type of value. */
2093
2094 #if MPACK_EXTENSIONS
2095 int8_t exttype; /*< The extension type if the type is @ref mpack_type_ext. */
2096 #endif
2097
2098 /* The value for non-compound types. */
2099 union {
2100 uint64_t u; /*< The value if the type is unsigned int. */
2101 int64_t i; /*< The value if the type is signed int. */
2102 bool b; /*< The value if the type is bool. */
2103
2104 #if MPACK_FLOAT
2105 float f; /*< The value if the type is float. */
2106 #else
2107 uint32_t f; /*< The raw value if the type is float. */
2108 #endif
2109
2110 #if MPACK_DOUBLE
2111 double d; /*< The value if the type is double. */
2112 #else
2113 uint64_t d; /*< The raw value if the type is double. */
2114 #endif
2115
2116 /* The number of bytes if the type is str, bin or ext. */
2117 uint32_t l;
2118
2119 /* The element count if the type is an array, or the number of
2120 key/value pairs if the type is map. */
2121 uint32_t n;
2122 } v;
2123};
2124/** @endcond */
2125
2126/**
2127 * @name Tag Generators
2128 * @{
2129 */
2130
2131/**
2132 * @def MPACK_TAG_ZERO
2133 *
2134 * An @ref mpack_tag_t initializer that zeroes the given tag.
2135 *
2136 * @warning This does not make the tag nil! The tag's type is invalid when
2137 * initialized this way. Use @ref mpack_tag_make_nil() to generate a nil tag.
2138 */
2139#if MPACK_EXTENSIONS
2140#define MPACK_TAG_ZERO {(mpack_type_t)0, 0, {0}}
2141#else
2142#define MPACK_TAG_ZERO {(mpack_type_t)0, {0}}
2143#endif
2144
2145/** Generates a nil tag. */
2148 ret.type = mpack_type_nil;
2149 return ret;
2150}
2151
2152/** Generates a bool tag. */
2153MPACK_INLINE mpack_tag_t mpack_tag_make_bool(bool value) {
2155 ret.type = mpack_type_bool;
2156 ret.v.b = value;
2157 return ret;
2158}
2159
2160/** Generates a bool tag with value true. */
2163 ret.type = mpack_type_bool;
2164 ret.v.b = true;
2165 return ret;
2166}
2167
2168/** Generates a bool tag with value false. */
2171 ret.type = mpack_type_bool;
2172 ret.v.b = false;
2173 return ret;
2174}
2175
2176/** Generates a signed int tag. */
2177MPACK_INLINE mpack_tag_t mpack_tag_make_int(int64_t value) {
2179 ret.type = mpack_type_int;
2180 ret.v.i = value;
2181 return ret;
2182}
2183
2184/** Generates an unsigned int tag. */
2185MPACK_INLINE mpack_tag_t mpack_tag_make_uint(uint64_t value) {
2187 ret.type = mpack_type_uint;
2188 ret.v.u = value;
2189 return ret;
2190}
2191
2192#if MPACK_FLOAT
2193/** Generates a float tag. */
2194MPACK_INLINE mpack_tag_t mpack_tag_make_float(float value)
2195#else
2196/** Generates a float tag from a raw uint32_t. */
2197MPACK_INLINE mpack_tag_t mpack_tag_make_raw_float(uint32_t value)
2198#endif
2199{
2201 ret.type = mpack_type_float;
2202 ret.v.f = value;
2203 return ret;
2204}
2205
2206#if MPACK_DOUBLE
2207/** Generates a double tag. */
2208MPACK_INLINE mpack_tag_t mpack_tag_make_double(double value)
2209#else
2210/** Generates a double tag from a raw uint64_t. */
2211MPACK_INLINE mpack_tag_t mpack_tag_make_raw_double(uint64_t value)
2212#endif
2213{
2215 ret.type = mpack_type_double;
2216 ret.v.d = value;
2217 return ret;
2218}
2219
2220/** Generates an array tag. */
2223 ret.type = mpack_type_array;
2224 ret.v.n = count;
2225 return ret;
2226}
2227
2228/** Generates a map tag. */
2229MPACK_INLINE mpack_tag_t mpack_tag_make_map(uint32_t count) {
2231 ret.type = mpack_type_map;
2232 ret.v.n = count;
2233 return ret;
2234}
2235
2236/** Generates a str tag. */
2237MPACK_INLINE mpack_tag_t mpack_tag_make_str(uint32_t length) {
2239 ret.type = mpack_type_str;
2240 ret.v.l = length;
2241 return ret;
2242}
2243
2244/** Generates a bin tag. */
2245MPACK_INLINE mpack_tag_t mpack_tag_make_bin(uint32_t length) {
2247 ret.type = mpack_type_bin;
2248 ret.v.l = length;
2249 return ret;
2250}
2251
2252#if MPACK_EXTENSIONS
2253/**
2254 * Generates an ext tag.
2255 *
2256 * @note This requires @ref MPACK_EXTENSIONS.
2257 */
2258MPACK_INLINE mpack_tag_t mpack_tag_make_ext(int8_t exttype, uint32_t length) {
2260 ret.type = mpack_type_ext;
2261 ret.exttype = exttype;
2262 ret.v.l = length;
2263 return ret;
2264}
2265#endif
2266
2267/**
2268 * @}
2269 */
2270
2271/**
2272 * @name Tag Querying Functions
2273 * @{
2274 */
2275
2276/**
2277 * Gets the type of a tag.
2278 */
2280 return tag->type;
2281}
2282
2283/**
2284 * Gets the boolean value of a bool-type tag. The tag must be of type @ref
2285 * mpack_type_bool.
2286 *
2287 * This asserts that the type in the tag is @ref mpack_type_bool. (No check is
2288 * performed if MPACK_DEBUG is not set.)
2289 */
2290MPACK_INLINE bool mpack_tag_bool_value(mpack_tag_t* tag) {
2291 mpack_assert(tag->type == mpack_type_bool, "tag is not a bool!");
2292 return tag->v.b;
2293}
2294
2295/**
2296 * Gets the signed integer value of an int-type tag.
2297 *
2298 * This asserts that the type in the tag is @ref mpack_type_int. (No check is
2299 * performed if MPACK_DEBUG is not set.)
2300 *
2301 * @warning This does not convert between signed and unsigned tags! A positive
2302 * integer may be stored in a tag as either @ref mpack_type_int or @ref
2303 * mpack_type_uint. You must check the type first; this can only be used if the
2304 * type is @ref mpack_type_int.
2305 *
2306 * @see mpack_type_int
2307 */
2308MPACK_INLINE int64_t mpack_tag_int_value(mpack_tag_t* tag) {
2309 mpack_assert(tag->type == mpack_type_int, "tag is not an int!");
2310 return tag->v.i;
2311}
2312
2313/**
2314 * Gets the unsigned integer value of a uint-type tag.
2315 *
2316 * This asserts that the type in the tag is @ref mpack_type_uint. (No check is
2317 * performed if MPACK_DEBUG is not set.)
2318 *
2319 * @warning This does not convert between signed and unsigned tags! A positive
2320 * integer may be stored in a tag as either @ref mpack_type_int or @ref
2321 * mpack_type_uint. You must check the type first; this can only be used if the
2322 * type is @ref mpack_type_uint.
2323 *
2324 * @see mpack_type_uint
2325 */
2326MPACK_INLINE uint64_t mpack_tag_uint_value(mpack_tag_t* tag) {
2327 mpack_assert(tag->type == mpack_type_uint, "tag is not a uint!");
2328 return tag->v.u;
2329}
2330
2331/**
2332 * Gets the float value of a float-type tag.
2333 *
2334 * This asserts that the type in the tag is @ref mpack_type_float. (No check is
2335 * performed if MPACK_DEBUG is not set.)
2336 *
2337 * @warning This does not convert between float and double tags! This can only
2338 * be used if the type is @ref mpack_type_float.
2339 *
2340 * @see mpack_type_float
2341 */
2342MPACK_INLINE
2343#if MPACK_FLOAT
2345#else
2346uint32_t mpack_tag_raw_float_value(mpack_tag_t* tag)
2347#endif
2348{
2349 mpack_assert(tag->type == mpack_type_float, "tag is not a float!");
2350 return tag->v.f;
2351}
2352
2353/**
2354 * Gets the double value of a double-type tag.
2355 *
2356 * This asserts that the type in the tag is @ref mpack_type_double. (No check
2357 * is performed if MPACK_DEBUG is not set.)
2358 *
2359 * @warning This does not convert between float and double tags! This can only
2360 * be used if the type is @ref mpack_type_double.
2361 *
2362 * @see mpack_type_double
2363 */
2364MPACK_INLINE
2365#if MPACK_DOUBLE
2367#else
2368uint64_t mpack_tag_raw_double_value(mpack_tag_t* tag)
2369#endif
2370{
2371 mpack_assert(tag->type == mpack_type_double, "tag is not a double!");
2372 return tag->v.d;
2373}
2374
2375/**
2376 * Gets the number of elements in an array tag.
2377 *
2378 * This asserts that the type in the tag is @ref mpack_type_array. (No check is
2379 * performed if MPACK_DEBUG is not set.)
2380 *
2381 * @see mpack_type_array
2382 */
2383MPACK_INLINE uint32_t mpack_tag_array_count(mpack_tag_t* tag) {
2384 mpack_assert(tag->type == mpack_type_array, "tag is not an array!");
2385 return tag->v.n;
2386}
2387
2388/**
2389 * Gets the number of key-value pairs in a map tag.
2390 *
2391 * This asserts that the type in the tag is @ref mpack_type_map. (No check is
2392 * performed if MPACK_DEBUG is not set.)
2393 *
2394 * @see mpack_type_map
2395 */
2396MPACK_INLINE uint32_t mpack_tag_map_count(mpack_tag_t* tag) {
2397 mpack_assert(tag->type == mpack_type_map, "tag is not a map!");
2398 return tag->v.n;
2399}
2400
2401/**
2402 * Gets the length in bytes of a str-type tag.
2403 *
2404 * This asserts that the type in the tag is @ref mpack_type_str. (No check is
2405 * performed if MPACK_DEBUG is not set.)
2406 *
2407 * @see mpack_type_str
2408 */
2409MPACK_INLINE uint32_t mpack_tag_str_length(mpack_tag_t* tag) {
2410 mpack_assert(tag->type == mpack_type_str, "tag is not a str!");
2411 return tag->v.l;
2412}
2413
2414/**
2415 * Gets the length in bytes of a bin-type tag.
2416 *
2417 * This asserts that the type in the tag is @ref mpack_type_bin. (No check is
2418 * performed if MPACK_DEBUG is not set.)
2419 *
2420 * @see mpack_type_bin
2421 */
2422MPACK_INLINE uint32_t mpack_tag_bin_length(mpack_tag_t* tag) {
2423 mpack_assert(tag->type == mpack_type_bin, "tag is not a bin!");
2424 return tag->v.l;
2425}
2426
2427#if MPACK_EXTENSIONS
2428/**
2429 * Gets the length in bytes of an ext-type tag.
2430 *
2431 * This asserts that the type in the tag is @ref mpack_type_ext. (No check is
2432 * performed if MPACK_DEBUG is not set.)
2433 *
2434 * @note This requires @ref MPACK_EXTENSIONS.
2435 *
2436 * @see mpack_type_ext
2437 */
2438MPACK_INLINE uint32_t mpack_tag_ext_length(mpack_tag_t* tag) {
2439 mpack_assert(tag->type == mpack_type_ext, "tag is not an ext!");
2440 return tag->v.l;
2441}
2442
2443/**
2444 * Gets the extension type (exttype) of an ext-type tag.
2445 *
2446 * This asserts that the type in the tag is @ref mpack_type_ext. (No check is
2447 * performed if MPACK_DEBUG is not set.)
2448 *
2449 * @note This requires @ref MPACK_EXTENSIONS.
2450 *
2451 * @see mpack_type_ext
2452 */
2453MPACK_INLINE int8_t mpack_tag_ext_exttype(mpack_tag_t* tag) {
2454 mpack_assert(tag->type == mpack_type_ext, "tag is not an ext!");
2455 return tag->exttype;
2456}
2457#endif
2458
2459/**
2460 * Gets the length in bytes of a str-, bin- or ext-type tag.
2461 *
2462 * This asserts that the type in the tag is @ref mpack_type_str, @ref
2463 * mpack_type_bin or @ref mpack_type_ext. (No check is performed if MPACK_DEBUG
2464 * is not set.)
2465 *
2466 * @see mpack_type_str
2467 * @see mpack_type_bin
2468 * @see mpack_type_ext
2469 */
2470MPACK_INLINE uint32_t mpack_tag_bytes(mpack_tag_t* tag) {
2471 #if MPACK_EXTENSIONS
2472 mpack_assert(tag->type == mpack_type_str || tag->type == mpack_type_bin
2473 || tag->type == mpack_type_ext, "tag is not a str, bin or ext!");
2474 #else
2475 mpack_assert(tag->type == mpack_type_str || tag->type == mpack_type_bin,
2476 "tag is not a str or bin!");
2477 #endif
2478 return tag->v.l;
2479}
2480
2481/**
2482 * @}
2483 */
2484
2485/**
2486 * @name Other tag functions
2487 * @{
2488 */
2489
2490#if MPACK_EXTENSIONS
2491/**
2492 * The extension type for a timestamp.
2493 *
2494 * @note This requires @ref MPACK_EXTENSIONS.
2495 */
2496#define MPACK_EXTTYPE_TIMESTAMP ((int8_t)(-1))
2497#endif
2498
2499/**
2500 * Compares two tags with an arbitrary fixed ordering. Returns 0 if the tags are
2501 * equal, a negative integer if left comes before right, or a positive integer
2502 * otherwise.
2503 *
2504 * \warning The ordering is not guaranteed to be preserved across MPack versions; do
2505 * not rely on it in persistent data.
2506 *
2507 * \warning Floating point numbers are compared bit-for-bit, not using the language's
2508 * operator==. This means that NaNs with matching representation will compare equal.
2509 * This behaviour is up for debate; see comments in the definition of mpack_tag_cmp().
2510 *
2511 * See mpack_tag_equal() for more information on when tags are considered equal.
2512 */
2514
2515/**
2516 * Compares two tags for equality. Tags are considered equal if the types are compatible
2517 * and the values (for non-compound types) are equal.
2518 *
2519 * The field width of variable-width fields is ignored (and in fact is not stored
2520 * in a tag), and positive numbers in signed integers are considered equal to their
2521 * unsigned counterparts. So for example the value 1 stored as a positive fixint
2522 * is equal to the value 1 stored in a 64-bit unsigned integer field.
2523 *
2524 * The "extension type" of an extension object is considered part of the value
2525 * and must match exactly.
2526 *
2527 * \warning Floating point numbers are compared bit-for-bit, not using the language's
2528 * operator==. This means that NaNs with matching representation will compare equal.
2529 * This behaviour is up for debate; see comments in the definition of mpack_tag_cmp().
2530 */
2531MPACK_INLINE bool mpack_tag_equal(mpack_tag_t left, mpack_tag_t right) {
2532 return mpack_tag_cmp(left, right) == 0;
2533}
2534
2535#if MPACK_DEBUG && MPACK_STDIO
2536/**
2537 * Generates a json-like debug description of the given tag into the given buffer.
2538 *
2539 * This is only available in debug mode, and only if stdio is available (since
2540 * it uses snprintf().) It's strictly for debugging purposes.
2541 *
2542 * The prefix is used to print the first few hexadecimal bytes of a bin or ext
2543 * type. Pass NULL if not a bin or ext.
2544 */
2545void mpack_tag_debug_pseudo_json(mpack_tag_t tag, char* buffer, size_t buffer_size,
2546 const char* prefix, size_t prefix_size);
2547
2548/**
2549 * Generates a debug string description of the given tag into the given buffer.
2550 *
2551 * This is only available in debug mode, and only if stdio is available (since
2552 * it uses snprintf().) It's strictly for debugging purposes.
2553 */
2554void mpack_tag_debug_describe(mpack_tag_t tag, char* buffer, size_t buffer_size);
2555
2556/** @cond */
2557
2558/*
2559 * A callback function for printing pseudo-JSON for debugging purposes.
2560 *
2561 * @see mpack_node_print_callback
2562 */
2563typedef void (*mpack_print_callback_t)(void* context, const char* data, size_t count);
2564
2565// helpers for printing debug output
2566// i feel a bit like i'm re-implementing a buffered writer again...
2567typedef struct mpack_print_t {
2568 char* buffer;
2569 size_t size;
2570 size_t count;
2571 mpack_print_callback_t callback;
2572 void* context;
2573} mpack_print_t;
2574
2575void mpack_print_append(mpack_print_t* print, const char* data, size_t count);
2576
2577MPACK_INLINE void mpack_print_append_cstr(mpack_print_t* print, const char* cstr) {
2578 mpack_print_append(print, cstr, mpack_strlen(cstr));
2579}
2580
2581void mpack_print_flush(mpack_print_t* print);
2582
2583void mpack_print_file_callback(void* context, const char* data, size_t count);
2584
2585/** @endcond */
2586
2587#endif
2588
2589/**
2590 * @}
2591 */
2592
2593/**
2594 * @name Deprecated Tag Generators
2595 * @{
2596 */
2597
2598/*
2599 * "make" has been added to their names to disambiguate them from the
2600 * value-fetching functions (e.g. mpack_tag_make_bool() vs
2601 * mpack_tag_bool_value().)
2602 *
2603 * The length and count for all compound types was the wrong sign (int32_t
2604 * instead of uint32_t.) These preserve the old behaviour; the new "make"
2605 * functions have the correct sign.
2606 */
2607
2608/** \deprecated Renamed to mpack_tag_make_nil(). */
2609MPACK_INLINE mpack_tag_t mpack_tag_nil(void) {
2610 return mpack_tag_make_nil();
2611}
2612
2613/** \deprecated Renamed to mpack_tag_make_bool(). */
2614MPACK_INLINE mpack_tag_t mpack_tag_bool(bool value) {
2615 return mpack_tag_make_bool(value);
2616}
2617
2618/** \deprecated Renamed to mpack_tag_make_true(). */
2619MPACK_INLINE mpack_tag_t mpack_tag_true(void) {
2620 return mpack_tag_make_true();
2621}
2622
2623/** \deprecated Renamed to mpack_tag_make_false(). */
2624MPACK_INLINE mpack_tag_t mpack_tag_false(void) {
2625 return mpack_tag_make_false();
2626}
2627
2628/** \deprecated Renamed to mpack_tag_make_int(). */
2629MPACK_INLINE mpack_tag_t mpack_tag_int(int64_t value) {
2630 return mpack_tag_make_int(value);
2631}
2632
2633/** \deprecated Renamed to mpack_tag_make_uint(). */
2634MPACK_INLINE mpack_tag_t mpack_tag_uint(uint64_t value) {
2635 return mpack_tag_make_uint(value);
2636}
2637
2638#if MPACK_FLOAT
2639/** \deprecated Renamed to mpack_tag_make_float(). */
2640MPACK_INLINE mpack_tag_t mpack_tag_float(float value) {
2641 return mpack_tag_make_float(value);
2642}
2643#endif
2644
2645#if MPACK_DOUBLE
2646/** \deprecated Renamed to mpack_tag_make_double(). */
2647MPACK_INLINE mpack_tag_t mpack_tag_double(double value) {
2648 return mpack_tag_make_double(value);
2649}
2650#endif
2651
2652/** \deprecated Renamed to mpack_tag_make_array(). */
2653MPACK_INLINE mpack_tag_t mpack_tag_array(int32_t count) {
2654 return mpack_tag_make_array((uint32_t)count);
2655}
2656
2657/** \deprecated Renamed to mpack_tag_make_map(). */
2658MPACK_INLINE mpack_tag_t mpack_tag_map(int32_t count) {
2659 return mpack_tag_make_map((uint32_t)count);
2660}
2661
2662/** \deprecated Renamed to mpack_tag_make_str(). */
2663MPACK_INLINE mpack_tag_t mpack_tag_str(int32_t length) {
2664 return mpack_tag_make_str((uint32_t)length);
2665}
2666
2667/** \deprecated Renamed to mpack_tag_make_bin(). */
2668MPACK_INLINE mpack_tag_t mpack_tag_bin(int32_t length) {
2669 return mpack_tag_make_bin((uint32_t)length);
2670}
2671
2672#if MPACK_EXTENSIONS
2673/** \deprecated Renamed to mpack_tag_make_ext(). */
2674MPACK_INLINE mpack_tag_t mpack_tag_ext(int8_t exttype, int32_t length) {
2675 return mpack_tag_make_ext(exttype, (uint32_t)length);
2676}
2677#endif
2678
2679/**
2680 * @}
2681 */
2682
2683/** @cond */
2684
2685/*
2686 * Helpers to perform unaligned network-endian loads and stores
2687 * at arbitrary addresses. Byte-swapping builtins are used if they
2688 * are available and if they improve performance.
2689 *
2690 * These will remain available in the public API so feel free to
2691 * use them for other purposes, but they are undocumented.
2692 */
2693
2694MPACK_INLINE uint8_t mpack_load_u8(const char* p) {
2695 return (uint8_t)p[0];
2696}
2697
2698MPACK_INLINE uint16_t mpack_load_u16(const char* p) {
2699 #ifdef MPACK_NHSWAP16
2700 uint16_t val;
2701 mpack_memcpy(&val, p, sizeof(val));
2702 return MPACK_NHSWAP16(val);
2703 #else
2704 return (uint16_t)((((uint16_t)(uint8_t)p[0]) << 8) |
2705 ((uint16_t)(uint8_t)p[1]));
2706 #endif
2707}
2708
2709MPACK_INLINE uint32_t mpack_load_u32(const char* p) {
2710 #ifdef MPACK_NHSWAP32
2711 uint32_t val;
2712 mpack_memcpy(&val, p, sizeof(val));
2713 return MPACK_NHSWAP32(val);
2714 #else
2715 return (((uint32_t)(uint8_t)p[0]) << 24) |
2716 (((uint32_t)(uint8_t)p[1]) << 16) |
2717 (((uint32_t)(uint8_t)p[2]) << 8) |
2718 ((uint32_t)(uint8_t)p[3]);
2719 #endif
2720}
2721
2722MPACK_INLINE uint64_t mpack_load_u64(const char* p) {
2723 #ifdef MPACK_NHSWAP64
2724 uint64_t val;
2725 mpack_memcpy(&val, p, sizeof(val));
2726 return MPACK_NHSWAP64(val);
2727 #else
2728 return (((uint64_t)(uint8_t)p[0]) << 56) |
2729 (((uint64_t)(uint8_t)p[1]) << 48) |
2730 (((uint64_t)(uint8_t)p[2]) << 40) |
2731 (((uint64_t)(uint8_t)p[3]) << 32) |
2732 (((uint64_t)(uint8_t)p[4]) << 24) |
2733 (((uint64_t)(uint8_t)p[5]) << 16) |
2734 (((uint64_t)(uint8_t)p[6]) << 8) |
2735 ((uint64_t)(uint8_t)p[7]);
2736 #endif
2737}
2738
2739MPACK_INLINE void mpack_store_u8(char* p, uint8_t val) {
2740 uint8_t* u = (uint8_t*)p;
2741 u[0] = val;
2742}
2743
2744MPACK_INLINE void mpack_store_u16(char* p, uint16_t val) {
2745 #ifdef MPACK_NHSWAP16
2746 val = MPACK_NHSWAP16(val);
2747 mpack_memcpy(p, &val, sizeof(val));
2748 #else
2749 uint8_t* u = (uint8_t*)p;
2750 u[0] = (uint8_t)((val >> 8) & 0xFF);
2751 u[1] = (uint8_t)( val & 0xFF);
2752 #endif
2753}
2754
2755MPACK_INLINE void mpack_store_u32(char* p, uint32_t val) {
2756 #ifdef MPACK_NHSWAP32
2757 val = MPACK_NHSWAP32(val);
2758 mpack_memcpy(p, &val, sizeof(val));
2759 #else
2760 uint8_t* u = (uint8_t*)p;
2761 u[0] = (uint8_t)((val >> 24) & 0xFF);
2762 u[1] = (uint8_t)((val >> 16) & 0xFF);
2763 u[2] = (uint8_t)((val >> 8) & 0xFF);
2764 u[3] = (uint8_t)( val & 0xFF);
2765 #endif
2766}
2767
2768MPACK_INLINE void mpack_store_u64(char* p, uint64_t val) {
2769 #ifdef MPACK_NHSWAP64
2770 val = MPACK_NHSWAP64(val);
2771 mpack_memcpy(p, &val, sizeof(val));
2772 #else
2773 uint8_t* u = (uint8_t*)p;
2774 u[0] = (uint8_t)((val >> 56) & 0xFF);
2775 u[1] = (uint8_t)((val >> 48) & 0xFF);
2776 u[2] = (uint8_t)((val >> 40) & 0xFF);
2777 u[3] = (uint8_t)((val >> 32) & 0xFF);
2778 u[4] = (uint8_t)((val >> 24) & 0xFF);
2779 u[5] = (uint8_t)((val >> 16) & 0xFF);
2780 u[6] = (uint8_t)((val >> 8) & 0xFF);
2781 u[7] = (uint8_t)( val & 0xFF);
2782 #endif
2783}
2784
2785MPACK_INLINE int8_t mpack_load_i8 (const char* p) {return (int8_t) mpack_load_u8 (p);}
2786MPACK_INLINE int16_t mpack_load_i16(const char* p) {return (int16_t)mpack_load_u16(p);}
2787MPACK_INLINE int32_t mpack_load_i32(const char* p) {return (int32_t)mpack_load_u32(p);}
2788MPACK_INLINE int64_t mpack_load_i64(const char* p) {return (int64_t)mpack_load_u64(p);}
2789MPACK_INLINE void mpack_store_i8 (char* p, int8_t val) {mpack_store_u8 (p, (uint8_t) val);}
2790MPACK_INLINE void mpack_store_i16(char* p, int16_t val) {mpack_store_u16(p, (uint16_t)val);}
2791MPACK_INLINE void mpack_store_i32(char* p, int32_t val) {mpack_store_u32(p, (uint32_t)val);}
2792MPACK_INLINE void mpack_store_i64(char* p, int64_t val) {mpack_store_u64(p, (uint64_t)val);}
2793
2794#if MPACK_FLOAT
2795MPACK_INLINE float mpack_load_float(const char* p) {
2796 MPACK_CHECK_FLOAT_ORDER();
2797 MPACK_STATIC_ASSERT(sizeof(float) == sizeof(uint32_t), "float is wrong size??");
2798 union {
2799 float f;
2800 uint32_t u;
2801 } v;
2802 v.u = mpack_load_u32(p);
2803 return v.f;
2804}
2805#endif
2806
2807#if MPACK_DOUBLE
2808MPACK_INLINE double mpack_load_double(const char* p) {
2809 MPACK_CHECK_FLOAT_ORDER();
2810 MPACK_STATIC_ASSERT(sizeof(double) == sizeof(uint64_t), "double is wrong size??");
2811 union {
2812 double d;
2813 uint64_t u;
2814 } v;
2815 v.u = mpack_load_u64(p);
2816 return v.d;
2817}
2818#endif
2819
2820#if MPACK_FLOAT
2821MPACK_INLINE void mpack_store_float(char* p, float value) {
2822 MPACK_CHECK_FLOAT_ORDER();
2823 union {
2824 float f;
2825 uint32_t u;
2826 } v;
2827 v.f = value;
2828 mpack_store_u32(p, v.u);
2829}
2830#endif
2831
2832#if MPACK_DOUBLE
2833MPACK_INLINE void mpack_store_double(char* p, double value) {
2834 MPACK_CHECK_FLOAT_ORDER();
2835 union {
2836 double d;
2837 uint64_t u;
2838 } v;
2839 v.d = value;
2840 mpack_store_u64(p, v.u);
2841}
2842#endif
2843
2844#if MPACK_FLOAT && !MPACK_DOUBLE
2845/**
2846 * Performs a manual shortening conversion on the raw 64-bit representation of
2847 * a double. This is useful for parsing doubles on platforms that only support
2848 * floats (such as AVR.)
2849 *
2850 * The significand is truncated rather than rounded and subnormal numbers are
2851 * set to 0 so this may not be quite as accurate as a real double-to-float
2852 * conversion.
2853 */
2854MPACK_INLINE float mpack_shorten_raw_double_to_float(uint64_t d) {
2855 MPACK_CHECK_FLOAT_ORDER();
2856 union {
2857 float f;
2858 uint32_t u;
2859 } v;
2860
2861 // float has 1 bit sign, 8 bits exponent, 23 bits significand
2862 // double has 1 bit sign, 11 bits exponent, 52 bits significand
2863
2864 uint64_t d_sign = (uint64_t)(d >> 63);
2865 uint64_t d_exponent = (uint32_t)(d >> 52) & ((1 << 11) - 1);
2866 uint64_t d_significand = d & (((uint64_t)1 << 52) - 1);
2867
2868 uint32_t f_sign = (uint32_t)d_sign;
2869 uint32_t f_exponent;
2870 uint32_t f_significand;
2871
2872 if (MPACK_UNLIKELY(d_exponent == ((1 << 11) - 1))) {
2873 // infinity or NAN. shift down to preserve the top bit since it
2874 // indicates signaling NAN, but also set the low bit if any bits were
2875 // set (that way we can't shift NAN to infinity.)
2876 f_exponent = ((1 << 8) - 1);
2877 f_significand = (uint32_t)(d_significand >> 29) | (d_significand ? 1 : 0);
2878
2879 } else {
2880 int fix_bias = (int)d_exponent - ((1 << 10) - 1) + ((1 << 7) - 1);
2881 if (MPACK_UNLIKELY(fix_bias <= 0)) {
2882 // we don't currently handle subnormal numbers. just set it to zero.
2883 f_exponent = 0;
2884 f_significand = 0;
2885 } else if (MPACK_UNLIKELY(fix_bias > 0xff)) {
2886 // exponent is too large; saturate to infinity
2887 f_exponent = 0xff;
2888 f_significand = 0;
2889 } else {
2890 // a normal number that fits in a float. this is the usual case.
2891 f_exponent = (uint32_t)fix_bias;
2892 f_significand = (uint32_t)(d_significand >> 29);
2893 }
2894 }
2895
2896 #if 0
2897 printf("\n===============\n");
2898 for (size_t i = 0; i < 64; ++i)
2899 printf("%i%s",(int)((d>>(63-i))&1),((i%8)==7)?" ":"");
2900 printf("\n%lu %lu %lu\n", d_sign, d_exponent, d_significand);
2901 printf("%u %u %u\n", f_sign, f_exponent, f_significand);
2902 #endif
2903
2904 v.u = (f_sign << 31) | (f_exponent << 23) | f_significand;
2905 return v.f;
2906}
2907#endif
2908
2909/** @endcond */
2910
2911
2912
2913/** @cond */
2914
2915// Sizes in bytes for the various possible tags
2916#define MPACK_TAG_SIZE_FIXUINT 1
2917#define MPACK_TAG_SIZE_U8 2
2918#define MPACK_TAG_SIZE_U16 3
2919#define MPACK_TAG_SIZE_U32 5
2920#define MPACK_TAG_SIZE_U64 9
2921#define MPACK_TAG_SIZE_FIXINT 1
2922#define MPACK_TAG_SIZE_I8 2
2923#define MPACK_TAG_SIZE_I16 3
2924#define MPACK_TAG_SIZE_I32 5
2925#define MPACK_TAG_SIZE_I64 9
2926#define MPACK_TAG_SIZE_FLOAT 5
2927#define MPACK_TAG_SIZE_DOUBLE 9
2928#define MPACK_TAG_SIZE_FIXARRAY 1
2929#define MPACK_TAG_SIZE_ARRAY16 3
2930#define MPACK_TAG_SIZE_ARRAY32 5
2931#define MPACK_TAG_SIZE_FIXMAP 1
2932#define MPACK_TAG_SIZE_MAP16 3
2933#define MPACK_TAG_SIZE_MAP32 5
2934#define MPACK_TAG_SIZE_FIXSTR 1
2935#define MPACK_TAG_SIZE_STR8 2
2936#define MPACK_TAG_SIZE_STR16 3
2937#define MPACK_TAG_SIZE_STR32 5
2938#define MPACK_TAG_SIZE_BIN8 2
2939#define MPACK_TAG_SIZE_BIN16 3
2940#define MPACK_TAG_SIZE_BIN32 5
2941#define MPACK_TAG_SIZE_FIXEXT1 2
2942#define MPACK_TAG_SIZE_FIXEXT2 2
2943#define MPACK_TAG_SIZE_FIXEXT4 2
2944#define MPACK_TAG_SIZE_FIXEXT8 2
2945#define MPACK_TAG_SIZE_FIXEXT16 2
2946#define MPACK_TAG_SIZE_EXT8 3
2947#define MPACK_TAG_SIZE_EXT16 4
2948#define MPACK_TAG_SIZE_EXT32 6
2949
2950// size in bytes for complete ext types
2951#define MPACK_EXT_SIZE_TIMESTAMP4 (MPACK_TAG_SIZE_FIXEXT4 + 4)
2952#define MPACK_EXT_SIZE_TIMESTAMP8 (MPACK_TAG_SIZE_FIXEXT8 + 8)
2953#define MPACK_EXT_SIZE_TIMESTAMP12 (MPACK_TAG_SIZE_EXT8 + 12)
2954
2955/** @endcond */
2956
2957
2958
2959#if MPACK_READ_TRACKING || MPACK_WRITE_TRACKING
2960/* Tracks the write state of compound elements (maps, arrays, */
2961/* strings, binary blobs and extension types) */
2962/** @cond */
2963
2964typedef struct mpack_track_element_t {
2966 uint32_t left;
2967
2968 // indicates that a value still needs to be read/written for an already
2969 // read/written key. left is not decremented until both key and value are
2970 // read/written.
2971 bool key_needs_value;
2972
2973 // tracks whether the map/array being written is using a builder. if true,
2974 // the number of elements is automatic, and left is 0.
2975 bool builder;
2976} mpack_track_element_t;
2977
2978typedef struct mpack_track_t {
2979 size_t count;
2980 size_t capacity;
2981 mpack_track_element_t* elements;
2982} mpack_track_t;
2983
2984#if MPACK_INTERNAL
2985mpack_error_t mpack_track_init(mpack_track_t* track);
2986mpack_error_t mpack_track_grow(mpack_track_t* track);
2987mpack_error_t mpack_track_push(mpack_track_t* track, mpack_type_t type, uint32_t count);
2988mpack_error_t mpack_track_push_builder(mpack_track_t* track, mpack_type_t type);
2989mpack_error_t mpack_track_pop(mpack_track_t* track, mpack_type_t type);
2990mpack_error_t mpack_track_pop_builder(mpack_track_t* track, mpack_type_t type);
2991mpack_error_t mpack_track_element(mpack_track_t* track, bool read);
2992mpack_error_t mpack_track_peek_element(mpack_track_t* track, bool read);
2993mpack_error_t mpack_track_bytes(mpack_track_t* track, bool read, size_t count);
2994mpack_error_t mpack_track_str_bytes_all(mpack_track_t* track, bool read, size_t count);
2995mpack_error_t mpack_track_check_empty(mpack_track_t* track);
2996mpack_error_t mpack_track_destroy(mpack_track_t* track, bool cancel);
2997#endif
2998
2999/** @endcond */
3000#endif
3001
3002
3003
3004#if MPACK_INTERNAL
3005/** @cond */
3006
3007
3008
3009/* Miscellaneous string functions */
3010
3011/**
3012 * Returns true if the given UTF-8 string is valid.
3013 */
3014bool mpack_utf8_check(const char* str, size_t bytes);
3015
3016/**
3017 * Returns true if the given UTF-8 string is valid and contains no null characters.
3018 */
3019bool mpack_utf8_check_no_null(const char* str, size_t bytes);
3020
3021/**
3022 * Returns true if the given string has no null bytes.
3023 */
3024bool mpack_str_check_no_null(const char* str, size_t bytes);
3025
3026
3027
3028/** @endcond */
3029#endif
3030
3031
3032
3033/**
3034 * @}
3035 */
3036
3037MPACK_EXTERN_C_END
3038MPACK_SILENCE_WARNINGS_END
3039
3040#endif
3041
3042
3043/* mpack/mpack-writer.h.h */
3044
3045/**
3046 * @file
3047 *
3048 * Declares the MPack Writer.
3049 */
3050
3051#ifndef MPACK_WRITER_H
3052#define MPACK_WRITER_H 1
3053
3054/* #include "mpack-common.h" */
3055
3056#if MPACK_WRITER
3057
3058MPACK_SILENCE_WARNINGS_BEGIN
3059MPACK_EXTERN_C_BEGIN
3060
3061#if MPACK_WRITE_TRACKING
3062struct mpack_track_t;
3063#endif
3064
3065/**
3066 * @defgroup mpack_writer Write API
3067 * @ingroup mpack
3068 *
3069 * The MPack Write API encodes structured data of a fixed (hardcoded) schema to MessagePack.
3070 *
3071 * @{
3072 */
3073
3074/**
3075 * @def MPACK_WRITER_MINIMUM_BUFFER_SIZE
3076 *
3077 * The minimum buffer size for a writer with a flush function.
3078 */
3079#define MPACK_WRITER_MINIMUM_BUFFER_SIZE 32
3080
3081/**
3082 * A buffered MessagePack encoder.
3083 *
3084 * The encoder wraps an existing buffer and, optionally, a flush function.
3085 * This allows efficiently encoding to an in-memory buffer or to a stream.
3086 *
3087 * All write operations are synchronous; they will block until the
3088 * data is fully written, or an error occurs.
3089 */
3091
3092/**
3093 * The MPack writer's flush function to flush the buffer to the output stream.
3094 * It should flag an appropriate error on the writer if flushing fails (usually
3095 * mpack_error_io or mpack_error_memory.)
3096 *
3097 * The specified context for callbacks is at writer->context.
3098 */
3099typedef void (*mpack_writer_flush_t)(mpack_writer_t* writer, const char* buffer, size_t count);
3100
3101/**
3102 * An error handler function to be called when an error is flagged on
3103 * the writer.
3104 *
3105 * The error handler will only be called once on the first error flagged;
3106 * any subsequent writes and errors are ignored, and the writer is
3107 * permanently in that error state.
3108 *
3109 * MPack is safe against non-local jumps out of error handler callbacks.
3110 * This means you are allowed to longjmp or throw an exception (in C++,
3111 * Objective-C, or with SEH) out of this callback.
3112 *
3113 * Bear in mind when using longjmp that local non-volatile variables that
3114 * have changed are undefined when setjmp() returns, so you can't put the
3115 * writer on the stack in the same activation frame as the setjmp without
3116 * declaring it volatile.
3117 *
3118 * You must still eventually destroy the writer. It is not destroyed
3119 * automatically when an error is flagged. It is safe to destroy the
3120 * writer within this error callback, but you will either need to perform
3121 * a non-local jump, or store something in your context to identify
3122 * that the writer is destroyed since any future accesses to it cause
3123 * undefined behavior.
3124 */
3125typedef void (*mpack_writer_error_t)(mpack_writer_t* writer, mpack_error_t error);
3126
3127/**
3128 * A teardown function to be called when the writer is destroyed.
3129 */
3131
3132/* Hide internals from documentation */
3133/** @cond */
3134
3135#if MPACK_BUILDER
3136/**
3137 * Build buffer pages form a linked list.
3138 *
3139 * They don't always fill up. If there is not enough space within them to write
3140 * a tag or place an mpack_build_t, a new page is allocated. For this reason
3141 * they store the number of used bytes.
3142 */
3143typedef struct mpack_builder_page_t {
3144 struct mpack_builder_page_t* next;
3145 size_t bytes_used;
3146} mpack_builder_page_t;
3147
3148/**
3149 * Builds form a linked list of mpack_build_t, interleaved with their encoded
3150 * contents directly in the paged builder buffer.
3151 */
3152typedef struct mpack_build_t {
3153 //mpack_builder_page_t* page;
3154 struct mpack_build_t* parent;
3155 //struct mpack_build_t* next;
3156
3157 size_t bytes; // number of bytes between this build and the next one
3158 uint32_t count; // number of elements (or key/value pairs) in this map/array
3160
3161 // depth of nested non-build compound elements within this
3162 // build.
3163 uint32_t nested_compound_elements;
3164
3165 // indicates that a value still needs to be written for an already
3166 // written key. count is not incremented until both key and value are
3167 // written.
3168 bool key_needs_value;
3169} mpack_build_t;
3170
3171/**
3172 * The builder state. This is stored within mpack_writer_t.
3173 */
3174typedef struct mpack_builder_t {
3175 mpack_build_t* current_build; // build which is accumulating elements
3176 mpack_build_t* latest_build; // build which is accumulating bytes
3177 mpack_builder_page_t* current_page;
3178 mpack_builder_page_t* pages;
3179 char* stash_buffer;
3180 char* stash_position;
3181 char* stash_end;
3182 #if MPACK_BUILDER_INTERNAL_STORAGE
3184 #endif
3185} mpack_builder_t;
3186#endif
3187
3188struct mpack_writer_t {
3189 #if MPACK_COMPATIBILITY
3190 mpack_version_t version; /* Version of the MessagePack spec to write */
3191 #endif
3192 mpack_writer_flush_t flush; /* Function to write bytes to the output stream */
3193 mpack_writer_error_t error_fn; /* Function to call on error */
3194 mpack_writer_teardown_t teardown; /* Function to teardown the context on destroy */
3195 void* context; /* Context for writer callbacks */
3196
3197 char* buffer; /* Byte buffer */
3198 char* position; /* Current position within the buffer */
3199 char* end; /* The end of the buffer */
3200 mpack_error_t error; /* Error state */
3201
3202 #if MPACK_WRITE_TRACKING
3203 mpack_track_t track; /* Stack of map/array/str/bin/ext writes */
3204 #endif
3205
3206 #ifdef MPACK_MALLOC
3207 /* Reserved. You can use this space to allocate a custom
3208 * context in order to reduce heap allocations. */
3209 void* reserved[2];
3210 #endif
3211
3212 #if MPACK_BUILDER
3213 mpack_builder_t builder;
3214 #endif
3215};
3216
3217
3218#if MPACK_WRITE_TRACKING
3219void mpack_writer_track_push(mpack_writer_t* writer, mpack_type_t type, uint32_t count);
3220void mpack_writer_track_push_builder(mpack_writer_t* writer, mpack_type_t type);
3221void mpack_writer_track_pop(mpack_writer_t* writer, mpack_type_t type);
3222void mpack_writer_track_pop_builder(mpack_writer_t* writer, mpack_type_t type);
3223void mpack_writer_track_bytes(mpack_writer_t* writer, size_t count);
3224#else
3225MPACK_INLINE void mpack_writer_track_push(mpack_writer_t* writer, mpack_type_t type, uint32_t count) {
3226 MPACK_UNUSED(writer);
3227 MPACK_UNUSED(type);
3228 MPACK_UNUSED(count);
3229}
3230MPACK_INLINE void mpack_writer_track_push_builder(mpack_writer_t* writer, mpack_type_t type) {
3231 MPACK_UNUSED(writer);
3232 MPACK_UNUSED(type);
3233}
3234MPACK_INLINE void mpack_writer_track_pop(mpack_writer_t* writer, mpack_type_t type) {
3235 MPACK_UNUSED(writer);
3236 MPACK_UNUSED(type);
3237}
3238MPACK_INLINE void mpack_writer_track_pop_builder(mpack_writer_t* writer, mpack_type_t type) {
3239 MPACK_UNUSED(writer);
3240 MPACK_UNUSED(type);
3241}
3242MPACK_INLINE void mpack_writer_track_bytes(mpack_writer_t* writer, size_t count) {
3243 MPACK_UNUSED(writer);
3244 MPACK_UNUSED(count);
3245}
3246#endif
3247
3248/** @endcond */
3249
3250/**
3251 * @name Lifecycle Functions
3252 * @{
3253 */
3254
3255/**
3256 * Initializes an MPack writer with the given buffer. The writer
3257 * does not assume ownership of the buffer.
3258 *
3259 * Trying to write past the end of the buffer will result in mpack_error_too_big
3260 * unless a flush function is set with mpack_writer_set_flush(). To use the data
3261 * without flushing, call mpack_writer_buffer_used() to determine the number of
3262 * bytes written.
3263 *
3264 * @param writer The MPack writer.
3265 * @param buffer The buffer into which to write MessagePack data.
3266 * @param size The size of the buffer.
3267 */
3268void mpack_writer_init(mpack_writer_t* writer, char* buffer, size_t size);
3269
3270#ifdef MPACK_MALLOC
3271/**
3272 * Initializes an MPack writer using a growable buffer.
3273 *
3274 * The data is placed in the given data pointer if and when the writer
3275 * is destroyed without error. The data pointer is NULL during writing,
3276 * and will remain NULL if an error occurs.
3277 *
3278 * The allocated data must be freed with MPACK_FREE() (or simply free()
3279 * if MPack's allocator hasn't been customized.)
3280 *
3281 * @throws mpack_error_memory if the buffer fails to grow when
3282 * flushing.
3283 *
3284 * @param writer The MPack writer.
3285 * @param data Where to place the allocated data.
3286 * @param size Where to write the size of the data.
3287 */
3288void mpack_writer_init_growable(mpack_writer_t* writer, char** data, size_t* size);
3289#endif
3290
3291/**
3292 * Initializes an MPack writer directly into an error state. Use this if you
3293 * are writing a wrapper to mpack_writer_init() which can fail its setup.
3294 */
3296
3297#if MPACK_STDIO
3298/**
3299 * Initializes an MPack writer that writes to a file.
3300 *
3301 * @throws mpack_error_memory if allocation fails
3302 * @throws mpack_error_io if the file cannot be opened
3303 */
3304void mpack_writer_init_filename(mpack_writer_t* writer, const char* filename);
3305
3306/**
3307 * Deprecated.
3308 *
3309 * \deprecated Renamed to mpack_writer_init_filename().
3310 */
3311MPACK_INLINE void mpack_writer_init_file(mpack_writer_t* writer, const char* filename) {
3312 mpack_writer_init_filename(writer, filename);
3313}
3314
3315/**
3316 * Initializes an MPack writer that writes to a libc FILE. This can be used to
3317 * write to stdout or stderr, or to a file opened separately.
3318 *
3319 * @param writer The MPack writer.
3320 * @param stdfile The FILE.
3321 * @param close_when_done If true, fclose() will be called on the FILE when it
3322 * is no longer needed. If false, the file will not be flushed or
3323 * closed when writing is done.
3324 *
3325 * @note The writer is buffered. If you want to write other data to the FILE in
3326 * between messages, you must flush it first.
3327 *
3328 * @see mpack_writer_flush_message
3329 */
3330void mpack_writer_init_stdfile(mpack_writer_t* writer, FILE* stdfile, bool close_when_done);
3331#endif
3332
3333/** @cond */
3334
3335#define mpack_writer_init_stack_line_ex(line, writer) \
3336 char mpack_buf_##line[MPACK_STACK_SIZE]; \
3337 mpack_writer_init(writer, mpack_buf_##line, sizeof(mpack_buf_##line))
3338
3339#define mpack_writer_init_stack_line(line, writer) \
3340 mpack_writer_init_stack_line_ex(line, writer)
3341
3342/*
3343 * Initializes an MPack writer using stack space as a buffer. A flush function
3344 * should be added to the writer to flush the buffer.
3345 *
3346 * This is currently undocumented since it's not entirely useful on its own.
3347 */
3348
3349#define mpack_writer_init_stack(writer) \
3350 mpack_writer_init_stack_line(__LINE__, (writer))
3351
3352/** @endcond */
3353
3354/**
3355 * Cleans up the MPack writer, flushing and closing the underlying stream,
3356 * if any. Returns the final error state of the writer.
3357 *
3358 * No flushing is performed if the writer is in an error state. The attached
3359 * teardown function is called whether or not the writer is in an error state.
3360 *
3361 * This will assert in tracking mode if the writer is not in an error
3362 * state and has any unclosed compound types. If you want to cancel
3363 * writing in the middle of a document, you need to flag an error on
3364 * the writer before destroying it (such as mpack_error_data).
3365 *
3366 * Note that a writer may raise an error and call your error handler during
3367 * the final flush. It is safe to longjmp or throw out of this error handler,
3368 * but if you do, the writer will not be destroyed, and the teardown function
3369 * will not be called. You can still get the writer's error state, and you
3370 * must call @ref mpack_writer_destroy() again. (The second call is guaranteed
3371 * not to call your error handler again since the writer is already in an error
3372 * state.)
3373 *
3374 * @see mpack_writer_set_error_handler
3375 * @see mpack_writer_set_flush
3376 * @see mpack_writer_set_teardown
3377 * @see mpack_writer_flag_error
3378 * @see mpack_error_data
3379 */
3381
3382/**
3383 * @}
3384 */
3385
3386/**
3387 * @name Configuration
3388 * @{
3389 */
3390
3391#if MPACK_COMPATIBILITY
3392/**
3393 * Sets the version of the MessagePack spec that will be generated.
3394 *
3395 * This can be used to interface with older libraries that do not support
3396 * the newest MessagePack features (such as the @c str8 type.)
3397 *
3398 * @note This requires @ref MPACK_COMPATIBILITY.
3399 */
3400MPACK_INLINE void mpack_writer_set_version(mpack_writer_t* writer, mpack_version_t version) {
3401 writer->version = version;
3402}
3403#endif
3404
3405/**
3406 * Sets the custom pointer to pass to the writer callbacks, such as flush
3407 * or teardown.
3408 *
3409 * @param writer The MPack writer.
3410 * @param context User data to pass to the writer callbacks.
3411 *
3412 * @see mpack_writer_context()
3413 */
3414MPACK_INLINE void mpack_writer_set_context(mpack_writer_t* writer, void* context) {
3415 writer->context = context;
3416}
3417
3418/**
3419 * Returns the custom context for writer callbacks.
3420 *
3421 * @see mpack_writer_set_context
3422 * @see mpack_writer_set_flush
3423 */
3424MPACK_INLINE void* mpack_writer_context(mpack_writer_t* writer) {
3425 return writer->context;
3426}
3427
3428/**
3429 * Sets the flush function to write out the data when the buffer is full.
3430 *
3431 * If no flush function is used, trying to write past the end of the
3432 * buffer will result in mpack_error_too_big.
3433 *
3434 * This should normally be used with mpack_writer_set_context() to register
3435 * a custom pointer to pass to the flush function.
3436 *
3437 * @param writer The MPack writer.
3438 * @param flush The function to write out data from the buffer.
3439 *
3440 * @see mpack_writer_context()
3441 */
3443
3444/**
3445 * Sets the error function to call when an error is flagged on the writer.
3446 *
3447 * This should normally be used with mpack_writer_set_context() to register
3448 * a custom pointer to pass to the error function.
3449 *
3450 * See the definition of mpack_writer_error_t for more information about
3451 * what you can do from an error callback.
3452 *
3453 * @see mpack_writer_error_t
3454 * @param writer The MPack writer.
3455 * @param error_fn The function to call when an error is flagged on the writer.
3456 */
3458 writer->error_fn = error_fn;
3459}
3460
3461/**
3462 * Sets the teardown function to call when the writer is destroyed.
3463 *
3464 * This should normally be used with mpack_writer_set_context() to register
3465 * a custom pointer to pass to the teardown function.
3466 *
3467 * @param writer The MPack writer.
3468 * @param teardown The function to call when the writer is destroyed.
3469 */
3471 writer->teardown = teardown;
3472}
3473
3474/**
3475 * @}
3476 */
3477
3478/**
3479 * @name Core Writer Functions
3480 * @{
3481 */
3482
3483/**
3484 * Flushes any buffered data to the underlying stream.
3485 *
3486 * If the writer is connected to a socket and you are keeping it open,
3487 * you will want to call this after writing a message (or set of
3488 * messages) so that the data is actually sent.
3489 *
3490 * It is not necessary to call this if you are not keeping the writer
3491 * open afterwards. You can just call `mpack_writer_destroy()` and it
3492 * will flush before cleaning up.
3493 *
3494 * This will assert if no flush function is assigned to the writer.
3495 *
3496 * If write tracking is enabled, this will break and flag @ref
3497 * mpack_error_bug if the writer has any open compound types, ensuring
3498 * that no compound types are still open. This prevents a "missing
3499 * finish" bug from causing a never-ending message.
3500 */
3502
3503/**
3504 * Returns the number of bytes currently stored in the buffer. This
3505 * may be less than the total number of bytes written if bytes have
3506 * been flushed to an underlying stream.
3507 */
3508MPACK_INLINE size_t mpack_writer_buffer_used(mpack_writer_t* writer) {
3509 return (size_t)(writer->position - writer->buffer);
3510}
3511
3512/**
3513 * Returns the amount of space left in the buffer. This may be reset
3514 * after a write if bytes are flushed to an underlying stream.
3515 */
3516MPACK_INLINE size_t mpack_writer_buffer_left(mpack_writer_t* writer) {
3517 return (size_t)(writer->end - writer->position);
3518}
3519
3520/**
3521 * Returns the (current) size of the buffer. This may change after a write if
3522 * the flush callback changes the buffer.
3523 */
3524MPACK_INLINE size_t mpack_writer_buffer_size(mpack_writer_t* writer) {
3525 return (size_t)(writer->end - writer->buffer);
3526}
3527
3528/**
3529 * Places the writer in the given error state, calling the error callback if one
3530 * is set.
3531 *
3532 * This allows you to externally flag errors, for example if you are validating
3533 * data as you write it, or if you want to cancel writing in the middle of a
3534 * document. (The writer will assert if you try to destroy it without error and
3535 * with unclosed compound types. In this case you should flag mpack_error_data
3536 * before destroying it.)
3537 *
3538 * If the writer is already in an error state, this call is ignored and no
3539 * error callback is called.
3540 *
3541 * @see mpack_writer_destroy
3542 * @see mpack_error_data
3543 */
3545
3546/**
3547 * Queries the error state of the MPack writer.
3548 *
3549 * If a writer is in an error state, you should discard all data since the
3550 * last time the error flag was checked. The error flag cannot be cleared.
3551 */
3553 return writer->error;
3554}
3555
3556/**
3557 * Writes a MessagePack object header (an MPack Tag.)
3558 *
3559 * If the value is a map, array, string, binary or extension type, the
3560 * containing elements or bytes must be written separately and the
3561 * appropriate finish function must be called (as though one of the
3562 * mpack_start_*() functions was called.)
3563 *
3564 * @see mpack_write_bytes()
3565 * @see mpack_finish_map()
3566 * @see mpack_finish_array()
3567 * @see mpack_finish_str()
3568 * @see mpack_finish_bin()
3569 * @see mpack_finish_ext()
3570 * @see mpack_finish_type()
3571 */
3573
3574/**
3575 * @}
3576 */
3577
3578/**
3579 * @name Integers
3580 * @{
3581 */
3582
3583/** Writes an 8-bit integer in the most efficient packing available. */
3584void mpack_write_i8(mpack_writer_t* writer, int8_t value);
3585
3586/** Writes a 16-bit integer in the most efficient packing available. */
3587void mpack_write_i16(mpack_writer_t* writer, int16_t value);
3588
3589/** Writes a 32-bit integer in the most efficient packing available. */
3590void mpack_write_i32(mpack_writer_t* writer, int32_t value);
3591
3592/** Writes a 64-bit integer in the most efficient packing available. */
3593void mpack_write_i64(mpack_writer_t* writer, int64_t value);
3594
3595/** Writes an integer in the most efficient packing available. */
3596MPACK_INLINE void mpack_write_int(mpack_writer_t* writer, int64_t value) {
3597 mpack_write_i64(writer, value);
3598}
3599
3600/** Writes an 8-bit unsigned integer in the most efficient packing available. */
3601void mpack_write_u8(mpack_writer_t* writer, uint8_t value);
3602
3603/** Writes an 16-bit unsigned integer in the most efficient packing available. */
3604void mpack_write_u16(mpack_writer_t* writer, uint16_t value);
3605
3606/** Writes an 32-bit unsigned integer in the most efficient packing available. */
3607void mpack_write_u32(mpack_writer_t* writer, uint32_t value);
3608
3609/** Writes an 64-bit unsigned integer in the most efficient packing available. */
3610void mpack_write_u64(mpack_writer_t* writer, uint64_t value);
3611
3612/** Writes an unsigned integer in the most efficient packing available. */
3613MPACK_INLINE void mpack_write_uint(mpack_writer_t* writer, uint64_t value) {
3614 mpack_write_u64(writer, value);
3615}
3616
3617/**
3618 * @}
3619 */
3620
3621/**
3622 * @name Other Basic Types
3623 * @{
3624 */
3625
3626#if MPACK_FLOAT
3627/** Writes a float. */
3628void mpack_write_float(mpack_writer_t* writer, float value);
3629#else
3630/** Writes a float from a raw uint32_t. */
3631void mpack_write_raw_float(mpack_writer_t* writer, uint32_t raw_value);
3632#endif
3633
3634#if MPACK_DOUBLE
3635/** Writes a double. */
3636void mpack_write_double(mpack_writer_t* writer, double value);
3637#else
3638/** Writes a double from a raw uint64_t. */
3639void mpack_write_raw_double(mpack_writer_t* writer, uint64_t raw_value);
3640#endif
3641
3642/** Writes a boolean. */
3643void mpack_write_bool(mpack_writer_t* writer, bool value);
3644
3645/** Writes a boolean with value true. */
3647
3648/** Writes a boolean with value false. */
3650
3651/** Writes a nil. */
3653
3654/** Write a pre-encoded messagepack object */
3655void mpack_write_object_bytes(mpack_writer_t* writer, const char* data, size_t bytes);
3656
3657#if MPACK_EXTENSIONS
3658/**
3659 * Writes a timestamp.
3660 *
3661 * @note This requires @ref MPACK_EXTENSIONS.
3662 *
3663 * @param writer The writer
3664 * @param seconds The (signed) number of seconds since 1970-01-01T00:00:00Z.
3665 * @param nanoseconds The additional number of nanoseconds from 0 to 999,999,999 inclusive.
3666 */
3667void mpack_write_timestamp(mpack_writer_t* writer, int64_t seconds, uint32_t nanoseconds);
3668
3669/**
3670 * Writes a timestamp with the given number of seconds (and zero nanoseconds).
3671 *
3672 * @note This requires @ref MPACK_EXTENSIONS.
3673 *
3674 * @param writer The writer
3675 * @param seconds The (signed) number of seconds since 1970-01-01T00:00:00Z.
3676 */
3677MPACK_INLINE void mpack_write_timestamp_seconds(mpack_writer_t* writer, int64_t seconds) {
3678 mpack_write_timestamp(writer, seconds, 0);
3679}
3680
3681/**
3682 * Writes a timestamp.
3683 *
3684 * @note This requires @ref MPACK_EXTENSIONS.
3685 */
3686MPACK_INLINE void mpack_write_timestamp_struct(mpack_writer_t* writer, mpack_timestamp_t timestamp) {
3687 mpack_write_timestamp(writer, timestamp.seconds, timestamp.nanoseconds);
3688}
3689#endif
3690
3691/**
3692 * @}
3693 */
3694
3695/**
3696 * @name Map and Array Functions
3697 * @{
3698 */
3699
3700/**
3701 * Opens an array.
3702 *
3703 * `count` elements must follow, and mpack_finish_array() must be called
3704 * when done.
3705 *
3706 * If you do not know the number of elements to be written ahead of time, call
3707 * mpack_build_array() instead.
3708 *
3709 * @see mpack_finish_array()
3710 * @see mpack_build_array() to count the number of elements automatically
3711 */
3713
3714/**
3715 * Opens a map.
3716 *
3717 * `count * 2` elements must follow, and mpack_finish_map() must be called
3718 * when done.
3719 *
3720 * If you do not know the number of elements to be written ahead of time, call
3721 * mpack_build_map() instead.
3722 *
3723 * Remember that while map elements in MessagePack are implicitly ordered,
3724 * they are not ordered in JSON. If you need elements to be read back
3725 * in the order they are written, consider use an array instead.
3726 *
3727 * @see mpack_finish_map()
3728 * @see mpack_build_map() to count the number of key/value pairs automatically
3729 */
3730void mpack_start_map(mpack_writer_t* writer, uint32_t count);
3731
3733 MPACK_UNUSED(writer);
3734
3735 #if MPACK_BUILDER
3736 mpack_build_t* build = writer->builder.current_build;
3737 if (build != NULL) {
3738 ++build->nested_compound_elements;
3739 }
3740 #endif
3741}
3742
3743MPACK_INLINE void mpack_builder_compound_pop(mpack_writer_t* writer) {
3744 MPACK_UNUSED(writer);
3745
3746 #if MPACK_BUILDER
3747 mpack_build_t* build = writer->builder.current_build;
3748 if (build != NULL) {
3749 mpack_assert(build->nested_compound_elements > 0);
3750 --build->nested_compound_elements;
3751 }
3752 #endif
3753}
3754
3755/**
3756 * Finishes writing an array.
3757 *
3758 * This should be called only after a corresponding call to mpack_start_array()
3759 * and after the array contents are written.
3760 *
3761 * In debug mode (or if MPACK_WRITE_TRACKING is not 0), this will track writes
3762 * to ensure that the correct number of elements are written.
3763 *
3764 * @see mpack_start_array()
3765 */
3766MPACK_INLINE void mpack_finish_array(mpack_writer_t* writer) {
3767 mpack_writer_track_pop(writer, mpack_type_array);
3769}
3770
3771/**
3772 * Finishes writing a map.
3773 *
3774 * This should be called only after a corresponding call to mpack_start_map()
3775 * and after the map contents are written.
3776 *
3777 * In debug mode (or if MPACK_WRITE_TRACKING is not 0), this will track writes
3778 * to ensure that the correct number of elements are written.
3779 *
3780 * @see mpack_start_map()
3781 */
3782MPACK_INLINE void mpack_finish_map(mpack_writer_t* writer) {
3783 mpack_writer_track_pop(writer, mpack_type_map);
3785}
3786
3787/**
3788 * Starts building an array.
3789 *
3790 * Elements must follow, and mpack_complete_array() must be called when done. The
3791 * number of elements is determined automatically.
3792 *
3793 * If you know ahead of time the number of elements in the array, it is more
3794 * efficient to call mpack_start_array() instead, even if you are already
3795 * within another open build.
3796 *
3797 * Builder containers can be nested within normal (known size) containers and
3798 * vice versa. You can call mpack_build_array(), then mpack_start_array()
3799 * inside it, then mpack_build_array() inside that, and so forth.
3800 *
3801 * @see mpack_complete_array() to complete this array
3802 * @see mpack_start_array() if you already know the size of the array
3803 * @see mpack_build_map() for implementation details
3804 */
3806
3807/**
3808 * Starts building a map.
3809 *
3810 * An even number of elements must follow, and mpack_complete_map() must be
3811 * called when done. The number of elements is determined automatically.
3812 *
3813 * If you know ahead of time the number of elements in the map, it is more
3814 * efficient to call mpack_start_map() instead, even if you are already within
3815 * another open build.
3816 *
3817 * Builder containers can be nested within normal (known size) containers and
3818 * vice versa. You can call mpack_build_map(), then mpack_start_map() inside
3819 * it, then mpack_build_map() inside that, and so forth.
3820 *
3821 * A writer in build mode diverts writes to a builder buffer that allocates as
3822 * needed. Once the last map or array being built is completed, the deferred
3823 * message is composed with computed array and map sizes into the writer.
3824 * Builder maps and arrays are encoded exactly the same as ordinary maps and
3825 * arrays in the final message.
3826 *
3827 * This indirect encoding is costly, as it incurs at least an extra copy of all
3828 * data written within a builder (but not additional copies for nested
3829 * builders.) Expect a speed penalty of half or more.
3830 *
3831 * A good strategy is to use this during early development when your messages
3832 * are constantly changing, and then closer to release when your message
3833 * formats have stabilized, replace all your build calls with start calls with
3834 * pre-computed sizes. Or don't, if you find the builder has little impact on
3835 * performance, because even with builders MPack is extremely fast.
3836 *
3837 * @note When an array or map starts being built, nothing will be flushed
3838 * until it is completed. If you are building a large message that
3839 * does not fit in the output stream, you won't get an error about it
3840 * until everything is written.
3841 *
3842 * @see mpack_complete_map() to complete this map
3843 * @see mpack_start_map() if you already know the size of the map
3844 */
3845void mpack_build_map(struct mpack_writer_t* writer);
3846
3847/**
3848 * Completes an array being built.
3849 *
3850 * @see mpack_build_array()
3851 */
3853
3854/**
3855 * Completes a map being built.
3856 *
3857 * @see mpack_build_map()
3858 */
3860
3861/**
3862 * @}
3863 */
3864
3865/**
3866 * @name Data Helpers
3867 * @{
3868 */
3869
3870/**
3871 * Writes a string.
3872 *
3873 * To stream a string in chunks, use mpack_start_str() instead.
3874 *
3875 * MPack does not care about the underlying encoding, but UTF-8 is highly
3876 * recommended, especially for compatibility with JSON. You should consider
3877 * calling mpack_write_utf8() instead, especially if you will be reading
3878 * it back as UTF-8.
3879 *
3880 * You should not call mpack_finish_str() after calling this; this
3881 * performs both start and finish.
3882 */
3883void mpack_write_str(mpack_writer_t* writer, const char* str, uint32_t length);
3884
3885/**
3886 * Writes a string, ensuring that it is valid UTF-8.
3887 *
3888 * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
3889 * WTF-8. Only pure UTF-8 is allowed.
3890 *
3891 * You should not call mpack_finish_str() after calling this; this
3892 * performs both start and finish.
3893 *
3894 * @throws mpack_error_invalid if the string is not valid UTF-8
3895 */
3896void mpack_write_utf8(mpack_writer_t* writer, const char* str, uint32_t length);
3897
3898/**
3899 * Writes a null-terminated string. (The null-terminator is not written.)
3900 *
3901 * MPack does not care about the underlying encoding, but UTF-8 is highly
3902 * recommended, especially for compatibility with JSON. You should consider
3903 * calling mpack_write_utf8_cstr() instead, especially if you will be reading
3904 * it back as UTF-8.
3905 *
3906 * You should not call mpack_finish_str() after calling this; this
3907 * performs both start and finish.
3908 */
3909void mpack_write_cstr(mpack_writer_t* writer, const char* cstr);
3910
3911/**
3912 * Writes a null-terminated string, or a nil node if the given cstr pointer
3913 * is NULL. (The null-terminator is not written.)
3914 *
3915 * MPack does not care about the underlying encoding, but UTF-8 is highly
3916 * recommended, especially for compatibility with JSON. You should consider
3917 * calling mpack_write_utf8_cstr_or_nil() instead, especially if you will
3918 * be reading it back as UTF-8.
3919 *
3920 * You should not call mpack_finish_str() after calling this; this
3921 * performs both start and finish.
3922 */
3923void mpack_write_cstr_or_nil(mpack_writer_t* writer, const char* cstr);
3924
3925/**
3926 * Writes a null-terminated string, ensuring that it is valid UTF-8. (The
3927 * null-terminator is not written.)
3928 *
3929 * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
3930 * WTF-8. Only pure UTF-8 is allowed.
3931 *
3932 * You should not call mpack_finish_str() after calling this; this
3933 * performs both start and finish.
3934 *
3935 * @throws mpack_error_invalid if the string is not valid UTF-8
3936 */
3937void mpack_write_utf8_cstr(mpack_writer_t* writer, const char* cstr);
3938
3939/**
3940 * Writes a null-terminated string ensuring that it is valid UTF-8, or
3941 * writes nil if the given cstr pointer is NULL. (The null-terminator
3942 * is not written.)
3943 *
3944 * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
3945 * WTF-8. Only pure UTF-8 is allowed.
3946 *
3947 * You should not call mpack_finish_str() after calling this; this
3948 * performs both start and finish.
3949 *
3950 * @throws mpack_error_invalid if the string is not valid UTF-8
3951 */
3952void mpack_write_utf8_cstr_or_nil(mpack_writer_t* writer, const char* cstr);
3953
3954/**
3955 * Writes a binary blob.
3956 *
3957 * To stream a binary blob in chunks, use mpack_start_bin() instead.
3958 *
3959 * You should not call mpack_finish_bin() after calling this; this
3960 * performs both start and finish.
3961 */
3962void mpack_write_bin(mpack_writer_t* writer, const char* data, uint32_t count);
3963
3964#if MPACK_EXTENSIONS
3965/**
3966 * Writes an extension type.
3967 *
3968 * To stream an extension blob in chunks, use mpack_start_ext() instead.
3969 *
3970 * Extension types [0, 127] are available for application-specific types. Extension
3971 * types [-128, -1] are reserved for future extensions of MessagePack.
3972 *
3973 * You should not call mpack_finish_ext() after calling this; this
3974 * performs both start and finish.
3975 *
3976 * @note This requires @ref MPACK_EXTENSIONS.
3977 */
3978void mpack_write_ext(mpack_writer_t* writer, int8_t exttype, const char* data, uint32_t count);
3979#endif
3980
3981/**
3982 * @}
3983 */
3984
3985/**
3986 * @name Chunked Data Functions
3987 * @{
3988 */
3989
3990/**
3991 * Opens a string. `count` bytes should be written with calls to
3992 * mpack_write_bytes(), and mpack_finish_str() should be called
3993 * when done.
3994 *
3995 * To write an entire string at once, use mpack_write_str() or
3996 * mpack_write_cstr() instead.
3997 *
3998 * MPack does not care about the underlying encoding, but UTF-8 is highly
3999 * recommended, especially for compatibility with JSON.
4000 */
4001void mpack_start_str(mpack_writer_t* writer, uint32_t count);
4002
4003/**
4004 * Opens a binary blob. `count` bytes should be written with calls to
4005 * mpack_write_bytes(), and mpack_finish_bin() should be called
4006 * when done.
4007 */
4008void mpack_start_bin(mpack_writer_t* writer, uint32_t count);
4009
4010#if MPACK_EXTENSIONS
4011/**
4012 * Opens an extension type. `count` bytes should be written with calls
4013 * to mpack_write_bytes(), and mpack_finish_ext() should be called
4014 * when done.
4015 *
4016 * Extension types [0, 127] are available for application-specific types. Extension
4017 * types [-128, -1] are reserved for future extensions of MessagePack.
4018 *
4019 * @note This requires @ref MPACK_EXTENSIONS.
4020 */
4021void mpack_start_ext(mpack_writer_t* writer, int8_t exttype, uint32_t count);
4022#endif
4023
4024/**
4025 * Writes a portion of bytes for a string, binary blob or extension type which
4026 * was opened by mpack_write_tag() or one of the mpack_start_*() functions.
4027 *
4028 * This can be called multiple times to write the data in chunks, as long as
4029 * the total amount of bytes written matches the count given when the compound
4030 * type was started.
4031 *
4032 * The corresponding mpack_finish_*() function must be called when done.
4033 *
4034 * To write an entire string, binary blob or extension type at
4035 * once, use one of the mpack_write_*() functions instead.
4036 *
4037 * @see mpack_write_tag()
4038 * @see mpack_start_str()
4039 * @see mpack_start_bin()
4040 * @see mpack_start_ext()
4041 * @see mpack_finish_str()
4042 * @see mpack_finish_bin()
4043 * @see mpack_finish_ext()
4044 * @see mpack_finish_type()
4045 */
4046void mpack_write_bytes(mpack_writer_t* writer, const char* data, size_t count);
4047
4048/**
4049 * Finishes writing a string.
4050 *
4051 * This should be called only after a corresponding call to mpack_start_str()
4052 * and after the string bytes are written with mpack_write_bytes().
4053 *
4054 * This will track writes to ensure that the correct number of elements are written.
4055 *
4056 * @see mpack_start_str()
4057 * @see mpack_write_bytes()
4058 */
4059MPACK_INLINE void mpack_finish_str(mpack_writer_t* writer) {
4060 mpack_writer_track_pop(writer, mpack_type_str);
4061}
4062
4063/**
4064 * Finishes writing a binary blob.
4065 *
4066 * This should be called only after a corresponding call to mpack_start_bin()
4067 * and after the binary bytes are written with mpack_write_bytes().
4068 *
4069 * This will track writes to ensure that the correct number of bytes are written.
4070 *
4071 * @see mpack_start_bin()
4072 * @see mpack_write_bytes()
4073 */
4074MPACK_INLINE void mpack_finish_bin(mpack_writer_t* writer) {
4075 mpack_writer_track_pop(writer, mpack_type_bin);
4076}
4077
4078#if MPACK_EXTENSIONS
4079/**
4080 * Finishes writing an extended type binary data blob.
4081 *
4082 * This should be called only after a corresponding call to mpack_start_bin()
4083 * and after the binary bytes are written with mpack_write_bytes().
4084 *
4085 * This will track writes to ensure that the correct number of bytes are written.
4086 *
4087 * @note This requires @ref MPACK_EXTENSIONS.
4088 *
4089 * @see mpack_start_ext()
4090 * @see mpack_write_bytes()
4091 */
4092MPACK_INLINE void mpack_finish_ext(mpack_writer_t* writer) {
4093 mpack_writer_track_pop(writer, mpack_type_ext);
4094}
4095#endif
4096
4097/**
4098 * Finishes writing the given compound type.
4099 *
4100 * This will track writes to ensure that the correct number of elements
4101 * or bytes are written.
4102 *
4103 * This can be called with the appropriate type instead the corresponding
4104 * mpack_finish_*() function if you want to finish a dynamic type.
4105 */
4107 mpack_writer_track_pop(writer, type);
4108}
4109
4110/**
4111 * @}
4112 */
4113
4114#if MPACK_HAS_GENERIC && !defined(__cplusplus)
4115
4116/**
4117 * @name Type-Generic Writers
4118 * @{
4119 */
4120
4121/**
4122 * @def mpack_write(writer, value)
4123 *
4124 * Type-generic writer for primitive types.
4125 *
4126 * The compiler will dispatch to an appropriate write function based
4127 * on the type of the @a value parameter.
4128 *
4129 * @note This requires C11 `_Generic` support. (A set of inline overloads
4130 * are used in C++ to provide the same functionality.)
4131 *
4132 * @warning In C11, the indentifiers `true`, `false` and `NULL` are
4133 * all of type `int`, not `bool` or `void*`! They will emit unexpected
4134 * types when passed uncast, so be careful when using them.
4135 */
4136#if MPACK_FLOAT
4137 #define MPACK_WRITE_GENERIC_FLOAT float: mpack_write_float,
4138#else
4139 #define MPACK_WRITE_GENERIC_FLOAT /*nothing*/
4140#endif
4141#if MPACK_DOUBLE
4142 #define MPACK_WRITE_GENERIC_DOUBLE double: mpack_write_double,
4143#else
4144 #define MPACK_WRITE_GENERIC_DOUBLE /*nothing*/
4145#endif
4146#define mpack_write(writer, value) \
4147 _Generic(((void)0, value), \
4148 int8_t: mpack_write_i8, \
4149 int16_t: mpack_write_i16, \
4150 int32_t: mpack_write_i32, \
4151 int64_t: mpack_write_i64, \
4152 uint8_t: mpack_write_u8, \
4153 uint16_t: mpack_write_u16, \
4154 uint32_t: mpack_write_u32, \
4155 uint64_t: mpack_write_u64, \
4156 bool: mpack_write_bool, \
4157 MPACK_WRITE_GENERIC_FLOAT \
4158 MPACK_WRITE_GENERIC_DOUBLE \
4159 char *: mpack_write_cstr_or_nil, \
4160 const char *: mpack_write_cstr_or_nil \
4161 )(writer, value)
4162
4163/**
4164 * @def mpack_write_kv(writer, key, value)
4165 *
4166 * Type-generic writer for key-value pairs of null-terminated string
4167 * keys and primitive values.
4168 *
4169 * @warning @a writer may be evaluated multiple times.
4170 *
4171 * @warning In C11, the indentifiers `true`, `false` and `NULL` are
4172 * all of type `int`, not `bool` or `void*`! They will emit unexpected
4173 * types when passed uncast, so be careful when using them.
4174 *
4175 * @param writer The writer.
4176 * @param key A null-terminated C string.
4177 * @param value A primitive type supported by mpack_write().
4178 */
4179#define mpack_write_kv(writer, key, value) do { \
4180 mpack_write_cstr(writer, key); \
4181 mpack_write(writer, value); \
4182} while (0)
4183
4184/**
4185 * @}
4186 */
4187
4188#endif // MPACK_HAS_GENERIC && !defined(__cplusplus)
4189
4190// The rest of this file contains C++ overloads, so we end extern "C" here.
4191MPACK_EXTERN_C_END
4192
4193#if defined(__cplusplus) || defined(MPACK_DOXYGEN)
4194
4195namespace mpack {
4196/**
4197 * @name C++ write overloads
4198 * @{
4199 */
4200
4201/*
4202 * C++ generic writers for primitive values
4203 */
4204
4205#ifdef MPACK_DOXYGEN
4206#undef mpack_write
4207#undef mpack_write_kv
4208#endif
4209
4210MPACK_INLINE void mpack_write(mpack_writer_t* writer, int8_t value) {
4211 mpack_write_i8(writer, value);
4212}
4213
4214MPACK_INLINE void mpack_write(mpack_writer_t* writer, int16_t value) {
4215 mpack_write_i16(writer, value);
4216}
4217
4218MPACK_INLINE void mpack_write(mpack_writer_t* writer, int32_t value) {
4219 mpack_write_i32(writer, value);
4220}
4221
4222MPACK_INLINE void mpack_write(mpack_writer_t* writer, int64_t value) {
4223 mpack_write_i64(writer, value);
4224}
4225
4226MPACK_INLINE void mpack_write(mpack_writer_t* writer, uint8_t value) {
4227 mpack_write_u8(writer, value);
4228}
4229
4230MPACK_INLINE void mpack_write(mpack_writer_t* writer, uint16_t value) {
4231 mpack_write_u16(writer, value);
4232}
4233
4234MPACK_INLINE void mpack_write(mpack_writer_t* writer, uint32_t value) {
4235 mpack_write_u32(writer, value);
4236}
4237
4238MPACK_INLINE void mpack_write(mpack_writer_t* writer, uint64_t value) {
4239 mpack_write_u64(writer, value);
4240}
4241
4242MPACK_INLINE void mpack_write(mpack_writer_t* writer, bool value) {
4243 mpack_write_bool(writer, value);
4244}
4245
4246MPACK_INLINE void mpack_write(mpack_writer_t* writer, float value) {
4247 mpack_write_float(writer, value);
4248}
4249
4250MPACK_INLINE void mpack_write(mpack_writer_t* writer, double value) {
4251 mpack_write_double(writer, value);
4252}
4253
4254MPACK_INLINE void mpack_write(mpack_writer_t* writer, char *value) {
4255 mpack_write_cstr_or_nil(writer, value);
4256}
4257
4258MPACK_INLINE void mpack_write(mpack_writer_t* writer, const char *value) {
4259 mpack_write_cstr_or_nil(writer, value);
4260}
4261
4262/* C++ generic write for key-value pairs */
4263
4264MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, int8_t value) {
4265 mpack_write_cstr(writer, key);
4266 mpack_write_i8(writer, value);
4267}
4268
4269MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, int16_t value) {
4270 mpack_write_cstr(writer, key);
4271 mpack_write_i16(writer, value);
4272}
4273
4274MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, int32_t value) {
4275 mpack_write_cstr(writer, key);
4276 mpack_write_i32(writer, value);
4277}
4278
4279MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, int64_t value) {
4280 mpack_write_cstr(writer, key);
4281 mpack_write_i64(writer, value);
4282}
4283
4284MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, uint8_t value) {
4285 mpack_write_cstr(writer, key);
4286 mpack_write_u8(writer, value);
4287}
4288
4289MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, uint16_t value) {
4290 mpack_write_cstr(writer, key);
4291 mpack_write_u16(writer, value);
4292}
4293
4294MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, uint32_t value) {
4295 mpack_write_cstr(writer, key);
4296 mpack_write_u32(writer, value);
4297}
4298
4299MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, uint64_t value) {
4300 mpack_write_cstr(writer, key);
4301 mpack_write_u64(writer, value);
4302}
4303
4304MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, bool value) {
4305 mpack_write_cstr(writer, key);
4306 mpack_write_bool(writer, value);
4307}
4308
4309MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, float value) {
4310 mpack_write_cstr(writer, key);
4311 mpack_write_float(writer, value);
4312}
4313
4314MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, double value) {
4315 mpack_write_cstr(writer, key);
4316 mpack_write_double(writer, value);
4317}
4318
4319MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, char *value) {
4320 mpack_write_cstr(writer, key);
4321 mpack_write_cstr_or_nil(writer, value);
4322}
4323
4324MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, const char *value) {
4325 mpack_write_cstr(writer, key);
4326 mpack_write_cstr_or_nil(writer, value);
4327}
4328
4329/**
4330 * @}
4331 */
4332} // namespace mpack
4333#endif /* __cplusplus */
4334
4335/**
4336 * @}
4337 */
4338
4339MPACK_SILENCE_WARNINGS_END
4340
4341#endif // MPACK_WRITER
4342
4343#endif
4344
4345/* mpack/mpack-reader.h.h */
4346
4347/**
4348 * @file
4349 *
4350 * Declares the core MPack Tag Reader.
4351 */
4352
4353#ifndef MPACK_READER_H
4354#define MPACK_READER_H 1
4355
4356/* #include "mpack-common.h" */
4357
4358MPACK_SILENCE_WARNINGS_BEGIN
4359MPACK_EXTERN_C_BEGIN
4360
4361#if MPACK_READER
4362
4363#if MPACK_READ_TRACKING
4364struct mpack_track_t;
4365#endif
4366
4367// The denominator to determine whether a read is a small
4368// fraction of the buffer size.
4369#define MPACK_READER_SMALL_FRACTION_DENOMINATOR 32
4370
4371/**
4372 * @defgroup mpack_reader Reader API
4373 * @ingroup mpack
4374 *
4375 * The MPack Reader API contains functions for imperatively reading dynamically
4376 * typed data from a MessagePack stream.
4377 *
4378 * See @ref docs/reader.md for examples.
4379 *
4380 * @note If you are not writing code for an embedded device (or otherwise do
4381 * not need maximum performance with minimal memory usage), you should not use
4382 * this. You probably want to use the @link node Node API@endlink instead.
4383 *
4384 * This forms the basis of the @link expect Expect API@endlink, which can be
4385 * used to interpret the stream of elements in expected types and value ranges.
4386 *
4387 * @{
4388 */
4389
4390/**
4391 * @def MPACK_READER_MINIMUM_BUFFER_SIZE
4392 *
4393 * The minimum buffer size for a reader with a fill function.
4394 */
4395#define MPACK_READER_MINIMUM_BUFFER_SIZE 32
4396
4397/**
4398 * A buffered MessagePack decoder.
4399 *
4400 * The decoder wraps an existing buffer and, optionally, a fill function.
4401 * This allows efficiently decoding data from existing memory buffers, files,
4402 * streams, etc.
4403 *
4404 * All read operations are synchronous; they will block until the
4405 * requested data is fully read, or an error occurs.
4406 *
4407 * This structure is opaque; its fields should not be accessed outside
4408 * of MPack.
4409 */
4411
4412/**
4413 * The MPack reader's fill function. It should fill the buffer with at
4414 * least one byte and at most the given @c count, returning the number
4415 * of bytes written to the buffer.
4416 *
4417 * In case of error, it should flag an appropriate error on the reader
4418 * (usually @ref mpack_error_io), or simply return zero. If zero is
4419 * returned, mpack_error_io is raised.
4420 *
4421 * @note When reading from a stream, you should only copy and return
4422 * the bytes that are immediately available. It is always safe to return
4423 * less than the requested count as long as some non-zero number of bytes
4424 * are read; if more bytes are needed, the read function will simply be
4425 * called again.
4426 *
4427 * @see mpack_reader_context()
4428 */
4429typedef size_t (*mpack_reader_fill_t)(mpack_reader_t* reader, char* buffer, size_t count);
4430
4431/**
4432 * The MPack reader's skip function. It should discard the given number
4433 * of bytes from the source (for example by seeking forward.)
4434 *
4435 * In case of error, it should flag an appropriate error on the reader.
4436 *
4437 * @see mpack_reader_context()
4438 */
4439typedef void (*mpack_reader_skip_t)(mpack_reader_t* reader, size_t count);
4440
4441/**
4442 * An error handler function to be called when an error is flagged on
4443 * the reader.
4444 *
4445 * The error handler will only be called once on the first error flagged;
4446 * any subsequent reads and errors are ignored, and the reader is
4447 * permanently in that error state.
4448 *
4449 * MPack is safe against non-local jumps out of error handler callbacks.
4450 * This means you are allowed to longjmp or throw an exception (in C++,
4451 * Objective-C, or with SEH) out of this callback.
4452 *
4453 * Bear in mind when using longjmp that local non-volatile variables that
4454 * have changed are undefined when setjmp() returns, so you can't put the
4455 * reader on the stack in the same activation frame as the setjmp without
4456 * declaring it volatile.
4457 *
4458 * You must still eventually destroy the reader. It is not destroyed
4459 * automatically when an error is flagged. It is safe to destroy the
4460 * reader within this error callback, but you will either need to perform
4461 * a non-local jump, or store something in your context to identify
4462 * that the reader is destroyed since any future accesses to it cause
4463 * undefined behavior.
4464 */
4465typedef void (*mpack_reader_error_t)(mpack_reader_t* reader, mpack_error_t error);
4466
4467/**
4468 * A teardown function to be called when the reader is destroyed.
4469 */
4471
4472/* Hide internals from documentation */
4473/** @cond */
4474
4475struct mpack_reader_t {
4476 void* context; /* Context for reader callbacks */
4477 mpack_reader_fill_t fill; /* Function to read bytes into the buffer */
4478 mpack_reader_error_t error_fn; /* Function to call on error */
4479 mpack_reader_teardown_t teardown; /* Function to teardown the context on destroy */
4480 mpack_reader_skip_t skip; /* Function to skip bytes from the source */
4481
4482 char* buffer; /* Writeable byte buffer */
4483 size_t size; /* Size of the buffer */
4484
4485 const char* data; /* Current data pointer (in the buffer, if it is used) */
4486 const char* end; /* The end of available data (in the buffer, if it is used) */
4487
4488 mpack_error_t error; /* Error state */
4489
4490 #if MPACK_READ_TRACKING
4491 mpack_track_t track; /* Stack of map/array/str/bin/ext reads */
4492 #endif
4493};
4494
4495/** @endcond */
4496
4497/**
4498 * @name Lifecycle Functions
4499 * @{
4500 */
4501
4502/**
4503 * Initializes an MPack reader with the given buffer. The reader does
4504 * not assume ownership of the buffer, but the buffer must be writeable
4505 * if a fill function will be used to refill it.
4506 *
4507 * @param reader The MPack reader.
4508 * @param buffer The buffer with which to read MessagePack data.
4509 * @param size The size of the buffer.
4510 * @param count The number of bytes already in the buffer.
4511 */
4512void mpack_reader_init(mpack_reader_t* reader, char* buffer, size_t size, size_t count);
4513
4514/**
4515 * Initializes an MPack reader directly into an error state. Use this if you
4516 * are writing a wrapper to mpack_reader_init() which can fail its setup.
4517 */
4519
4520/**
4521 * Initializes an MPack reader to parse a pre-loaded contiguous chunk of data. The
4522 * reader does not assume ownership of the data.
4523 *
4524 * @param reader The MPack reader.
4525 * @param data The data to parse.
4526 * @param count The number of bytes pointed to by data.
4527 */
4528void mpack_reader_init_data(mpack_reader_t* reader, const char* data, size_t count);
4529
4530#if MPACK_STDIO
4531/**
4532 * Initializes an MPack reader that reads from a file.
4533 *
4534 * The file will be automatically opened and closed by the reader.
4535 */
4536void mpack_reader_init_filename(mpack_reader_t* reader, const char* filename);
4537
4538/**
4539 * Deprecated.
4540 *
4541 * \deprecated Renamed to mpack_reader_init_filename().
4542 */
4543MPACK_INLINE void mpack_reader_init_file(mpack_reader_t* reader, const char* filename) {
4544 mpack_reader_init_filename(reader, filename);
4545}
4546
4547/**
4548 * Initializes an MPack reader that reads from a libc FILE. This can be used to
4549 * read from stdin, or from a file opened separately.
4550 *
4551 * @param reader The MPack reader.
4552 * @param stdfile The FILE.
4553 * @param close_when_done If true, fclose() will be called on the FILE when it
4554 * is no longer needed. If false, the file will not be closed when
4555 * reading is done.
4556 *
4557 * @warning The reader is buffered. It will read data in advance of parsing it,
4558 * and it may read more data than it parsed. See mpack_reader_remaining() to
4559 * access the extra data.
4560 */
4561void mpack_reader_init_stdfile(mpack_reader_t* reader, FILE* stdfile, bool close_when_done);
4562#endif
4563
4564/**
4565 * @def mpack_reader_init_stack(reader)
4566 * @hideinitializer
4567 *
4568 * Initializes an MPack reader using stack space as a buffer. A fill function
4569 * should be added to the reader to fill the buffer.
4570 *
4571 * @see mpack_reader_set_fill
4572 */
4573
4574/** @cond */
4575#define mpack_reader_init_stack_line_ex(line, reader) \
4576 char mpack_buf_##line[MPACK_STACK_SIZE]; \
4577 mpack_reader_init((reader), mpack_buf_##line, sizeof(mpack_buf_##line), 0)
4578
4579#define mpack_reader_init_stack_line(line, reader) \
4580 mpack_reader_init_stack_line_ex(line, reader)
4581/** @endcond */
4582
4583#define mpack_reader_init_stack(reader) \
4584 mpack_reader_init_stack_line(__LINE__, (reader))
4585
4586/**
4587 * Cleans up the MPack reader, ensuring that all compound elements
4588 * have been completely read. Returns the final error state of the
4589 * reader.
4590 *
4591 * This will assert in tracking mode if the reader is not in an error
4592 * state and has any incomplete reads. If you want to cancel reading
4593 * in the middle of a document, you need to flag an error on the reader
4594 * before destroying it (such as mpack_error_data).
4595 *
4596 * @see mpack_read_tag()
4597 * @see mpack_reader_flag_error()
4598 * @see mpack_error_data
4599 */
4601
4602/**
4603 * @}
4604 */
4605
4606/**
4607 * @name Callbacks
4608 * @{
4609 */
4610
4611/**
4612 * Sets the custom pointer to pass to the reader callbacks, such as fill
4613 * or teardown.
4614 *
4615 * @param reader The MPack reader.
4616 * @param context User data to pass to the reader callbacks.
4617 *
4618 * @see mpack_reader_context()
4619 */
4620MPACK_INLINE void mpack_reader_set_context(mpack_reader_t* reader, void* context) {
4621 reader->context = context;
4622}
4623
4624/**
4625 * Returns the custom context for reader callbacks.
4626 *
4627 * @see mpack_reader_set_context
4628 * @see mpack_reader_set_fill
4629 * @see mpack_reader_set_skip
4630 */
4631MPACK_INLINE void* mpack_reader_context(mpack_reader_t* reader) {
4632 return reader->context;
4633}
4634
4635/**
4636 * Sets the fill function to refill the data buffer when it runs out of data.
4637 *
4638 * If no fill function is used, truncated MessagePack data results in
4639 * mpack_error_invalid (since the buffer is assumed to contain a
4640 * complete MessagePack object.)
4641 *
4642 * If a fill function is used, truncated MessagePack data usually
4643 * results in mpack_error_io (since the fill function fails to get
4644 * the missing data.)
4645 *
4646 * This should normally be used with mpack_reader_set_context() to register
4647 * a custom pointer to pass to the fill function.
4648 *
4649 * @param reader The MPack reader.
4650 * @param fill The function to fetch additional data into the buffer.
4651 */
4653
4654/**
4655 * Sets the skip function to discard bytes from the source stream.
4656 *
4657 * It's not necessary to implement this function. If the stream is not
4658 * seekable, don't set a skip callback. The reader will fall back to
4659 * using the fill function instead.
4660 *
4661 * This should normally be used with mpack_reader_set_context() to register
4662 * a custom pointer to pass to the skip function.
4663 *
4664 * The skip function is ignored in size-optimized builds to reduce code
4665 * size. Data will be skipped with the fill function when necessary.
4666 *
4667 * @param reader The MPack reader.
4668 * @param skip The function to discard bytes from the source stream.
4669 */
4671
4672/**
4673 * Sets the error function to call when an error is flagged on the reader.
4674 *
4675 * This should normally be used with mpack_reader_set_context() to register
4676 * a custom pointer to pass to the error function.
4677 *
4678 * See the definition of mpack_reader_error_t for more information about
4679 * what you can do from an error callback.
4680 *
4681 * @see mpack_reader_error_t
4682 * @param reader The MPack reader.
4683 * @param error_fn The function to call when an error is flagged on the reader.
4684 */
4686 reader->error_fn = error_fn;
4687}
4688
4689/**
4690 * Sets the teardown function to call when the reader is destroyed.
4691 *
4692 * This should normally be used with mpack_reader_set_context() to register
4693 * a custom pointer to pass to the teardown function.
4694 *
4695 * @param reader The MPack reader.
4696 * @param teardown The function to call when the reader is destroyed.
4697 */
4699 reader->teardown = teardown;
4700}
4701
4702/**
4703 * @}
4704 */
4705
4706/**
4707 * @name Core Reader Functions
4708 * @{
4709 */
4710
4711/**
4712 * Queries the error state of the MPack reader.
4713 *
4714 * If a reader is in an error state, you should discard all data since the
4715 * last time the error flag was checked. The error flag cannot be cleared.
4716 */
4718 return reader->error;
4719}
4720
4721/**
4722 * Places the reader in the given error state, calling the error callback if one
4723 * is set.
4724 *
4725 * This allows you to externally flag errors, for example if you are validating
4726 * data as you read it.
4727 *
4728 * If the reader is already in an error state, this call is ignored and no
4729 * error callback is called.
4730 */
4732
4733/**
4734 * Places the reader in the given error state if the given error is not mpack_ok,
4735 * returning the resulting error state of the reader.
4736 *
4737 * This allows you to externally flag errors, for example if you are validating
4738 * data as you read it.
4739 *
4740 * If the given error is mpack_ok or if the reader is already in an error state,
4741 * this call is ignored and the actual error state of the reader is returned.
4742 */
4744 if (error != mpack_ok)
4745 mpack_reader_flag_error(reader, error);
4746 return mpack_reader_error(reader);
4747}
4748
4749/**
4750 * Returns bytes left in the reader's buffer.
4751 *
4752 * If you are done reading MessagePack data but there is other interesting data
4753 * following it, the reader may have buffered too much data. The number of bytes
4754 * remaining in the buffer and a pointer to the position of those bytes can be
4755 * queried here.
4756 *
4757 * If you know the length of the MPack chunk beforehand, it's better to instead
4758 * have your fill function limit the data it reads so that the reader does not
4759 * have extra data. In this case you can simply check that this returns zero.
4760 *
4761 * Returns 0 if the reader is in an error state.
4762 *
4763 * @param reader The MPack reader from which to query remaining data.
4764 * @param data [out] A pointer to the remaining data, or NULL.
4765 * @return The number of bytes remaining in the buffer.
4766 */
4767size_t mpack_reader_remaining(mpack_reader_t* reader, const char** data);
4768
4769/**
4770 * Reads a MessagePack object header (an MPack tag.)
4771 *
4772 * If an error occurs, the reader is placed in an error state and a
4773 * nil tag is returned. If the reader is already in an error state,
4774 * a nil tag is returned.
4775 *
4776 * If the type is compound (i.e. is a map, array, string, binary or
4777 * extension type), additional reads are required to get the contained
4778 * data, and the corresponding done function must be called when done.
4779 *
4780 * @note Maps in JSON are unordered, so it is recommended not to expect
4781 * a specific ordering for your map values in case your data is converted
4782 * to/from JSON.
4783 *
4784 * @see mpack_read_bytes()
4785 * @see mpack_done_array()
4786 * @see mpack_done_map()
4787 * @see mpack_done_str()
4788 * @see mpack_done_bin()
4789 * @see mpack_done_ext()
4790 */
4792
4793/**
4794 * Parses the next MessagePack object header (an MPack tag) without
4795 * advancing the reader.
4796 *
4797 * If an error occurs, the reader is placed in an error state and a
4798 * nil tag is returned. If the reader is already in an error state,
4799 * a nil tag is returned.
4800 *
4801 * @note Maps in JSON are unordered, so it is recommended not to expect
4802 * a specific ordering for your map values in case your data is converted
4803 * to/from JSON.
4804 *
4805 * @see mpack_read_tag()
4806 * @see mpack_discard()
4807 */
4809
4810/**
4811 * @}
4812 */
4813
4814/**
4815 * @name String and Data Functions
4816 * @{
4817 */
4818
4819/**
4820 * Skips bytes from the underlying stream. This is used only to
4821 * skip the contents of a string, binary blob or extension object.
4822 */
4824
4825/**
4826 * Reads bytes from a string, binary blob or extension object, copying
4827 * them into the given buffer.
4828 *
4829 * A str, bin or ext must have been opened by a call to mpack_read_tag()
4830 * which yielded one of these types, or by a call to an expect function
4831 * such as mpack_expect_str() or mpack_expect_bin().
4832 *
4833 * If an error occurs, the buffer contents are undefined.
4834 *
4835 * This can be called multiple times for a single str, bin or ext
4836 * to read the data in chunks. The total data read must add up
4837 * to the size of the object.
4838 *
4839 * @param reader The MPack reader
4840 * @param p The buffer in which to copy the bytes
4841 * @param count The number of bytes to read
4842 */
4843void mpack_read_bytes(mpack_reader_t* reader, char* p, size_t count);
4844
4845/**
4846 * Reads bytes from a string, ensures that the string is valid UTF-8,
4847 * and copies the bytes into the given buffer.
4848 *
4849 * A string must have been opened by a call to mpack_read_tag() which
4850 * yielded a string, or by a call to an expect function such as
4851 * mpack_expect_str().
4852 *
4853 * The given byte count must match the complete size of the string as
4854 * returned by the tag or expect function. You must ensure that the
4855 * buffer fits the data.
4856 *
4857 * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
4858 * WTF-8. Only pure UTF-8 is allowed.
4859 *
4860 * If an error occurs, the buffer contents are undefined.
4861 *
4862 * Unlike mpack_read_bytes(), this cannot be used to read the data in
4863 * chunks (since this might split a character's UTF-8 bytes, and the
4864 * reader does not keep track of the UTF-8 decoding state between reads.)
4865 *
4866 * @throws mpack_error_type if the string contains invalid UTF-8.
4867 */
4868void mpack_read_utf8(mpack_reader_t* reader, char* p, size_t byte_count);
4869
4870/**
4871 * Reads bytes from a string, ensures that the string contains no NUL
4872 * bytes, copies the bytes into the given buffer and adds a null-terminator.
4873 *
4874 * A string must have been opened by a call to mpack_read_tag() which
4875 * yielded a string, or by a call to an expect function such as
4876 * mpack_expect_str().
4877 *
4878 * The given byte count must match the size of the string as returned
4879 * by the tag or expect function. The string will only be copied if
4880 * the buffer is large enough to store it.
4881 *
4882 * If an error occurs, the buffer will contain an empty string.
4883 *
4884 * @note If you know the object will be a string before reading it,
4885 * it is highly recommended to use mpack_expect_cstr() instead.
4886 * Alternatively you could use mpack_peek_tag() and call
4887 * mpack_expect_cstr() if it's a string.
4888 *
4889 * @throws mpack_error_too_big if the string plus null-terminator is larger than the given buffer size
4890 * @throws mpack_error_type if the string contains a null byte.
4891 *
4892 * @see mpack_peek_tag()
4893 * @see mpack_expect_cstr()
4894 * @see mpack_expect_utf8_cstr()
4895 */
4896void mpack_read_cstr(mpack_reader_t* reader, char* buf, size_t buffer_size, size_t byte_count);
4897
4898/**
4899 * Reads bytes from a string, ensures that the string is valid UTF-8
4900 * with no NUL bytes, copies the bytes into the given buffer and adds a
4901 * null-terminator.
4902 *
4903 * A string must have been opened by a call to mpack_read_tag() which
4904 * yielded a string, or by a call to an expect function such as
4905 * mpack_expect_str().
4906 *
4907 * The given byte count must match the size of the string as returned
4908 * by the tag or expect function. The string will only be copied if
4909 * the buffer is large enough to store it.
4910 *
4911 * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
4912 * WTF-8. Only pure UTF-8 is allowed, but without the NUL character, since
4913 * it cannot be represented in a null-terminated string.
4914 *
4915 * If an error occurs, the buffer will contain an empty string.
4916 *
4917 * @note If you know the object will be a string before reading it,
4918 * it is highly recommended to use mpack_expect_utf8_cstr() instead.
4919 * Alternatively you could use mpack_peek_tag() and call
4920 * mpack_expect_utf8_cstr() if it's a string.
4921 *
4922 * @throws mpack_error_too_big if the string plus null-terminator is larger than the given buffer size
4923 * @throws mpack_error_type if the string contains invalid UTF-8 or a null byte.
4924 *
4925 * @see mpack_peek_tag()
4926 * @see mpack_expect_utf8_cstr()
4927 */
4928void mpack_read_utf8_cstr(mpack_reader_t* reader, char* buf, size_t buffer_size, size_t byte_count);
4929
4930#ifdef MPACK_MALLOC
4931/** @cond */
4932// This can optionally add a null-terminator, but it does not check
4933// whether the data contains null bytes. This must be done separately
4934// in a cstring read function (possibly as part of a UTF-8 check.)
4935char* mpack_read_bytes_alloc_impl(mpack_reader_t* reader, size_t count, bool null_terminated);
4936/** @endcond */
4937
4938/**
4939 * Reads bytes from a string, binary blob or extension object, allocating
4940 * storage for them and returning the allocated pointer.
4941 *
4942 * The allocated string must be freed with MPACK_FREE() (or simply free()
4943 * if MPack's allocator hasn't been customized.)
4944 *
4945 * Returns NULL if any error occurs, or if count is zero.
4946 */
4947MPACK_INLINE char* mpack_read_bytes_alloc(mpack_reader_t* reader, size_t count) {
4948 return mpack_read_bytes_alloc_impl(reader, count, false);
4949}
4950#endif
4951
4952/**
4953 * Reads bytes from a string, binary blob or extension object in-place in
4954 * the buffer. This can be used to avoid copying the data.
4955 *
4956 * A str, bin or ext must have been opened by a call to mpack_read_tag()
4957 * which yielded one of these types, or by a call to an expect function
4958 * such as mpack_expect_str() or mpack_expect_bin().
4959 *
4960 * If the bytes are from a string, the string is not null-terminated! Use
4961 * mpack_read_cstr() to copy the string into a buffer and add a null-terminator.
4962 *
4963 * The returned pointer is invalidated on the next read, or when the buffer
4964 * is destroyed.
4965 *
4966 * The reader will move data around in the buffer if needed to ensure that
4967 * the pointer can always be returned, so this should only be used if
4968 * count is very small compared to the buffer size. If you need to check
4969 * whether a small size is reasonable (for example you intend to handle small and
4970 * large sizes differently), you can call mpack_should_read_bytes_inplace().
4971 *
4972 * This can be called multiple times for a single str, bin or ext
4973 * to read the data in chunks. The total data read must add up
4974 * to the size of the object.
4975 *
4976 * NULL is returned if the reader is in an error state.
4977 *
4978 * @throws mpack_error_too_big if the requested size is larger than the buffer size
4979 *
4980 * @see mpack_should_read_bytes_inplace()
4981 */
4982const char* mpack_read_bytes_inplace(mpack_reader_t* reader, size_t count);
4983
4984/**
4985 * Reads bytes from a string in-place in the buffer and ensures they are
4986 * valid UTF-8. This can be used to avoid copying the data.
4987 *
4988 * A string must have been opened by a call to mpack_read_tag() which
4989 * yielded a string, or by a call to an expect function such as
4990 * mpack_expect_str().
4991 *
4992 * The string is not null-terminated! Use mpack_read_utf8_cstr() to
4993 * copy the string into a buffer and add a null-terminator.
4994 *
4995 * The returned pointer is invalidated on the next read, or when the buffer
4996 * is destroyed.
4997 *
4998 * The reader will move data around in the buffer if needed to ensure that
4999 * the pointer can always be returned, so this should only be used if
5000 * count is very small compared to the buffer size. If you need to check
5001 * whether a small size is reasonable (for example you intend to handle small and
5002 * large sizes differently), you can call mpack_should_read_bytes_inplace().
5003 *
5004 * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
5005 * WTF-8. Only pure UTF-8 is allowed.
5006 *
5007 * Unlike mpack_read_bytes_inplace(), this cannot be used to read the data in
5008 * chunks (since this might split a character's UTF-8 bytes, and the
5009 * reader does not keep track of the UTF-8 decoding state between reads.)
5010 *
5011 * NULL is returned if the reader is in an error state.
5012 *
5013 * @throws mpack_error_type if the string contains invalid UTF-8
5014 * @throws mpack_error_too_big if the requested size is larger than the buffer size
5015 *
5016 * @see mpack_should_read_bytes_inplace()
5017 */
5018const char* mpack_read_utf8_inplace(mpack_reader_t* reader, size_t count);
5019
5020/**
5021 * Returns true if it's a good idea to read the given number of bytes
5022 * in-place.
5023 *
5024 * If the read will be larger than some small fraction of the buffer size,
5025 * this will return false to avoid shuffling too much data back and forth
5026 * in the buffer.
5027 *
5028 * Use this if you're expecting arbitrary size data, and you want to read
5029 * in-place for the best performance when possible but will fall back to
5030 * a normal read if the data is too large.
5031 *
5032 * @see mpack_read_bytes_inplace()
5033 */
5034MPACK_INLINE bool mpack_should_read_bytes_inplace(mpack_reader_t* reader, size_t count) {
5035 return (reader->size == 0 || count <= reader->size / MPACK_READER_SMALL_FRACTION_DENOMINATOR);
5036}
5037
5038#if MPACK_EXTENSIONS
5039/**
5040 * Reads a timestamp contained in an ext object of the given size, closing the
5041 * ext type.
5042 *
5043 * An ext object of exttype @ref MPACK_EXTTYPE_TIMESTAMP must have been opened
5044 * by a call to e.g. mpack_read_tag() or mpack_expect_ext().
5045 *
5046 * You must NOT call mpack_done_ext() after calling this. A timestamp ext
5047 * object can only contain a single timestamp value, so this calls
5048 * mpack_done_ext() automatically.
5049 *
5050 * @note This requires @ref MPACK_EXTENSIONS.
5051 *
5052 * @throws mpack_error_invalid if the size is not one of the supported
5053 * timestamp sizes, or if the nanoseconds are out of range.
5054 */
5055mpack_timestamp_t mpack_read_timestamp(mpack_reader_t* reader, size_t size);
5056#endif
5057
5058/**
5059 * @}
5060 */
5061
5062/**
5063 * @name Core Reader Functions
5064 * @{
5065 */
5066
5067#if MPACK_READ_TRACKING
5068/**
5069 * Finishes reading the given type.
5070 *
5071 * This will track reads to ensure that the correct number of elements
5072 * or bytes are read.
5073 */
5075#else
5077 MPACK_UNUSED(reader);
5078 MPACK_UNUSED(type);
5079}
5080#endif
5081
5082/**
5083 * Finishes reading an array.
5084 *
5085 * This will track reads to ensure that the correct number of elements are read.
5086 */
5087MPACK_INLINE void mpack_done_array(mpack_reader_t* reader) {
5089}
5090
5091/**
5092 * @fn mpack_done_map(mpack_reader_t* reader)
5093 *
5094 * Finishes reading a map.
5095 *
5096 * This will track reads to ensure that the correct number of elements are read.
5097 */
5098MPACK_INLINE void mpack_done_map(mpack_reader_t* reader) {
5100}
5101
5102/**
5103 * @fn mpack_done_str(mpack_reader_t* reader)
5104 *
5105 * Finishes reading a string.
5106 *
5107 * This will track reads to ensure that the correct number of bytes are read.
5108 */
5109MPACK_INLINE void mpack_done_str(mpack_reader_t* reader) {
5111}
5112
5113/**
5114 * @fn mpack_done_bin(mpack_reader_t* reader)
5115 *
5116 * Finishes reading a binary data blob.
5117 *
5118 * This will track reads to ensure that the correct number of bytes are read.
5119 */
5120MPACK_INLINE void mpack_done_bin(mpack_reader_t* reader) {
5122}
5123
5124#if MPACK_EXTENSIONS
5125/**
5126 * @fn mpack_done_ext(mpack_reader_t* reader)
5127 *
5128 * Finishes reading an extended type binary data blob.
5129 *
5130 * This will track reads to ensure that the correct number of bytes are read.
5131 *
5132 * @note This requires @ref MPACK_EXTENSIONS.
5133 */
5134MPACK_INLINE void mpack_done_ext(mpack_reader_t* reader) {
5135 mpack_done_type(reader, mpack_type_ext);
5136}
5137#endif
5138
5139/**
5140 * Reads and discards the next object. This will read and discard all
5141 * contained data as well if it is a compound type.
5142 */
5144
5145/**
5146 * @}
5147 */
5148
5149/** @cond */
5150
5151#if MPACK_DEBUG && MPACK_STDIO
5152/**
5153 * @name Debugging Functions
5154 * @{
5155 */
5156/*
5157 * Converts a blob of MessagePack to a pseudo-JSON string for debugging
5158 * purposes, placing the result in the given buffer with a null-terminator.
5159 *
5160 * If the buffer does not have enough space, the result will be truncated (but
5161 * it is guaranteed to be null-terminated.)
5162 *
5163 * This is only available in debug mode, and only if stdio is available (since
5164 * it uses snprintf().) It's strictly for debugging purposes.
5165 */
5166void mpack_print_data_to_buffer(const char* data, size_t data_size, char* buffer, size_t buffer_size);
5167
5168/*
5169 * Converts a node to pseudo-JSON for debugging purposes, calling the given
5170 * callback as many times as is necessary to output the character data.
5171 *
5172 * No null-terminator or trailing newline will be written.
5173 *
5174 * This is only available in debug mode, and only if stdio is available (since
5175 * it uses snprintf().) It's strictly for debugging purposes.
5176 */
5177void mpack_print_data_to_callback(const char* data, size_t size, mpack_print_callback_t callback, void* context);
5178
5179/*
5180 * Converts a blob of MessagePack to pseudo-JSON for debugging purposes
5181 * and pretty-prints it to the given file.
5182 */
5183void mpack_print_data_to_file(const char* data, size_t len, FILE* file);
5184
5185/*
5186 * Converts a blob of MessagePack to pseudo-JSON for debugging purposes
5187 * and pretty-prints it to stdout.
5188 */
5189MPACK_INLINE void mpack_print_data_to_stdout(const char* data, size_t len) {
5190 mpack_print_data_to_file(data, len, stdout);
5191}
5192
5193/*
5194 * Converts the MessagePack contained in the given `FILE*` to pseudo-JSON for
5195 * debugging purposes, calling the given callback as many times as is necessary
5196 * to output the character data.
5197 */
5198void mpack_print_stdfile_to_callback(FILE* file, mpack_print_callback_t callback, void* context);
5199
5200/*
5201 * Deprecated.
5202 *
5203 * \deprecated Renamed to mpack_print_data_to_stdout().
5204 */
5205MPACK_INLINE void mpack_print(const char* data, size_t len) {
5206 mpack_print_data_to_stdout(data, len);
5207}
5208
5209/**
5210 * @}
5211 */
5212#endif
5213
5214/** @endcond */
5215
5216/**
5217 * @}
5218 */
5219
5220
5221
5222#if MPACK_INTERNAL
5223
5224bool mpack_reader_ensure_straddle(mpack_reader_t* reader, size_t count);
5225
5226/*
5227 * Ensures there are at least @c count bytes left in the
5228 * data, raising an error and returning false if more
5229 * data cannot be made available.
5230 */
5231MPACK_INLINE bool mpack_reader_ensure(mpack_reader_t* reader, size_t count) {
5232 mpack_assert(count != 0, "cannot ensure zero bytes!");
5233 mpack_assert(reader->error == mpack_ok, "reader cannot be in an error state!");
5234
5235 if (count <= (size_t)(reader->end - reader->data))
5236 return true;
5237 return mpack_reader_ensure_straddle(reader, count);
5238}
5239
5240void mpack_read_native_straddle(mpack_reader_t* reader, char* p, size_t count);
5241
5242// Reads count bytes into p, deferring to mpack_read_native_straddle() if more
5243// bytes are needed than are available in the buffer.
5244MPACK_INLINE void mpack_read_native(mpack_reader_t* reader, char* p, size_t count) {
5245 mpack_assert(count == 0 || p != NULL, "data pointer for %i bytes is NULL", (int)count);
5246
5247 if (count > (size_t)(reader->end - reader->data)) {
5248 mpack_read_native_straddle(reader, p, count);
5249 } else {
5250 mpack_memcpy(p, reader->data, count);
5251 reader->data += count;
5252 }
5253}
5254
5255#if MPACK_READ_TRACKING
5256#define MPACK_READER_TRACK(reader, error_expr) \
5257 (((reader)->error == mpack_ok) ? mpack_reader_flag_if_error((reader), (error_expr)) : (reader)->error)
5258#else
5259#define MPACK_READER_TRACK(reader, error_expr) (MPACK_UNUSED(reader), mpack_ok)
5260#endif
5261
5262MPACK_INLINE mpack_error_t mpack_reader_track_element(mpack_reader_t* reader) {
5263 return MPACK_READER_TRACK(reader, mpack_track_element(&reader->track, true));
5264}
5265
5266MPACK_INLINE mpack_error_t mpack_reader_track_peek_element(mpack_reader_t* reader) {
5267 return MPACK_READER_TRACK(reader, mpack_track_peek_element(&reader->track, true));
5268}
5269
5270MPACK_INLINE mpack_error_t mpack_reader_track_bytes(mpack_reader_t* reader, size_t count) {
5271 MPACK_UNUSED(count);
5272 return MPACK_READER_TRACK(reader, mpack_track_bytes(&reader->track, true, count));
5273}
5274
5275MPACK_INLINE mpack_error_t mpack_reader_track_str_bytes_all(mpack_reader_t* reader, size_t count) {
5276 MPACK_UNUSED(count);
5277 return MPACK_READER_TRACK(reader, mpack_track_str_bytes_all(&reader->track, true, count));
5278}
5279
5280#endif
5281
5282
5283
5284#endif
5285
5286MPACK_EXTERN_C_END
5287MPACK_SILENCE_WARNINGS_END
5288
5289#endif
5290
5291
5292/* mpack/mpack-expect.h.h */
5293
5294/**
5295 * @file
5296 *
5297 * Declares the MPack static Expect API.
5298 */
5299
5300#ifndef MPACK_EXPECT_H
5301#define MPACK_EXPECT_H 1
5302
5303/* #include "mpack-reader.h" */
5304
5305MPACK_SILENCE_WARNINGS_BEGIN
5306MPACK_EXTERN_C_BEGIN
5307
5308#if MPACK_EXPECT
5309
5310#if !MPACK_READER
5311#error "MPACK_EXPECT requires MPACK_READER."
5312#endif
5313
5314/**
5315 * @defgroup mpack_expect Expect API
5316 * @ingroup mpack
5317 *
5318 * The MPack Expect API allows you to easily read MessagePack data when you
5319 * expect it to follow a predefined schema.
5320 *
5321 * @note If you are not writing code for an embedded device (or otherwise do
5322 * not need maximum performance with minimal memory usage), you should not use
5323 * this. You probably want to use the @link node Node API@endlink instead.
5324 *
5325 * See @ref docs/expect.md for examples.
5326 *
5327 * The main purpose of the Expect API is convenience, so the API is lax. It
5328 * automatically converts between similar types where there is no loss of
5329 * precision.
5330 *
5331 * When using any of the expect functions, if the type or value of what was
5332 * read does not match what is expected, @ref mpack_error_type is raised.
5333 *
5334 * @{
5335 */
5336
5337/**
5338 * @name Basic Number Functions
5339 * @{
5340 */
5341
5342/**
5343 * Reads an 8-bit unsigned integer.
5344 *
5345 * The underlying type may be an integer type of any size and signedness,
5346 * as long as the value can be represented in an 8-bit unsigned int.
5347 *
5348 * Returns zero if an error occurs.
5349 */
5351
5352/**
5353 * Reads a 16-bit unsigned integer.
5354 *
5355 * The underlying type may be an integer type of any size and signedness,
5356 * as long as the value can be represented in a 16-bit unsigned int.
5357 *
5358 * Returns zero if an error occurs.
5359 */
5361
5362/**
5363 * Reads a 32-bit unsigned integer.
5364 *
5365 * The underlying type may be an integer type of any size and signedness,
5366 * as long as the value can be represented in a 32-bit unsigned int.
5367 *
5368 * Returns zero if an error occurs.
5369 */
5371
5372/**
5373 * Reads a 64-bit unsigned integer.
5374 *
5375 * The underlying type may be an integer type of any size and signedness,
5376 * as long as the value can be represented in a 64-bit unsigned int.
5377 *
5378 * Returns zero if an error occurs.
5379 */
5381
5382/**
5383 * Reads an 8-bit signed integer.
5384 *
5385 * The underlying type may be an integer type of any size and signedness,
5386 * as long as the value can be represented in an 8-bit signed int.
5387 *
5388 * Returns zero if an error occurs.
5389 */
5391
5392/**
5393 * Reads a 16-bit signed integer.
5394 *
5395 * The underlying type may be an integer type of any size and signedness,
5396 * as long as the value can be represented in a 16-bit signed int.
5397 *
5398 * Returns zero if an error occurs.
5399 */
5401
5402/**
5403 * Reads a 32-bit signed integer.
5404 *
5405 * The underlying type may be an integer type of any size and signedness,
5406 * as long as the value can be represented in a 32-bit signed int.
5407 *
5408 * Returns zero if an error occurs.
5409 */
5411
5412/**
5413 * Reads a 64-bit signed integer.
5414 *
5415 * The underlying type may be an integer type of any size and signedness,
5416 * as long as the value can be represented in a 64-bit signed int.
5417 *
5418 * Returns zero if an error occurs.
5419 */
5421
5422#if MPACK_FLOAT
5423/**
5424 * Reads a number, returning the value as a float. The underlying value can be an
5425 * integer, float or double; the value is converted to a float.
5426 *
5427 * @note Reading a double or a large integer with this function can incur a
5428 * loss of precision.
5429 *
5430 * @throws mpack_error_type if the underlying value is not a float, double or integer.
5431 */
5433#endif
5434
5435#if MPACK_DOUBLE
5436/**
5437 * Reads a number, returning the value as a double. The underlying value can be an
5438 * integer, float or double; the value is converted to a double.
5439 *
5440 * @note Reading a very large integer with this function can incur a
5441 * loss of precision.
5442 *
5443 * @throws mpack_error_type if the underlying value is not a float, double or integer.
5444 */
5446#endif
5447
5448#if MPACK_FLOAT
5449/**
5450 * Reads a float. The underlying value must be a float, not a double or an integer.
5451 * This ensures no loss of precision can occur.
5452 *
5453 * @throws mpack_error_type if the underlying value is not a float.
5454 */
5456#endif
5457
5458#if MPACK_DOUBLE
5459/**
5460 * Reads a double. The underlying value must be a float or double, not an integer.
5461 * This ensures no loss of precision can occur.
5462 *
5463 * @throws mpack_error_type if the underlying value is not a float or double.
5464 */
5466#endif
5467
5468#if !MPACK_FLOAT
5469/**
5470 * Reads a float as a raw uint32_t. The underlying value must be a float, not a
5471 * double or an integer.
5472 *
5473 * @throws mpack_error_type if the underlying value is not a float.
5474 */
5475uint32_t mpack_expect_raw_float(mpack_reader_t* reader);
5476#endif
5477
5478#if !MPACK_DOUBLE
5479/**
5480 * Reads a double as a raw uint64_t. The underlying value must be a double, not a
5481 * float or an integer.
5482 *
5483 * @throws mpack_error_type if the underlying value is not a double.
5484 */
5485uint64_t mpack_expect_raw_double(mpack_reader_t* reader);
5486#endif
5487
5488/**
5489 * @}
5490 */
5491
5492/**
5493 * @name Ranged Number Functions
5494 * @{
5495 */
5496
5497/**
5498 * Reads an 8-bit unsigned integer, ensuring that it falls within the given range.
5499 *
5500 * The underlying type may be an integer type of any size and signedness,
5501 * as long as the value can be represented in an 8-bit unsigned int.
5502 *
5503 * Returns min_value if an error occurs.
5504 */
5505uint8_t mpack_expect_u8_range(mpack_reader_t* reader, uint8_t min_value, uint8_t max_value);
5506
5507/**
5508 * Reads a 16-bit unsigned integer, ensuring that it falls within the given range.
5509 *
5510 * The underlying type may be an integer type of any size and signedness,
5511 * as long as the value can be represented in a 16-bit unsigned int.
5512 *
5513 * Returns min_value if an error occurs.
5514 */
5515uint16_t mpack_expect_u16_range(mpack_reader_t* reader, uint16_t min_value, uint16_t max_value);
5516
5517/**
5518 * Reads a 32-bit unsigned integer, ensuring that it falls within the given range.
5519 *
5520 * The underlying type may be an integer type of any size and signedness,
5521 * as long as the value can be represented in a 32-bit unsigned int.
5522 *
5523 * Returns min_value if an error occurs.
5524 */
5525uint32_t mpack_expect_u32_range(mpack_reader_t* reader, uint32_t min_value, uint32_t max_value);
5526
5527/**
5528 * Reads a 64-bit unsigned integer, ensuring that it falls within the given range.
5529 *
5530 * The underlying type may be an integer type of any size and signedness,
5531 * as long as the value can be represented in a 64-bit unsigned int.
5532 *
5533 * Returns min_value if an error occurs.
5534 */
5535uint64_t mpack_expect_u64_range(mpack_reader_t* reader, uint64_t min_value, uint64_t max_value);
5536
5537/**
5538 * Reads an unsigned integer, ensuring that it falls within the given range.
5539 *
5540 * The underlying type may be an integer type of any size and signedness,
5541 * as long as the value can be represented in an unsigned int.
5542 *
5543 * Returns min_value if an error occurs.
5544 */
5545MPACK_INLINE unsigned int mpack_expect_uint_range(mpack_reader_t* reader, unsigned int min_value, unsigned int max_value) {
5546 // This should be true at compile-time, so this just wraps the 32-bit
5547 // function. We fallback to 64-bit if for some reason sizeof(int) isn't 4.
5548 if (sizeof(unsigned int) == 4)
5549 return (unsigned int)mpack_expect_u32_range(reader, (uint32_t)min_value, (uint32_t)max_value);
5550 return (unsigned int)mpack_expect_u64_range(reader, min_value, max_value);
5551}
5552
5553/**
5554 * Reads an 8-bit unsigned integer, ensuring that it is at most @a max_value.
5555 *
5556 * The underlying type may be an integer type of any size and signedness,
5557 * as long as the value can be represented in an 8-bit unsigned int.
5558 *
5559 * Returns 0 if an error occurs.
5560 */
5561MPACK_INLINE uint8_t mpack_expect_u8_max(mpack_reader_t* reader, uint8_t max_value) {
5562 return mpack_expect_u8_range(reader, 0, max_value);
5563}
5564
5565/**
5566 * Reads a 16-bit unsigned integer, ensuring that it is at most @a max_value.
5567 *
5568 * The underlying type may be an integer type of any size and signedness,
5569 * as long as the value can be represented in a 16-bit unsigned int.
5570 *
5571 * Returns 0 if an error occurs.
5572 */
5573MPACK_INLINE uint16_t mpack_expect_u16_max(mpack_reader_t* reader, uint16_t max_value) {
5574 return mpack_expect_u16_range(reader, 0, max_value);
5575}
5576
5577/**
5578 * Reads a 32-bit unsigned integer, ensuring that it is at most @a max_value.
5579 *
5580 * The underlying type may be an integer type of any size and signedness,
5581 * as long as the value can be represented in a 32-bit unsigned int.
5582 *
5583 * Returns 0 if an error occurs.
5584 */
5585MPACK_INLINE uint32_t mpack_expect_u32_max(mpack_reader_t* reader, uint32_t max_value) {
5586 return mpack_expect_u32_range(reader, 0, max_value);
5587}
5588
5589/**
5590 * Reads a 64-bit unsigned integer, ensuring that it is at most @a max_value.
5591 *
5592 * The underlying type may be an integer type of any size and signedness,
5593 * as long as the value can be represented in a 64-bit unsigned int.
5594 *
5595 * Returns 0 if an error occurs.
5596 */
5597MPACK_INLINE uint64_t mpack_expect_u64_max(mpack_reader_t* reader, uint64_t max_value) {
5598 return mpack_expect_u64_range(reader, 0, max_value);
5599}
5600
5601/**
5602 * Reads an unsigned integer, ensuring that it is at most @a max_value.
5603 *
5604 * The underlying type may be an integer type of any size and signedness,
5605 * as long as the value can be represented in an unsigned int.
5606 *
5607 * Returns 0 if an error occurs.
5608 */
5609MPACK_INLINE unsigned int mpack_expect_uint_max(mpack_reader_t* reader, unsigned int max_value) {
5610 return mpack_expect_uint_range(reader, 0, max_value);
5611}
5612
5613/**
5614 * Reads an 8-bit signed integer, ensuring that it falls within the given range.
5615 *
5616 * The underlying type may be an integer type of any size and signedness,
5617 * as long as the value can be represented in an 8-bit signed int.
5618 *
5619 * Returns min_value if an error occurs.
5620 */
5621int8_t mpack_expect_i8_range(mpack_reader_t* reader, int8_t min_value, int8_t max_value);
5622
5623/**
5624 * Reads a 16-bit signed integer, ensuring that it falls within the given range.
5625 *
5626 * The underlying type may be an integer type of any size and signedness,
5627 * as long as the value can be represented in a 16-bit signed int.
5628 *
5629 * Returns min_value if an error occurs.
5630 */
5631int16_t mpack_expect_i16_range(mpack_reader_t* reader, int16_t min_value, int16_t max_value);
5632
5633/**
5634 * Reads a 32-bit signed integer, ensuring that it falls within the given range.
5635 *
5636 * The underlying type may be an integer type of any size and signedness,
5637 * as long as the value can be represented in a 32-bit signed int.
5638 *
5639 * Returns min_value if an error occurs.
5640 */
5641int32_t mpack_expect_i32_range(mpack_reader_t* reader, int32_t min_value, int32_t max_value);
5642
5643/**
5644 * Reads a 64-bit signed integer, ensuring that it falls within the given range.
5645 *
5646 * The underlying type may be an integer type of any size and signedness,
5647 * as long as the value can be represented in a 64-bit signed int.
5648 *
5649 * Returns min_value if an error occurs.
5650 */
5651int64_t mpack_expect_i64_range(mpack_reader_t* reader, int64_t min_value, int64_t max_value);
5652
5653/**
5654 * Reads a signed integer, ensuring that it falls within the given range.
5655 *
5656 * The underlying type may be an integer type of any size and signedness,
5657 * as long as the value can be represented in a signed int.
5658 *
5659 * Returns min_value if an error occurs.
5660 */
5661MPACK_INLINE int mpack_expect_int_range(mpack_reader_t* reader, int min_value, int max_value) {
5662 // This should be true at compile-time, so this just wraps the 32-bit
5663 // function. We fallback to 64-bit if for some reason sizeof(int) isn't 4.
5664 if (sizeof(int) == 4)
5665 return (int)mpack_expect_i32_range(reader, (int32_t)min_value, (int32_t)max_value);
5666 return (int)mpack_expect_i64_range(reader, min_value, max_value);
5667}
5668
5669/**
5670 * Reads an 8-bit signed integer, ensuring that it is at least zero and at
5671 * most @a max_value.
5672 *
5673 * The underlying type may be an integer type of any size and signedness,
5674 * as long as the value can be represented in an 8-bit signed int.
5675 *
5676 * Returns 0 if an error occurs.
5677 */
5678MPACK_INLINE int8_t mpack_expect_i8_max(mpack_reader_t* reader, int8_t max_value) {
5679 return mpack_expect_i8_range(reader, 0, max_value);
5680}
5681
5682/**
5683 * Reads a 16-bit signed integer, ensuring that it is at least zero and at
5684 * most @a max_value.
5685 *
5686 * The underlying type may be an integer type of any size and signedness,
5687 * as long as the value can be represented in a 16-bit signed int.
5688 *
5689 * Returns 0 if an error occurs.
5690 */
5691MPACK_INLINE int16_t mpack_expect_i16_max(mpack_reader_t* reader, int16_t max_value) {
5692 return mpack_expect_i16_range(reader, 0, max_value);
5693}
5694
5695/**
5696 * Reads a 32-bit signed integer, ensuring that it is at least zero and at
5697 * most @a max_value.
5698 *
5699 * The underlying type may be an integer type of any size and signedness,
5700 * as long as the value can be represented in a 32-bit signed int.
5701 *
5702 * Returns 0 if an error occurs.
5703 */
5704MPACK_INLINE int32_t mpack_expect_i32_max(mpack_reader_t* reader, int32_t max_value) {
5705 return mpack_expect_i32_range(reader, 0, max_value);
5706}
5707
5708/**
5709 * Reads a 64-bit signed integer, ensuring that it is at least zero and at
5710 * most @a max_value.
5711 *
5712 * The underlying type may be an integer type of any size and signedness,
5713 * as long as the value can be represented in a 64-bit signed int.
5714 *
5715 * Returns 0 if an error occurs.
5716 */
5717MPACK_INLINE int64_t mpack_expect_i64_max(mpack_reader_t* reader, int64_t max_value) {
5718 return mpack_expect_i64_range(reader, 0, max_value);
5719}
5720
5721/**
5722 * Reads an int, ensuring that it is at least zero and at most @a max_value.
5723 *
5724 * The underlying type may be an integer type of any size and signedness,
5725 * as long as the value can be represented in a signed int.
5726 *
5727 * Returns 0 if an error occurs.
5728 */
5729MPACK_INLINE int mpack_expect_int_max(mpack_reader_t* reader, int max_value) {
5730 return mpack_expect_int_range(reader, 0, max_value);
5731}
5732
5733#if MPACK_FLOAT
5734/**
5735 * Reads a number, ensuring that it falls within the given range and returning
5736 * the value as a float. The underlying value can be an integer, float or
5737 * double; the value is converted to a float.
5738 *
5739 * @note Reading a double or a large integer with this function can incur a
5740 * loss of precision.
5741 *
5742 * @throws mpack_error_type if the underlying value is not a float, double or integer.
5743 */
5744float mpack_expect_float_range(mpack_reader_t* reader, float min_value, float max_value);
5745#endif
5746
5747#if MPACK_DOUBLE
5748/**
5749 * Reads a number, ensuring that it falls within the given range and returning
5750 * the value as a double. The underlying value can be an integer, float or
5751 * double; the value is converted to a double.
5752 *
5753 * @note Reading a very large integer with this function can incur a
5754 * loss of precision.
5755 *
5756 * @throws mpack_error_type if the underlying value is not a float, double or integer.
5757 */
5758double mpack_expect_double_range(mpack_reader_t* reader, double min_value, double max_value);
5759#endif
5760
5761/**
5762 * @}
5763 */
5764
5765
5766
5767// These are additional Basic Number functions that wrap inline range functions.
5768
5769/**
5770 * @name Basic Number Functions
5771 * @{
5772 */
5773
5774/**
5775 * Reads an unsigned int.
5776 *
5777 * The underlying type may be an integer type of any size and signedness,
5778 * as long as the value can be represented in an unsigned int.
5779 *
5780 * Returns zero if an error occurs.
5781 */
5782MPACK_INLINE unsigned int mpack_expect_uint(mpack_reader_t* reader) {
5783
5784 // This should be true at compile-time, so this just wraps the 32-bit function.
5785 if (sizeof(unsigned int) == 4)
5786 return (unsigned int)mpack_expect_u32(reader);
5787
5788 // Otherwise we wrap the max function to ensure it fits.
5789 return (unsigned int)mpack_expect_u64_max(reader, MPACK_UINT_MAX);
5790
5791}
5792
5793/**
5794 * Reads a signed int.
5795 *
5796 * The underlying type may be an integer type of any size and signedness,
5797 * as long as the value can be represented in a signed int.
5798 *
5799 * Returns zero if an error occurs.
5800 */
5801MPACK_INLINE int mpack_expect_int(mpack_reader_t* reader) {
5802
5803 // This should be true at compile-time, so this just wraps the 32-bit function.
5804 if (sizeof(int) == 4)
5805 return (int)mpack_expect_i32(reader);
5806
5807 // Otherwise we wrap the range function to ensure it fits.
5808 return (int)mpack_expect_i64_range(reader, MPACK_INT_MIN, MPACK_INT_MAX);
5809
5810}
5811
5812/**
5813 * @}
5814 */
5815
5816
5817
5818/**
5819 * @name Matching Number Functions
5820 * @{
5821 */
5822
5823/**
5824 * Reads an unsigned integer, ensuring that it exactly matches the given value.
5825 *
5826 * mpack_error_type is raised if the value is not representable as an unsigned
5827 * integer or if it does not exactly match the given value.
5828 */
5829void mpack_expect_uint_match(mpack_reader_t* reader, uint64_t value);
5830
5831/**
5832 * Reads a signed integer, ensuring that it exactly matches the given value.
5833 *
5834 * mpack_error_type is raised if the value is not representable as a signed
5835 * integer or if it does not exactly match the given value.
5836 */
5837void mpack_expect_int_match(mpack_reader_t* reader, int64_t value);
5838
5839/**
5840 * @}
5841 */
5842
5843/**
5844 * @name Other Basic Types
5845 * @{
5846 */
5847
5848/**
5849 * Reads a nil, raising @ref mpack_error_type if the value is not nil.
5850 */
5852
5853/**
5854 * Reads a boolean.
5855 *
5856 * @note Integers will raise mpack_error_type; the value must be strictly a boolean.
5857 */
5859
5860/**
5861 * Reads a boolean, raising @ref mpack_error_type if its value is not @c true.
5862 */
5864
5865/**
5866 * Reads a boolean, raising @ref mpack_error_type if its value is not @c false.
5867 */
5869
5870/**
5871 * @}
5872 */
5873
5874/**
5875 * @name Extension Functions
5876 * @{
5877 */
5878
5879#if MPACK_EXTENSIONS
5880/**
5881 * Reads a timestamp.
5882 *
5883 * @note This requires @ref MPACK_EXTENSIONS.
5884 */
5885mpack_timestamp_t mpack_expect_timestamp(mpack_reader_t* reader);
5886
5887/**
5888 * Reads a timestamp in seconds, truncating the nanoseconds (if any).
5889 *
5890 * @note This requires @ref MPACK_EXTENSIONS.
5891 */
5892int64_t mpack_expect_timestamp_truncate(mpack_reader_t* reader);
5893#endif
5894
5895/**
5896 * @}
5897 */
5898
5899/**
5900 * @name Compound Types
5901 * @{
5902 */
5903
5904/**
5905 * Reads the start of a map, returning its element count.
5906 *
5907 * A number of values follow equal to twice the element count of the map,
5908 * alternating between keys and values. @ref mpack_done_map() must be called
5909 * once all elements have been read.
5910 *
5911 * @note Maps in JSON are unordered, so it is recommended not to expect
5912 * a specific ordering for your map values in case your data is converted
5913 * to/from JSON.
5914 *
5915 * @warning This call is dangerous! It does not have a size limit, and it
5916 * does not have any way of checking whether there is enough data in the
5917 * message (since the data could be coming from a stream.) When looping
5918 * through the map's contents, you must check for errors on each iteration
5919 * of the loop. Otherwise an attacker could craft a message declaring a map
5920 * of a billion elements which would throw your parsing code into an
5921 * infinite loop! You should strongly consider using mpack_expect_map_max()
5922 * with a safe maximum size instead.
5923 *
5924 * @throws mpack_error_type if the value is not a map.
5925 */
5927
5928/**
5929 * Reads the start of a map with a number of elements in the given range, returning
5930 * its element count.
5931 *
5932 * A number of values follow equal to twice the element count of the map,
5933 * alternating between keys and values. @ref mpack_done_map() must be called
5934 * once all elements have been read.
5935 *
5936 * @note Maps in JSON are unordered, so it is recommended not to expect
5937 * a specific ordering for your map values in case your data is converted
5938 * to/from JSON.
5939 *
5940 * min_count is returned if an error occurs.
5941 *
5942 * @throws mpack_error_type if the value is not a map or if its size does
5943 * not fall within the given range.
5944 */
5945uint32_t mpack_expect_map_range(mpack_reader_t* reader, uint32_t min_count, uint32_t max_count);
5946
5947/**
5948 * Reads the start of a map with a number of elements at most @a max_count,
5949 * returning its element count.
5950 *
5951 * A number of values follow equal to twice the element count of the map,
5952 * alternating between keys and values. @ref mpack_done_map() must be called
5953 * once all elements have been read.
5954 *
5955 * @note Maps in JSON are unordered, so it is recommended not to expect
5956 * a specific ordering for your map values in case your data is converted
5957 * to/from JSON.
5958 *
5959 * Zero is returned if an error occurs.
5960 *
5961 * @throws mpack_error_type if the value is not a map or if its size is
5962 * greater than max_count.
5963 */
5964MPACK_INLINE uint32_t mpack_expect_map_max(mpack_reader_t* reader, uint32_t max_count) {
5965 return mpack_expect_map_range(reader, 0, max_count);
5966}
5967
5968/**
5969 * Reads the start of a map of the exact size given.
5970 *
5971 * A number of values follow equal to twice the element count of the map,
5972 * alternating between keys and values. @ref mpack_done_map() must be called
5973 * once all elements have been read.
5974 *
5975 * @note Maps in JSON are unordered, so it is recommended not to expect
5976 * a specific ordering for your map values in case your data is converted
5977 * to/from JSON.
5978 *
5979 * @throws mpack_error_type if the value is not a map or if its size
5980 * does not match the given count.
5981 */
5983
5984/**
5985 * Reads a nil node or the start of a map, returning whether a map was
5986 * read and placing its number of key/value pairs in count.
5987 *
5988 * If a map was read, a number of values follow equal to twice the element count
5989 * of the map, alternating between keys and values. @ref mpack_done_map() should
5990 * also be called once all elements have been read (only if a map was read.)
5991 *
5992 * @note Maps in JSON are unordered, so it is recommended not to expect
5993 * a specific ordering for your map values in case your data is converted
5994 * to/from JSON.
5995 *
5996 * @warning This call is dangerous! It does not have a size limit, and it
5997 * does not have any way of checking whether there is enough data in the
5998 * message (since the data could be coming from a stream.) When looping
5999 * through the map's contents, you must check for errors on each iteration
6000 * of the loop. Otherwise an attacker could craft a message declaring a map
6001 * of a billion elements which would throw your parsing code into an
6002 * infinite loop! You should strongly consider using mpack_expect_map_max_or_nil()
6003 * with a safe maximum size instead.
6004 *
6005 * @returns @c true if a map was read successfully; @c false if nil was read
6006 * or an error occurred.
6007 * @throws mpack_error_type if the value is not a nil or map.
6008 */
6010
6011/**
6012 * Reads a nil node or the start of a map with a number of elements at most
6013 * max_count, returning whether a map was read and placing its number of
6014 * key/value pairs in count.
6015 *
6016 * If a map was read, a number of values follow equal to twice the element count
6017 * of the map, alternating between keys and values. @ref mpack_done_map() should
6018 * anlso be called once all elements have been read (only if a map was read.)
6019 *
6020 * @note Maps in JSON are unordered, so it is recommended not to expect
6021 * a specific ordering for your map values in case your data is converted
6022 * to/from JSON. Consider using mpack_expect_key_cstr() or mpack_expect_key_uint()
6023 * to switch on the key; see @ref docs/expect.md for examples.
6024 *
6025 * @returns @c true if a map was read successfully; @c false if nil was read
6026 * or an error occurred.
6027 * @throws mpack_error_type if the value is not a nil or map.
6028 */
6029bool mpack_expect_map_max_or_nil(mpack_reader_t* reader, uint32_t max_count, uint32_t* count);
6030
6031/**
6032 * Reads the start of an array, returning its element count.
6033 *
6034 * A number of values follow equal to the element count of the array.
6035 * @ref mpack_done_array() must be called once all elements have been read.
6036 *
6037 * @warning This call is dangerous! It does not have a size limit, and it
6038 * does not have any way of checking whether there is enough data in the
6039 * message (since the data could be coming from a stream.) When looping
6040 * through the array's contents, you must check for errors on each iteration
6041 * of the loop. Otherwise an attacker could craft a message declaring an array
6042 * of a billion elements which would throw your parsing code into an
6043 * infinite loop! You should strongly consider using mpack_expect_array_max()
6044 * with a safe maximum size instead.
6045 */
6047
6048/**
6049 * Reads the start of an array with a number of elements in the given range,
6050 * returning its element count.
6051 *
6052 * A number of values follow equal to the element count of the array.
6053 * @ref mpack_done_array() must be called once all elements have been read.
6054 *
6055 * min_count is returned if an error occurs.
6056 *
6057 * @throws mpack_error_type if the value is not an array or if its size does
6058 * not fall within the given range.
6059 */
6060uint32_t mpack_expect_array_range(mpack_reader_t* reader, uint32_t min_count, uint32_t max_count);
6061
6062/**
6063 * Reads the start of an array with a number of elements at most @a max_count,
6064 * returning its element count.
6065 *
6066 * A number of values follow equal to the element count of the array.
6067 * @ref mpack_done_array() must be called once all elements have been read.
6068 *
6069 * Zero is returned if an error occurs.
6070 *
6071 * @throws mpack_error_type if the value is not an array or if its size is
6072 * greater than max_count.
6073 */
6074MPACK_INLINE uint32_t mpack_expect_array_max(mpack_reader_t* reader, uint32_t max_count) {
6075 return mpack_expect_array_range(reader, 0, max_count);
6076}
6077
6078/**
6079 * Reads the start of an array of the exact size given.
6080 *
6081 * A number of values follow equal to the element count of the array.
6082 * @ref mpack_done_array() must be called once all elements have been read.
6083 *
6084 * @throws mpack_error_type if the value is not an array or if its size does
6085 * not match the given count.
6086 */
6088
6089/**
6090 * Reads a nil node or the start of an array, returning whether an array was
6091 * read and placing its number of elements in count.
6092 *
6093 * If an array was read, a number of values follow equal to the element count
6094 * of the array. @ref mpack_done_array() should also be called once all elements
6095 * have been read (only if an array was read.)
6096 *
6097 * @warning This call is dangerous! It does not have a size limit, and it
6098 * does not have any way of checking whether there is enough data in the
6099 * message (since the data could be coming from a stream.) When looping
6100 * through the array's contents, you must check for errors on each iteration
6101 * of the loop. Otherwise an attacker could craft a message declaring an array
6102 * of a billion elements which would throw your parsing code into an
6103 * infinite loop! You should strongly consider using mpack_expect_array_max_or_nil()
6104 * with a safe maximum size instead.
6105 *
6106 * @returns @c true if an array was read successfully; @c false if nil was read
6107 * or an error occurred.
6108 * @throws mpack_error_type if the value is not a nil or array.
6109 */
6111
6112/**
6113 * Reads a nil node or the start of an array with a number of elements at most
6114 * max_count, returning whether an array was read and placing its number of
6115 * key/value pairs in count.
6116 *
6117 * If an array was read, a number of values follow equal to the element count
6118 * of the array. @ref mpack_done_array() should also be called once all elements
6119 * have been read (only if an array was read.)
6120 *
6121 * @returns @c true if an array was read successfully; @c false if nil was read
6122 * or an error occurred.
6123 * @throws mpack_error_type if the value is not a nil or array.
6124 */
6125bool mpack_expect_array_max_or_nil(mpack_reader_t* reader, uint32_t max_count, uint32_t* count);
6126
6127#ifdef MPACK_MALLOC
6128/**
6129 * @hideinitializer
6130 *
6131 * Reads the start of an array and allocates storage for it, placing its
6132 * size in out_count. A number of objects follow equal to the element count
6133 * of the array. You must call @ref mpack_done_array() when done (even
6134 * if the element count is zero.)
6135 *
6136 * If an error occurs, NULL is returned and the reader is placed in an
6137 * error state.
6138 *
6139 * If the count is zero, NULL is returned. This does not indicate error.
6140 * You should not check the return value for NULL to check for errors; only
6141 * check the reader's error state.
6142 *
6143 * The allocated array must be freed with MPACK_FREE() (or simply free()
6144 * if MPack's allocator hasn't been customized.)
6145 *
6146 * @throws mpack_error_type if the value is not an array or if its size is
6147 * greater than max_count.
6148 */
6149#define mpack_expect_array_alloc(reader, Type, max_count, out_count) \
6150 ((Type*)mpack_expect_array_alloc_impl(reader, sizeof(Type), max_count, out_count, false))
6151
6152/**
6153 * @hideinitializer
6154 *
6155 * Reads a nil node or the start of an array and allocates storage for it,
6156 * placing its size in out_count. A number of objects follow equal to the element
6157 * count of the array if a non-empty array was read.
6158 *
6159 * If an error occurs, NULL is returned and the reader is placed in an
6160 * error state.
6161 *
6162 * If a nil node was read, NULL is returned. If an empty array was read,
6163 * mpack_done_array() is called automatically and NULL is returned. These
6164 * do not indicate error. You should not check the return value for NULL
6165 * to check for errors; only check the reader's error state.
6166 *
6167 * The allocated array must be freed with MPACK_FREE() (or simply free()
6168 * if MPack's allocator hasn't been customized.)
6169 *
6170 * @warning You must call @ref mpack_done_array() if and only if a non-zero
6171 * element count is read. This function does not differentiate between nil
6172 * and an empty array.
6173 *
6174 * @throws mpack_error_type if the value is not an array or if its size is
6175 * greater than max_count.
6176 */
6177#define mpack_expect_array_or_nil_alloc(reader, Type, max_count, out_count) \
6178 ((Type*)mpack_expect_array_alloc_impl(reader, sizeof(Type), max_count, out_count, true))
6179#endif
6180
6181/**
6182 * @}
6183 */
6184
6185/** @cond */
6186#ifdef MPACK_MALLOC
6187void* mpack_expect_array_alloc_impl(mpack_reader_t* reader,
6188 size_t element_size, uint32_t max_count, uint32_t* out_count, bool allow_nil);
6189#endif
6190/** @endcond */
6191
6192
6193/**
6194 * @name String Functions
6195 * @{
6196 */
6197
6198/**
6199 * Reads the start of a string, returning its size in bytes.
6200 *
6201 * The bytes follow and must be read separately with mpack_read_bytes()
6202 * or mpack_read_bytes_inplace(). mpack_done_str() must be called
6203 * once all bytes have been read.
6204 *
6205 * NUL bytes are allowed in the string, and no encoding checks are done.
6206 *
6207 * mpack_error_type is raised if the value is not a string.
6208 */
6210
6211/**
6212 * Reads a string of at most the given size, writing it into the
6213 * given buffer and returning its size in bytes.
6214 *
6215 * This does not add a null-terminator! Use mpack_expect_cstr() to
6216 * add a null-terminator.
6217 *
6218 * NUL bytes are allowed in the string, and no encoding checks are done.
6219 */
6220size_t mpack_expect_str_buf(mpack_reader_t* reader, char* buf, size_t bufsize);
6221
6222/**
6223 * Reads a string into the given buffer, ensuring it is a valid UTF-8 string
6224 * and returning its size in bytes.
6225 *
6226 * This does not add a null-terminator! Use mpack_expect_utf8_cstr() to
6227 * add a null-terminator.
6228 *
6229 * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
6230 * WTF-8. Only pure UTF-8 is allowed.
6231 *
6232 * NUL bytes are allowed in the string (as they are in UTF-8.)
6233 *
6234 * Raises mpack_error_too_big if there is not enough room for the string.
6235 * Raises mpack_error_type if the value is not a string or is not a valid UTF-8 string.
6236 */
6237size_t mpack_expect_utf8(mpack_reader_t* reader, char* buf, size_t bufsize);
6238
6239/**
6240 * Reads the start of a string, raising an error if its length is not
6241 * at most the given number of bytes (not including any null-terminator.)
6242 *
6243 * The bytes follow and must be read separately with mpack_read_bytes()
6244 * or mpack_read_bytes_inplace(). @ref mpack_done_str() must be called
6245 * once all bytes have been read.
6246 *
6247 * @throws mpack_error_type If the value is not a string.
6248 * @throws mpack_error_too_big If the string's length in bytes is larger than the given maximum size.
6249 */
6250MPACK_INLINE uint32_t mpack_expect_str_max(mpack_reader_t* reader, uint32_t maxsize) {
6251 uint32_t length = mpack_expect_str(reader);
6252 if (length > maxsize) {
6254 return 0;
6255 }
6256 return length;
6257}
6258
6259/**
6260 * Reads the start of a string, raising an error if its length is not
6261 * exactly the given number of bytes (not including any null-terminator.)
6262 *
6263 * The bytes follow and must be read separately with mpack_read_bytes()
6264 * or mpack_read_bytes_inplace(). @ref mpack_done_str() must be called
6265 * once all bytes have been read.
6266 *
6267 * mpack_error_type is raised if the value is not a string or if its
6268 * length does not match.
6269 */
6270MPACK_INLINE void mpack_expect_str_length(mpack_reader_t* reader, uint32_t count) {
6271 if (mpack_expect_str(reader) != count)
6273}
6274
6275/**
6276 * Reads a string, ensuring it exactly matches the given string.
6277 *
6278 * Remember that maps are unordered in JSON. Don't use this for map keys
6279 * unless the map has only a single key!
6280 */
6281void mpack_expect_str_match(mpack_reader_t* reader, const char* str, size_t length);
6282
6283/**
6284 * Reads a string into the given buffer, ensures it has no null bytes,
6285 * and adds a null-terminator at the end.
6286 *
6287 * Raises mpack_error_too_big if there is not enough room for the string and null-terminator.
6288 * Raises mpack_error_type if the value is not a string or contains a null byte.
6289 */
6290void mpack_expect_cstr(mpack_reader_t* reader, char* buf, size_t size);
6291
6292/**
6293 * Reads a string into the given buffer, ensures it is a valid UTF-8 string
6294 * without NUL characters, and adds a null-terminator at the end.
6295 *
6296 * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
6297 * WTF-8. Only pure UTF-8 is allowed, but without the NUL character, since
6298 * it cannot be represented in a null-terminated string.
6299 *
6300 * Raises mpack_error_too_big if there is not enough room for the string and null-terminator.
6301 * Raises mpack_error_type if the value is not a string or is not a valid UTF-8 string.
6302 */
6303void mpack_expect_utf8_cstr(mpack_reader_t* reader, char* buf, size_t size);
6304
6305#ifdef MPACK_MALLOC
6306/**
6307 * Reads a string with the given total maximum size (including space for a
6308 * null-terminator), allocates storage for it, ensures it has no null-bytes,
6309 * and adds a null-terminator at the end. You assume ownership of the
6310 * returned pointer if reading succeeds.
6311 *
6312 * The allocated string must be freed with MPACK_FREE() (or simply free()
6313 * if MPack's allocator hasn't been customized.)
6314 *
6315 * @throws mpack_error_too_big If the string plus null-terminator is larger than the given maxsize.
6316 * @throws mpack_error_type If the value is not a string or contains a null byte.
6317 */
6318char* mpack_expect_cstr_alloc(mpack_reader_t* reader, size_t maxsize);
6319
6320/**
6321 * Reads a string with the given total maximum size (including space for a
6322 * null-terminator), allocates storage for it, ensures it is valid UTF-8
6323 * with no null-bytes, and adds a null-terminator at the end. You assume
6324 * ownership of the returned pointer if reading succeeds.
6325 *
6326 * The length in bytes of the string, not including the null-terminator,
6327 * will be written to size.
6328 *
6329 * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
6330 * WTF-8. Only pure UTF-8 is allowed, but without the NUL character, since
6331 * it cannot be represented in a null-terminated string.
6332 *
6333 * The allocated string must be freed with MPACK_FREE() (or simply free()
6334 * if MPack's allocator hasn't been customized.)
6335 * if you want a null-terminator.
6336 *
6337 * @throws mpack_error_too_big If the string plus null-terminator is larger
6338 * than the given maxsize.
6339 * @throws mpack_error_type If the value is not a string or contains
6340 * invalid UTF-8 or a null byte.
6341 */
6342char* mpack_expect_utf8_cstr_alloc(mpack_reader_t* reader, size_t maxsize);
6343#endif
6344
6345/**
6346 * Reads a string, ensuring it exactly matches the given null-terminated
6347 * string.
6348 *
6349 * Remember that maps are unordered in JSON. Don't use this for map keys
6350 * unless the map has only a single key!
6351 */
6352MPACK_INLINE void mpack_expect_cstr_match(mpack_reader_t* reader, const char* cstr) {
6353 mpack_assert(cstr != NULL, "cstr pointer is NULL");
6354 mpack_expect_str_match(reader, cstr, mpack_strlen(cstr));
6355}
6356
6357/**
6358 * @}
6359 */
6360
6361/**
6362 * @name Binary Data
6363 * @{
6364 */
6365
6366/**
6367 * Reads the start of a binary blob, returning its size in bytes.
6368 *
6369 * The bytes follow and must be read separately with mpack_read_bytes()
6370 * or mpack_read_bytes_inplace(). @ref mpack_done_bin() must be called
6371 * once all bytes have been read.
6372 *
6373 * mpack_error_type is raised if the value is not a binary blob.
6374 */
6376
6377/**
6378 * Reads the start of a binary blob, raising an error if its length is not
6379 * at most the given number of bytes.
6380 *
6381 * The bytes follow and must be read separately with mpack_read_bytes()
6382 * or mpack_read_bytes_inplace(). @ref mpack_done_bin() must be called
6383 * once all bytes have been read.
6384 *
6385 * mpack_error_type is raised if the value is not a binary blob or if its
6386 * length does not match.
6387 */
6388MPACK_INLINE uint32_t mpack_expect_bin_max(mpack_reader_t* reader, uint32_t maxsize) {
6389 uint32_t length = mpack_expect_bin(reader);
6390 if (length > maxsize) {
6392 return 0;
6393 }
6394 return length;
6395}
6396
6397/**
6398 * Reads the start of a binary blob, raising an error if its length is not
6399 * exactly the given number of bytes.
6400 *
6401 * The bytes follow and must be read separately with mpack_read_bytes()
6402 * or mpack_read_bytes_inplace(). @ref mpack_done_bin() must be called
6403 * once all bytes have been read.
6404 *
6405 * @throws mpack_error_type if the value is not a binary blob or if its size
6406 * does not match.
6407 */
6408MPACK_INLINE void mpack_expect_bin_size(mpack_reader_t* reader, uint32_t count) {
6409 if (mpack_expect_bin(reader) != count)
6411}
6412
6413/**
6414 * Reads a binary blob into the given buffer, returning its size in bytes.
6415 *
6416 * For compatibility, this will accept if the underlying type is string or
6417 * binary (since in MessagePack 1.0, strings and binary data were combined
6418 * under the "raw" type which became string in 1.1.)
6419 */
6420size_t mpack_expect_bin_buf(mpack_reader_t* reader, char* buf, size_t size);
6421
6422/**
6423 * Reads a binary blob with the exact given size into the given buffer.
6424 *
6425 * For compatibility, this will accept if the underlying type is string or
6426 * binary (since in MessagePack 1.0, strings and binary data were combined
6427 * under the "raw" type which became string in 1.1.)
6428 *
6429 * @throws mpack_error_type if the value is not a binary blob or if its size
6430 * does not match.
6431 */
6432void mpack_expect_bin_size_buf(mpack_reader_t* reader, char* buf, uint32_t size);
6433
6434/**
6435 * Reads a binary blob with the given total maximum size, allocating storage for it.
6436 */
6437char* mpack_expect_bin_alloc(mpack_reader_t* reader, size_t maxsize, size_t* size);
6438
6439/**
6440 * @}
6441 */
6442
6443/**
6444 * @name Extension Functions
6445 * @{
6446 */
6447
6448#if MPACK_EXTENSIONS
6449/**
6450 * Reads the start of an extension blob, returning its size in bytes and
6451 * placing the type into @p type.
6452 *
6453 * The bytes follow and must be read separately with mpack_read_bytes()
6454 * or mpack_read_bytes_inplace(). @ref mpack_done_ext() must be called
6455 * once all bytes have been read.
6456 *
6457 * @p type will be a user-defined type in the range [0,127] or a reserved type
6458 * in the range [-128,-2].
6459 *
6460 * mpack_error_type is raised if the value is not an extension blob. The @p
6461 * type value is zero if an error occurs.
6462 *
6463 * @note This cannot be used to match a timestamp. @ref mpack_error_type will
6464 * be flagged if the value is a timestamp. Use mpack_expect_timestamp() or
6465 * mpack_expect_timestamp_truncate() instead.
6466 *
6467 * @note This requires @ref MPACK_EXTENSIONS.
6468 *
6469 * @warning Be careful when using reserved types. They may no longer be ext
6470 * types in the future, and previously valid data containing reserved types may
6471 * become invalid in the future.
6472 */
6473uint32_t mpack_expect_ext(mpack_reader_t* reader, int8_t* type);
6474
6475/**
6476 * Reads the start of an extension blob, raising an error if its length is not
6477 * at most the given number of bytes and placing the type into @p type.
6478 *
6479 * The bytes follow and must be read separately with mpack_read_bytes()
6480 * or mpack_read_bytes_inplace(). @ref mpack_done_ext() must be called
6481 * once all bytes have been read.
6482 *
6483 * mpack_error_type is raised if the value is not an extension blob or if its
6484 * length does not match. The @p type value is zero if an error is raised.
6485 *
6486 * @p type will be a user-defined type in the range [0,127] or a reserved type
6487 * in the range [-128,-2].
6488 *
6489 * @note This cannot be used to match a timestamp. @ref mpack_error_type will
6490 * be flagged if the value is a timestamp. Use mpack_expect_timestamp() or
6491 * mpack_expect_timestamp_truncate() instead.
6492 *
6493 * @note This requires @ref MPACK_EXTENSIONS.
6494 *
6495 * @warning Be careful when using reserved types. They may no longer be ext
6496 * types in the future, and previously valid data containing reserved types may
6497 * become invalid in the future.
6498 *
6499 * @see mpack_expect_ext()
6500 */
6501MPACK_INLINE uint32_t mpack_expect_ext_max(mpack_reader_t* reader, int8_t* type, uint32_t maxsize) {
6502 uint32_t length = mpack_expect_ext(reader, type);
6503 if (length > maxsize) {
6505 return 0;
6506 }
6507 return length;
6508}
6509
6510/**
6511 * Reads the start of an extension blob, raising an error if its length is not
6512 * exactly the given number of bytes and placing the type into @p type.
6513 *
6514 * The bytes follow and must be read separately with mpack_read_bytes()
6515 * or mpack_read_bytes_inplace(). @ref mpack_done_ext() must be called
6516 * once all bytes have been read.
6517 *
6518 * mpack_error_type is raised if the value is not an extension blob or if its
6519 * length does not match. The @p type value is zero if an error is raised.
6520 *
6521 * @p type will be a user-defined type in the range [0,127] or a reserved type
6522 * in the range [-128,-2].
6523 *
6524 * @note This cannot be used to match a timestamp. @ref mpack_error_type will
6525 * be flagged if the value is a timestamp. Use mpack_expect_timestamp() or
6526 * mpack_expect_timestamp_truncate() instead.
6527 *
6528 * @note This requires @ref MPACK_EXTENSIONS.
6529 *
6530 * @warning Be careful when using reserved types. They may no longer be ext
6531 * types in the future, and previously valid data containing reserved types may
6532 * become invalid in the future.
6533 *
6534 * @see mpack_expect_ext()
6535 */
6536MPACK_INLINE void mpack_expect_ext_size(mpack_reader_t* reader, int8_t* type, uint32_t count) {
6537 if (mpack_expect_ext(reader, type) != count) {
6538 *type = 0;
6540 }
6541}
6542
6543/**
6544 * Reads an extension blob into the given buffer, returning its size in bytes
6545 * and placing the type into @p type.
6546 *
6547 * mpack_error_type is raised if the value is not an extension blob or if its
6548 * length does not match. The @p type value is zero if an error is raised.
6549 *
6550 * @p type will be a user-defined type in the range [0,127] or a reserved type
6551 * in the range [-128,-2].
6552 *
6553 * @note This cannot be used to match a timestamp. @ref mpack_error_type will
6554 * be flagged if the value is a timestamp. Use mpack_expect_timestamp() or
6555 * mpack_expect_timestamp_truncate() instead.
6556 *
6557 * @warning Be careful when using reserved types. They may no longer be ext
6558 * types in the future, and previously valid data containing reserved types may
6559 * become invalid in the future.
6560 *
6561 * @note This requires @ref MPACK_EXTENSIONS.
6562 *
6563 * @see mpack_expect_ext()
6564 */
6565size_t mpack_expect_ext_buf(mpack_reader_t* reader, int8_t* type, char* buf, size_t size);
6566#endif
6567
6568#if MPACK_EXTENSIONS && defined(MPACK_MALLOC)
6569/**
6570 * Reads an extension blob with the given total maximum size, allocating
6571 * storage for it, and placing the type into @p type.
6572 *
6573 * mpack_error_type is raised if the value is not an extension blob or if its
6574 * length does not match. The @p type value is zero if an error is raised.
6575 *
6576 * @p type will be a user-defined type in the range [0,127] or a reserved type
6577 * in the range [-128,-2].
6578 *
6579 * @note This cannot be used to match a timestamp. @ref mpack_error_type will
6580 * be flagged if the value is a timestamp. Use mpack_expect_timestamp() or
6581 * mpack_expect_timestamp_truncate() instead.
6582 *
6583 * @warning Be careful when using reserved types. They may no longer be ext
6584 * types in the future, and previously valid data containing reserved types may
6585 * become invalid in the future.
6586 *
6587 * @note This requires @ref MPACK_EXTENSIONS and @ref MPACK_MALLOC.
6588 *
6589 * @see mpack_expect_ext()
6590 */
6591char* mpack_expect_ext_alloc(mpack_reader_t* reader, int8_t* type, size_t maxsize, size_t* size);
6592#endif
6593
6594/**
6595 * @}
6596 */
6597
6598/**
6599 * @name Special Functions
6600 * @{
6601 */
6602
6603/**
6604 * Reads a MessagePack object header (an MPack tag), expecting it to exactly
6605 * match the given tag.
6606 *
6607 * If the type is compound (i.e. is a map, array, string, binary or
6608 * extension type), additional reads are required to get the contained
6609 * data, and the corresponding done function must be called when done.
6610 *
6611 * @throws mpack_error_type if the tag does not match
6612 *
6613 * @see mpack_read_bytes()
6614 * @see mpack_done_array()
6615 * @see mpack_done_map()
6616 * @see mpack_done_str()
6617 * @see mpack_done_bin()
6618 * @see mpack_done_ext()
6619 */
6621
6622/**
6623 * Expects a string matching one of the strings in the given array,
6624 * returning its array index.
6625 *
6626 * If the value does not match any of the given strings,
6627 * @ref mpack_error_type is flagged. Use mpack_expect_enum_optional()
6628 * if you want to allow other values than the given strings.
6629 *
6630 * If any error occurs or the reader is in an error state, @a count
6631 * is returned.
6632 *
6633 * This can be used to quickly parse a string into an enum when the
6634 * enum values range from 0 to @a count-1. If the last value in the
6635 * enum is a special "count" value, it can be passed as the count,
6636 * and the return value can be cast directly to the enum type.
6637 *
6638 * @code{.c}
6639 * typedef enum { APPLE , BANANA , ORANGE , COUNT} fruit_t;
6640 * const char* fruits[] = {"apple", "banana", "orange"};
6641 *
6642 * fruit_t fruit = (fruit_t)mpack_expect_enum(reader, fruits, COUNT);
6643 * @endcode
6644 *
6645 * See @ref docs/expect.md for more examples.
6646 *
6647 * The maximum string length is the size of the buffer (strings are read in-place.)
6648 *
6649 * @param reader The reader
6650 * @param strings An array of expected strings of length count
6651 * @param count The number of strings
6652 * @return The index of the matched string, or @a count in case of error
6653 */
6654size_t mpack_expect_enum(mpack_reader_t* reader, const char* strings[], size_t count);
6655
6656/**
6657 * Expects a string matching one of the strings in the given array
6658 * returning its array index, or @a count if no strings match.
6659 *
6660 * If the value is not a string, or it does not match any of the
6661 * given strings, @a count is returned and no error is flagged.
6662 *
6663 * If any error occurs or the reader is in an error state, @a count
6664 * is returned.
6665 *
6666 * This can be used to quickly parse a string into an enum when the
6667 * enum values range from 0 to @a count-1. If the last value in the
6668 * enum is a special "count" value, it can be passed as the count,
6669 * and the return value can be cast directly to the enum type.
6670 *
6671 * @code{.c}
6672 * typedef enum { APPLE , BANANA , ORANGE , COUNT} fruit_t;
6673 * const char* fruits[] = {"apple", "banana", "orange"};
6674 *
6675 * fruit_t fruit = (fruit_t)mpack_expect_enum_optional(reader, fruits, COUNT);
6676 * @endcode
6677 *
6678 * See @ref docs/expect.md for more examples.
6679 *
6680 * The maximum string length is the size of the buffer (strings are read in-place.)
6681 *
6682 * @param reader The reader
6683 * @param strings An array of expected strings of length count
6684 * @param count The number of strings
6685 *
6686 * @return The index of the matched string, or @a count if it does not
6687 * match or an error occurs
6688 */
6689size_t mpack_expect_enum_optional(mpack_reader_t* reader, const char* strings[], size_t count);
6690
6691/**
6692 * Expects an unsigned integer map key between 0 and count-1, marking it
6693 * as found in the given bool array and returning it.
6694 *
6695 * This is a helper for switching among int keys in a map. It is
6696 * typically used with an enum to define the key values. It should
6697 * be called in the expression of a switch() statement. See @ref
6698 * docs/expect.md for an example.
6699 *
6700 * The found array must be cleared before expecting the first key. If the
6701 * flag for a given key is already set when found (i.e. the map contains a
6702 * duplicate key), mpack_error_invalid is flagged.
6703 *
6704 * If the key is not a non-negative integer, or if the key is @a count or
6705 * larger, @a count is returned and no error is flagged. If you want an error
6706 * on unrecognized keys, flag an error in the default case in your switch;
6707 * otherwise you must call mpack_discard() to discard its content.
6708 *
6709 * @param reader The reader
6710 * @param found An array of bool flags of length count
6711 * @param count The number of values in the found array, and one more than the
6712 * maximum allowed key
6713 *
6714 * @see @ref docs/expect.md
6715 */
6716size_t mpack_expect_key_uint(mpack_reader_t* reader, bool found[], size_t count);
6717
6718/**
6719 * Expects a string map key matching one of the strings in the given key list,
6720 * marking it as found in the given bool array and returning its index.
6721 *
6722 * This is a helper for switching among string keys in a map. It is
6723 * typically used with an enum with names matching the strings in the
6724 * array to define the key indices. It should be called in the expression
6725 * of a switch() statement. See @ref docs/expect.md for an example.
6726 *
6727 * The found array must be cleared before expecting the first key. If the
6728 * flag for a given key is already set when found (i.e. the map contains a
6729 * duplicate key), mpack_error_invalid is flagged.
6730 *
6731 * If the key is unrecognized, count is returned and no error is flagged. If
6732 * you want an error on unrecognized keys, flag an error in the default case
6733 * in your switch; otherwise you must call mpack_discard() to discard its content.
6734 *
6735 * The maximum key length is the size of the buffer (keys are read in-place.)
6736 *
6737 * @param reader The reader
6738 * @param keys An array of expected string keys of length count
6739 * @param found An array of bool flags of length count
6740 * @param count The number of values in the keys and found arrays
6741 *
6742 * @see @ref docs/expect.md
6743 */
6744size_t mpack_expect_key_cstr(mpack_reader_t* reader, const char* keys[],
6745 bool found[], size_t count);
6746
6747/**
6748 * @}
6749 */
6750
6751/**
6752 * @}
6753 */
6754
6755#endif
6756
6757MPACK_EXTERN_C_END
6758MPACK_SILENCE_WARNINGS_END
6759
6760#endif
6761
6762
6763
6764/* mpack/mpack-node.h.h */
6765
6766/**
6767 * @file
6768 *
6769 * Declares the MPack dynamic Node API.
6770 */
6771
6772#ifndef MPACK_NODE_H
6773#define MPACK_NODE_H 1
6774
6775/* #include "mpack-reader.h" */
6776
6777MPACK_SILENCE_WARNINGS_BEGIN
6778MPACK_EXTERN_C_BEGIN
6779
6780#if MPACK_NODE
6781
6782/**
6783 * @defgroup mpack_node Node API
6784 * @ingroup mpack
6785 *
6786 * The MPack Node API allows you to parse a chunk of MessagePack into a
6787 * dynamically typed data structure, providing random access to the parsed
6788 * data.
6789 *
6790 * See @ref docs/node.md for examples.
6791 *
6792 * @{
6793 */
6794
6795/**
6796 * A handle to node data in a parsed MPack tree.
6797 *
6798 * Nodes represent either primitive values or compound types. If a
6799 * node is a compound type, it contains a pointer to its child nodes,
6800 * or a pointer to its underlying data.
6801 *
6802 * Nodes are immutable.
6803 *
6804 * @note @ref mpack_node_t is an opaque reference to the node data, not the
6805 * node data itself. (It contains pointers to both the node data and the tree.)
6806 * It is passed by value in the Node API.
6807 */
6809
6810/**
6811 * The storage for nodes in an MPack tree.
6812 *
6813 * You only need to use this if you intend to provide your own storage
6814 * for nodes instead of letting the tree allocate it.
6815 *
6816 * @ref mpack_node_data_t is 16 bytes on most common architectures (32-bit
6817 * and 64-bit.)
6818 */
6820
6821/**
6822 * An MPack tree parser to parse a blob or stream of MessagePack.
6823 *
6824 * When a message is parsed, the tree contains a single root node which
6825 * contains all parsed data. The tree and its nodes are immutable.
6826 */
6828
6829/**
6830 * An error handler function to be called when an error is flagged on
6831 * the tree.
6832 *
6833 * The error handler will only be called once on the first error flagged;
6834 * any subsequent node reads and errors are ignored, and the tree is
6835 * permanently in that error state.
6836 *
6837 * MPack is safe against non-local jumps out of error handler callbacks.
6838 * This means you are allowed to longjmp or throw an exception (in C++,
6839 * Objective-C, or with SEH) out of this callback.
6840 *
6841 * Bear in mind when using longjmp that local non-volatile variables that
6842 * have changed are undefined when setjmp() returns, so you can't put the
6843 * tree on the stack in the same activation frame as the setjmp without
6844 * declaring it volatile.
6845 *
6846 * You must still eventually destroy the tree. It is not destroyed
6847 * automatically when an error is flagged. It is safe to destroy the
6848 * tree within this error callback, but you will either need to perform
6849 * a non-local jump, or store something in your context to identify
6850 * that the tree is destroyed since any future accesses to it cause
6851 * undefined behavior.
6852 */
6853typedef void (*mpack_tree_error_t)(mpack_tree_t* tree, mpack_error_t error);
6854
6855/**
6856 * The MPack tree's read function. It should fill the buffer with as many bytes
6857 * as are immediately available up to the given @c count, returning the number
6858 * of bytes written to the buffer.
6859 *
6860 * In case of error, it should flag an appropriate error on the reader
6861 * (usually @ref mpack_error_io.)
6862 *
6863 * The blocking or non-blocking behaviour of the read should match whether you
6864 * are using mpack_tree_parse() or mpack_tree_try_parse().
6865 *
6866 * If you are using mpack_tree_parse(), the read should block until at least
6867 * one byte is read. If you return 0, mpack_tree_parse() will raise @ref
6868 * mpack_error_io.
6869 *
6870 * If you are using mpack_tree_try_parse(), the read function can always
6871 * return 0, and must never block waiting for data (otherwise
6872 * mpack_tree_try_parse() would be equivalent to mpack_tree_parse().)
6873 * When you return 0, mpack_tree_try_parse() will return false without flagging
6874 * an error.
6875 */
6876typedef size_t (*mpack_tree_read_t)(mpack_tree_t* tree, char* buffer, size_t count);
6877
6878/**
6879 * A teardown function to be called when the tree is destroyed.
6880 */
6882
6883
6884
6885/* Hide internals from documentation */
6886/** @cond */
6887
6888struct mpack_node_t {
6889 mpack_node_data_t* data;
6890 mpack_tree_t* tree;
6891};
6892
6893struct mpack_node_data_t {
6895
6896 /*
6897 * The element count if the type is an array;
6898 * the number of key/value pairs if the type is map;
6899 * or the number of bytes if the type is str, bin or ext.
6900 */
6901 uint32_t len;
6902
6903 union {
6904 bool b; /* The value if the type is bool. */
6905
6906 #if MPACK_FLOAT
6907 float f; /* The value if the type is float. */
6908 #else
6909 uint32_t f; /*< The raw value if the type is float. */
6910 #endif
6911
6912 #if MPACK_DOUBLE
6913 double d; /* The value if the type is double. */
6914 #else
6915 uint64_t d; /*< The raw value if the type is double. */
6916 #endif
6917
6918 int64_t i; /* The value if the type is signed int. */
6919 uint64_t u; /* The value if the type is unsigned int. */
6920 size_t offset; /* The byte offset for str, bin and ext */
6921
6922 mpack_node_data_t* children; /* The children for map or array */
6923 } value;
6924};
6925
6926typedef struct mpack_tree_page_t {
6927 struct mpack_tree_page_t* next;
6928 mpack_node_data_t nodes[1]; // variable size
6929} mpack_tree_page_t;
6930
6931typedef enum mpack_tree_parse_state_t {
6932 mpack_tree_parse_state_not_started,
6933 mpack_tree_parse_state_in_progress,
6934 mpack_tree_parse_state_parsed,
6935} mpack_tree_parse_state_t;
6936
6937typedef struct mpack_level_t {
6938 mpack_node_data_t* child;
6939 size_t left; // children left in level
6940} mpack_level_t;
6941
6942typedef struct mpack_tree_parser_t {
6943 mpack_tree_parse_state_t state;
6944
6945 // We keep track of the number of "possible nodes" left in the data rather
6946 // than the number of bytes.
6947 //
6948 // When a map or array is parsed, we ensure at least one byte for each child
6949 // exists and subtract them right away. This ensures that if ever a map or
6950 // array declares more elements than could possibly be contained in the data,
6951 // we will error out immediately rather than allocating storage for them.
6952 //
6953 // For example malicious data that repeats 0xDE 0xFF 0xFF (start of a map
6954 // with 65536 key-value pairs) would otherwise cause us to run out of
6955 // memory. With this, the parser can allocate at most as many nodes as
6956 // there are bytes in the data (plus the paging overhead, 12%.) An error
6957 // will be flagged immediately if and when there isn't enough data left to
6958 // fully read all children of all open compound types on the parsing stack.
6959 //
6960 // Once an entire message has been parsed (and there are no nodes left to
6961 // parse whose bytes have been subtracted), this matches the number of left
6962 // over bytes in the data.
6963 size_t possible_nodes_left;
6964
6965 mpack_node_data_t* nodes; // next node in current page/pool
6966 size_t nodes_left; // nodes left in current page/pool
6967
6968 size_t current_node_reserved;
6969 size_t level;
6970
6971 #ifdef MPACK_MALLOC
6972 // It's much faster to allocate the initial parsing stack inline within the
6973 // parser. We replace it with a heap allocation if we need to grow it.
6974 mpack_level_t* stack;
6975 size_t stack_capacity;
6976 bool stack_owned;
6977 mpack_level_t stack_local[MPACK_NODE_INITIAL_DEPTH];
6978 #else
6979 // Without malloc(), we have to reserve a parsing stack the maximum allowed
6980 // parsing depth.
6981 mpack_level_t stack[MPACK_NODE_MAX_DEPTH_WITHOUT_MALLOC];
6982 #endif
6983} mpack_tree_parser_t;
6984
6985struct mpack_tree_t {
6986 mpack_tree_error_t error_fn; /* Function to call on error */
6987 mpack_tree_read_t read_fn; /* Function to call to read more data */
6988 mpack_tree_teardown_t teardown; /* Function to teardown the context on destroy */
6989 void* context; /* Context for tree callbacks */
6990
6991 mpack_node_data_t nil_node; /* a nil node to be returned in case of error */
6992 mpack_node_data_t missing_node; /* a missing node to be returned in optional lookups */
6994
6995 #ifdef MPACK_MALLOC
6996 char* buffer;
6997 size_t buffer_capacity;
6998 #endif
6999
7000 const char* data;
7001 size_t data_length; // length of data (and content of buffer, if used)
7002
7003 size_t size; // size in bytes of tree (usually matches data_length, but not if tree has trailing data)
7004 size_t node_count; // total number of nodes in tree (across all pages)
7005
7006 size_t max_size; // maximum message size
7007 size_t max_nodes; // maximum nodes in a message
7008
7009 mpack_tree_parser_t parser;
7010 mpack_node_data_t* root;
7011
7012 mpack_node_data_t* pool; // pool, or NULL if no pool provided
7013 size_t pool_count;
7014
7015 #ifdef MPACK_MALLOC
7016 mpack_tree_page_t* next;
7017 #endif
7018};
7019
7020// internal functions
7021
7022MPACK_INLINE mpack_node_t mpack_node(mpack_tree_t* tree, mpack_node_data_t* data) {
7023 mpack_node_t node;
7024 node.data = data;
7025 node.tree = tree;
7026 return node;
7027}
7028
7029MPACK_INLINE mpack_node_data_t* mpack_node_child(mpack_node_t node, size_t child) {
7030 return node.data->value.children + child;
7031}
7032
7033MPACK_INLINE mpack_node_t mpack_tree_nil_node(mpack_tree_t* tree) {
7034 return mpack_node(tree, &tree->nil_node);
7035}
7036
7037MPACK_INLINE mpack_node_t mpack_tree_missing_node(mpack_tree_t* tree) {
7038 return mpack_node(tree, &tree->missing_node);
7039}
7040
7041/** @endcond */
7042
7043
7044
7045/**
7046 * @name Tree Initialization
7047 * @{
7048 */
7049
7050#ifdef MPACK_MALLOC
7051/**
7052 * Initializes a tree parser with the given data.
7053 *
7054 * Configure the tree if desired, then call mpack_tree_parse() to parse it. The
7055 * tree will allocate pages of nodes as needed and will free them when
7056 * destroyed.
7057 *
7058 * The tree must be destroyed with mpack_tree_destroy().
7059 *
7060 * Any string or blob data types reference the original data, so the given data
7061 * pointer must remain valid until after the tree is destroyed.
7062 */
7063void mpack_tree_init_data(mpack_tree_t* tree, const char* data, size_t length);
7064
7065/**
7066 * Deprecated.
7067 *
7068 * \deprecated Renamed to mpack_tree_init_data().
7069 */
7070MPACK_INLINE void mpack_tree_init(mpack_tree_t* tree, const char* data, size_t length) {
7071 mpack_tree_init_data(tree, data, length);
7072}
7073
7074/**
7075 * Initializes a tree parser from an unbounded stream, or a stream of
7076 * unknown length.
7077 *
7078 * The parser can be used to read a single message from a stream of unknown
7079 * length, or multiple messages from an unbounded stream, allowing it to
7080 * be used for RPC communication. Call @ref mpack_tree_parse() to parse
7081 * a message from a blocking stream, or @ref mpack_tree_try_parse() for a
7082 * non-blocking stream.
7083 *
7084 * The stream will use a growable internal buffer to store the most recent
7085 * message, as well as allocated pages of nodes for the parse tree.
7086 *
7087 * Maximum allowances for message size and node count must be specified in this
7088 * function (since the stream is unbounded.) They can be changed later with
7089 * @ref mpack_tree_set_limits().
7090 *
7091 * @param tree The tree parser
7092 * @param read_fn The read function
7093 * @param context The context for the read function
7094 * @param max_message_size The maximum size of a message in bytes
7095 * @param max_message_nodes The maximum number of nodes per message. See
7096 * @ref mpack_node_data_t for the size of nodes.
7097 *
7098 * @see mpack_tree_read_t
7099 * @see mpack_reader_context()
7100 */
7101void mpack_tree_init_stream(mpack_tree_t* tree, mpack_tree_read_t read_fn, void* context,
7102 size_t max_message_size, size_t max_message_nodes);
7103#endif
7104
7105/**
7106 * Initializes a tree parser with the given data, using the given node data
7107 * pool to store the results.
7108 *
7109 * Configure the tree if desired, then call mpack_tree_parse() to parse it.
7110 *
7111 * If the data does not fit in the pool, @ref mpack_error_too_big will be flagged
7112 * on the tree.
7113 *
7114 * The tree must be destroyed with mpack_tree_destroy(), even if parsing fails.
7115 */
7116void mpack_tree_init_pool(mpack_tree_t* tree, const char* data, size_t length,
7117 mpack_node_data_t* node_pool, size_t node_pool_count);
7118
7119/**
7120 * Initializes an MPack tree directly into an error state. Use this if you
7121 * are writing a wrapper to another <tt>mpack_tree_init*()</tt> function which
7122 * can fail its setup.
7123 */
7125
7126#if MPACK_STDIO
7127/**
7128 * Initializes a tree to parse the given file. The tree must be destroyed with
7129 * mpack_tree_destroy(), even if parsing fails.
7130 *
7131 * The file is opened, loaded fully into memory, and closed before this call
7132 * returns.
7133 *
7134 * @param tree The tree to initialize
7135 * @param filename The filename passed to fopen() to read the file
7136 * @param max_bytes The maximum size of file to load, or 0 for unlimited size.
7137 */
7138void mpack_tree_init_filename(mpack_tree_t* tree, const char* filename, size_t max_bytes);
7139
7140/**
7141 * Deprecated.
7142 *
7143 * \deprecated Renamed to mpack_tree_init_filename().
7144 */
7145MPACK_INLINE void mpack_tree_init_file(mpack_tree_t* tree, const char* filename, size_t max_bytes) {
7146 mpack_tree_init_filename(tree, filename, max_bytes);
7147}
7148
7149/**
7150 * Initializes a tree to parse the given libc FILE. This can be used to
7151 * read from stdin, or from a file opened separately.
7152 *
7153 * The tree must be destroyed with mpack_tree_destroy(), even if parsing fails.
7154 *
7155 * The FILE is fully loaded fully into memory (and closed if requested) before
7156 * this call returns.
7157 *
7158 * @param tree The tree to initialize.
7159 * @param stdfile The FILE.
7160 * @param max_bytes The maximum size of file to load, or 0 for unlimited size.
7161 * @param close_when_done If true, fclose() will be called on the FILE when it
7162 * is no longer needed. If false, the file will not be closed when
7163 * reading is done.
7164 *
7165 * @warning The tree will read all data in the FILE before parsing it. If this
7166 * is used on stdin, the parser will block until it is closed, even if
7167 * a complete message has been written to it!
7168 */
7169void mpack_tree_init_stdfile(mpack_tree_t* tree, FILE* stdfile, size_t max_bytes, bool close_when_done);
7170#endif
7171
7172/**
7173 * @}
7174 */
7175
7176/**
7177 * @name Tree Functions
7178 * @{
7179 */
7180
7181/**
7182 * Sets the maximum byte size and maximum number of nodes allowed per message.
7183 *
7184 * The default is SIZE_MAX (no limit) unless @ref mpack_tree_init_stream() is
7185 * called (where maximums are required.)
7186 *
7187 * If a pool of nodes is used, the node limit is the lesser of this limit and
7188 * the pool size.
7189 *
7190 * @param tree The tree parser
7191 * @param max_message_size The maximum size of a message in bytes
7192 * @param max_message_nodes The maximum number of nodes per message. See
7193 * @ref mpack_node_data_t for the size of nodes.
7194 */
7195void mpack_tree_set_limits(mpack_tree_t* tree, size_t max_message_size,
7196 size_t max_message_nodes);
7197
7198/**
7199 * Parses a MessagePack message into a tree of immutable nodes.
7200 *
7201 * If successful, the root node will be available under @ref mpack_tree_root().
7202 * If not, an appropriate error will be flagged.
7203 *
7204 * This can be called repeatedly to parse a series of messages from a data
7205 * source. When this is called, all previous nodes from this tree and their
7206 * contents (including the root node) are invalidated.
7207 *
7208 * If this is called with a stream (see @ref mpack_tree_init_stream()), the
7209 * stream must block until data is available. (Otherwise, if this is called on
7210 * a non-blocking stream, parsing will fail with @ref mpack_error_io when the
7211 * fill function returns 0.)
7212 *
7213 * There is no way to recover a tree in an error state. It must be destroyed.
7214 */
7216
7217/**
7218 * Attempts to parse a MessagePack message from a non-blocking stream into a
7219 * tree of immutable nodes.
7220 *
7221 * A non-blocking read function must have been passed to the tree in
7222 * mpack_tree_init_stream().
7223 *
7224 * If this returns true, a message is available under
7225 * @ref mpack_tree_root(). The tree nodes and data will be valid until
7226 * the next time a parse is started.
7227 *
7228 * If this returns false, no message is available, because either not enough
7229 * data is available yet or an error has occurred. You must check the tree for
7230 * errors whenever this returns false. If there is no error, you should try
7231 * again later when more data is available. (You will want to select()/poll()
7232 * on the underlying socket or use some other asynchronous mechanism to
7233 * determine when it has data.)
7234 *
7235 * There is no way to recover a tree in an error state. It must be destroyed.
7236 *
7237 * @see mpack_tree_init_stream()
7238 */
7240
7241/**
7242 * Returns the root node of the tree, if the tree is not in an error state.
7243 * Returns a nil node otherwise.
7244 *
7245 * @warning You must call mpack_tree_parse() before calling this. If
7246 * @ref mpack_tree_parse() was never called, the tree will assert.
7247 */
7249
7250/**
7251 * Returns the error state of the tree.
7252 */
7254 return tree->error;
7255}
7256
7257/**
7258 * Returns the size in bytes of the current parsed message.
7259 *
7260 * If there is something in the buffer after the MessagePack object, this can
7261 * be used to find it.
7262 *
7263 * This is zero if an error occurred during tree parsing (since the
7264 * portion of the data that the first complete object occupies cannot
7265 * be determined if the data is invalid or corrupted.)
7266 */
7267MPACK_INLINE size_t mpack_tree_size(mpack_tree_t* tree) {
7268 return tree->size;
7269}
7270
7271/**
7272 * Destroys the tree.
7273 */
7275
7276/**
7277 * Sets the custom pointer to pass to the tree callbacks, such as teardown.
7278 *
7279 * @param tree The MPack tree.
7280 * @param context User data to pass to the tree callbacks.
7281 *
7282 * @see mpack_reader_context()
7283 */
7284MPACK_INLINE void mpack_tree_set_context(mpack_tree_t* tree, void* context) {
7285 tree->context = context;
7286}
7287
7288/**
7289 * Returns the custom context for tree callbacks.
7290 *
7291 * @see mpack_tree_set_context
7292 * @see mpack_tree_init_stream
7293 */
7294MPACK_INLINE void* mpack_tree_context(mpack_tree_t* tree) {
7295 return tree->context;
7296}
7297
7298/**
7299 * Sets the error function to call when an error is flagged on the tree.
7300 *
7301 * This should normally be used with mpack_tree_set_context() to register
7302 * a custom pointer to pass to the error function.
7303 *
7304 * See the definition of mpack_tree_error_t for more information about
7305 * what you can do from an error callback.
7306 *
7307 * @see mpack_tree_error_t
7308 * @param tree The MPack tree.
7309 * @param error_fn The function to call when an error is flagged on the tree.
7310 */
7312 tree->error_fn = error_fn;
7313}
7314
7315/**
7316 * Sets the teardown function to call when the tree is destroyed.
7317 *
7318 * This should normally be used with mpack_tree_set_context() to register
7319 * a custom pointer to pass to the teardown function.
7320 *
7321 * @param tree The MPack tree.
7322 * @param teardown The function to call when the tree is destroyed.
7323 */
7325 tree->teardown = teardown;
7326}
7327
7328/**
7329 * Places the tree in the given error state, calling the error callback if one
7330 * is set.
7331 *
7332 * This allows you to externally flag errors, for example if you are validating
7333 * data as you read it.
7334 *
7335 * If the tree is already in an error state, this call is ignored and no
7336 * error callback is called.
7337 */
7339
7340/**
7341 * @}
7342 */
7343
7344/**
7345 * @name Node Core Functions
7346 * @{
7347 */
7348
7349/**
7350 * Places the node's tree in the given error state, calling the error callback
7351 * if one is set.
7352 *
7353 * This allows you to externally flag errors, for example if you are validating
7354 * data as you read it.
7355 *
7356 * If the tree is already in an error state, this call is ignored and no
7357 * error callback is called.
7358 */
7360
7361/**
7362 * Returns the error state of the node's tree.
7363 */
7365 return mpack_tree_error(node.tree);
7366}
7367
7368/**
7369 * Returns a tag describing the given node, or a nil tag if the
7370 * tree is in an error state.
7371 */
7373
7374/** @cond */
7375
7376#if MPACK_DEBUG && MPACK_STDIO
7377/*
7378 * Converts a node to a pseudo-JSON string for debugging purposes, placing the
7379 * result in the given buffer with a null-terminator.
7380 *
7381 * If the buffer does not have enough space, the result will be truncated (but
7382 * it is guaranteed to be null-terminated.)
7383 *
7384 * This is only available in debug mode, and only if stdio is available (since
7385 * it uses snprintf().) It's strictly for debugging purposes.
7386 */
7387void mpack_node_print_to_buffer(mpack_node_t node, char* buffer, size_t buffer_size);
7388
7389/*
7390 * Converts a node to pseudo-JSON for debugging purposes, calling the given
7391 * callback as many times as is necessary to output the character data.
7392 *
7393 * No null-terminator or trailing newline will be written.
7394 *
7395 * This is only available in debug mode, and only if stdio is available (since
7396 * it uses snprintf().) It's strictly for debugging purposes.
7397 */
7398void mpack_node_print_to_callback(mpack_node_t node, mpack_print_callback_t callback, void* context);
7399
7400/*
7401 * Converts a node to pseudo-JSON for debugging purposes
7402 * and pretty-prints it to the given file.
7403 *
7404 * This is only available in debug mode, and only if stdio is available (since
7405 * it uses snprintf().) It's strictly for debugging purposes.
7406 */
7407void mpack_node_print_to_file(mpack_node_t node, FILE* file);
7408
7409/*
7410 * Converts a node to pseudo-JSON for debugging purposes
7411 * and pretty-prints it to stdout.
7412 *
7413 * This is only available in debug mode, and only if stdio is available (since
7414 * it uses snprintf().) It's strictly for debugging purposes.
7415 */
7416MPACK_INLINE void mpack_node_print_to_stdout(mpack_node_t node) {
7417 mpack_node_print_to_file(node, stdout);
7418}
7419
7420/*
7421 * Deprecated.
7422 *
7423 * \deprecated Renamed to mpack_node_print_to_stdout().
7424 */
7425MPACK_INLINE void mpack_node_print(mpack_node_t node) {
7426 mpack_node_print_to_stdout(node);
7427}
7428#endif
7429
7430/** @endcond */
7431
7432/**
7433 * @}
7434 */
7435
7436/**
7437 * @name Node Primitive Value Functions
7438 * @{
7439 */
7440
7441/**
7442 * Returns the type of the node.
7443 */
7445
7446/**
7447 * Returns true if the given node is a nil node; false otherwise.
7448 *
7449 * To ensure that a node is nil and flag an error otherwise, use
7450 * mpack_node_nil().
7451 */
7453
7454/**
7455 * Returns true if the given node handle indicates a missing node; false otherwise.
7456 *
7457 * To ensure that a node is missing and flag an error otherwise, use
7458 * mpack_node_missing().
7459 */
7461
7462/**
7463 * Checks that the given node is of nil type, raising @ref mpack_error_type
7464 * otherwise.
7465 *
7466 * Use mpack_node_is_nil() to return whether the node is nil.
7467 */
7469
7470/**
7471 * Checks that the given node indicates a missing node, raising @ref
7472 * mpack_error_type otherwise.
7473 *
7474 * Use mpack_node_is_missing() to return whether the node is missing.
7475 */
7477
7478/**
7479 * Returns the bool value of the node. If this node is not of the correct
7480 * type, false is returned and mpack_error_type is raised.
7481 */
7483
7484/**
7485 * Checks if the given node is of bool type with value true, raising
7486 * mpack_error_type otherwise.
7487 */
7489
7490/**
7491 * Checks if the given node is of bool type with value false, raising
7492 * mpack_error_type otherwise.
7493 */
7495
7496/**
7497 * Returns the 8-bit unsigned value of the node. If this node is not
7498 * of a compatible type, @ref mpack_error_type is raised and zero is returned.
7499 */
7501
7502/**
7503 * Returns the 8-bit signed value of the node. If this node is not
7504 * of a compatible type, @ref mpack_error_type is raised and zero is returned.
7505 */
7507
7508/**
7509 * Returns the 16-bit unsigned value of the node. If this node is not
7510 * of a compatible type, @ref mpack_error_type is raised and zero is returned.
7511 */
7513
7514/**
7515 * Returns the 16-bit signed value of the node. If this node is not
7516 * of a compatible type, @ref mpack_error_type is raised and zero is returned.
7517 */
7519
7520/**
7521 * Returns the 32-bit unsigned value of the node. If this node is not
7522 * of a compatible type, @ref mpack_error_type is raised and zero is returned.
7523 */
7525
7526/**
7527 * Returns the 32-bit signed value of the node. If this node is not
7528 * of a compatible type, @ref mpack_error_type is raised and zero is returned.
7529 */
7531
7532/**
7533 * Returns the 64-bit unsigned value of the node. If this node is not
7534 * of a compatible type, @ref mpack_error_type is raised, and zero is returned.
7535 */
7537
7538/**
7539 * Returns the 64-bit signed value of the node. If this node is not
7540 * of a compatible type, @ref mpack_error_type is raised and zero is returned.
7541 */
7543
7544/**
7545 * Returns the unsigned int value of the node.
7546 *
7547 * Returns zero if an error occurs.
7548 *
7549 * @throws mpack_error_type If the node is not an integer type or does not fit in the range of an unsigned int
7550 */
7552
7553/**
7554 * Returns the int value of the node.
7555 *
7556 * Returns zero if an error occurs.
7557 *
7558 * @throws mpack_error_type If the node is not an integer type or does not fit in the range of an int
7559 */
7561
7562#if MPACK_FLOAT
7563/**
7564 * Returns the float value of the node. The underlying value can be an
7565 * integer, float or double; the value is converted to a float.
7566 *
7567 * @note Reading a double or a large integer with this function can incur a
7568 * loss of precision.
7569 *
7570 * @throws mpack_error_type if the underlying value is not a float, double or integer.
7571 */
7573#endif
7574
7575#if MPACK_DOUBLE
7576/**
7577 * Returns the double value of the node. The underlying value can be an
7578 * integer, float or double; the value is converted to a double.
7579 *
7580 * @note Reading a very large integer with this function can incur a
7581 * loss of precision.
7582 *
7583 * @throws mpack_error_type if the underlying value is not a float, double or integer.
7584 */
7586#endif
7587
7588#if MPACK_FLOAT
7589/**
7590 * Returns the float value of the node. The underlying value must be a float,
7591 * not a double or an integer. This ensures no loss of precision can occur.
7592 *
7593 * @throws mpack_error_type if the underlying value is not a float.
7594 */
7596#endif
7597
7598#if MPACK_DOUBLE
7599/**
7600 * Returns the double value of the node. The underlying value must be a float
7601 * or double, not an integer. This ensures no loss of precision can occur.
7602 *
7603 * @throws mpack_error_type if the underlying value is not a float or double.
7604 */
7606#endif
7607
7608#if !MPACK_FLOAT
7609/**
7610 * Returns the float value of the node as a raw uint32_t. The underlying value
7611 * must be a float, not a double or an integer.
7612 *
7613 * @throws mpack_error_type if the underlying value is not a float.
7614 */
7615uint32_t mpack_node_raw_float(mpack_node_t node);
7616#endif
7617
7618#if !MPACK_DOUBLE
7619/**
7620 * Returns the double value of the node as a raw uint64_t. The underlying value
7621 * must be a double, not a float or an integer.
7622 *
7623 * @throws mpack_error_type if the underlying value is not a float or double.
7624 */
7625uint64_t mpack_node_raw_double(mpack_node_t node);
7626#endif
7627
7628
7629#if MPACK_EXTENSIONS
7630/**
7631 * Returns a timestamp.
7632 *
7633 * @note This requires @ref MPACK_EXTENSIONS.
7634 *
7635 * @throws mpack_error_type if the underlying value is not a timestamp.
7636 */
7637mpack_timestamp_t mpack_node_timestamp(mpack_node_t node);
7638
7639/**
7640 * Returns a timestamp's (signed) seconds since 1970-01-01T00:00:00Z.
7641 *
7642 * @note This requires @ref MPACK_EXTENSIONS.
7643 *
7644 * @throws mpack_error_type if the underlying value is not a timestamp.
7645 */
7646int64_t mpack_node_timestamp_seconds(mpack_node_t node);
7647
7648/**
7649 * Returns a timestamp's additional nanoseconds.
7650 *
7651 * @note This requires @ref MPACK_EXTENSIONS.
7652 *
7653 * @return A nanosecond count between 0 and 999,999,999 inclusive.
7654 * @throws mpack_error_type if the underlying value is not a timestamp.
7655 */
7656uint32_t mpack_node_timestamp_nanoseconds(mpack_node_t node);
7657#endif
7658
7659/**
7660 * @}
7661 */
7662
7663/**
7664 * @name Node String and Data Functions
7665 * @{
7666 */
7667
7668/**
7669 * Checks that the given node contains a valid UTF-8 string.
7670 *
7671 * If the string is invalid, this flags an error, which would cause subsequent calls
7672 * to mpack_node_str() to return NULL and mpack_node_strlen() to return zero. So you
7673 * can check the node for error immediately after calling this, or you can call those
7674 * functions to use the data anyway and check for errors later.
7675 *
7676 * @throws mpack_error_type If this node is not a string or does not contain valid UTF-8.
7677 *
7678 * @param node The string node to test
7679 *
7680 * @see mpack_node_str()
7681 * @see mpack_node_strlen()
7682 */
7684
7685/**
7686 * Checks that the given node contains a valid UTF-8 string with no NUL bytes.
7687 *
7688 * This does not check that the string has a null-terminator! It only checks whether
7689 * the string could safely be represented as a C-string by appending a null-terminator.
7690 * (If the string does already contain a null-terminator, this will flag an error.)
7691 *
7692 * This is performed automatically by other UTF-8 cstr helper functions. Only
7693 * call this if you will do something else with the data directly, but you still
7694 * want to ensure it will be valid as a UTF-8 C-string.
7695 *
7696 * @throws mpack_error_type If this node is not a string, does not contain valid UTF-8,
7697 * or contains a NUL byte.
7698 *
7699 * @param node The string node to test
7700 *
7701 * @see mpack_node_str()
7702 * @see mpack_node_strlen()
7703 * @see mpack_node_copy_utf8_cstr()
7704 * @see mpack_node_utf8_cstr_alloc()
7705 */
7707
7708#if MPACK_EXTENSIONS
7709/**
7710 * Returns the extension type of the given ext node.
7711 *
7712 * This returns zero if the tree is in an error state.
7713 *
7714 * @note This requires @ref MPACK_EXTENSIONS.
7715 */
7716int8_t mpack_node_exttype(mpack_node_t node);
7717#endif
7718
7719/**
7720 * Returns the number of bytes in the given bin node.
7721 *
7722 * This returns zero if the tree is in an error state.
7723 *
7724 * If this node is not a bin, @ref mpack_error_type is raised and zero is returned.
7725 */
7727
7728/**
7729 * Returns the length of the given str, bin or ext node.
7730 *
7731 * This returns zero if the tree is in an error state.
7732 *
7733 * If this node is not a str, bin or ext, @ref mpack_error_type is raised and zero
7734 * is returned.
7735 */
7737
7738/**
7739 * Returns the length in bytes of the given string node. This does not
7740 * include any null-terminator.
7741 *
7742 * This returns zero if the tree is in an error state.
7743 *
7744 * If this node is not a str, @ref mpack_error_type is raised and zero is returned.
7745 */
7747
7748/**
7749 * Returns a pointer to the data contained by this node, ensuring the node is a
7750 * string.
7751 *
7752 * @warning Strings are not null-terminated! Use one of the cstr functions
7753 * to get a null-terminated string.
7754 *
7755 * The pointer is valid as long as the data backing the tree is valid.
7756 *
7757 * If this node is not a string, @ref mpack_error_type is raised and @c NULL is returned.
7758 *
7759 * @see mpack_node_copy_cstr()
7760 * @see mpack_node_cstr_alloc()
7761 * @see mpack_node_utf8_cstr_alloc()
7762 */
7764
7765/**
7766 * Returns a pointer to the data contained by this node.
7767 *
7768 * @note Strings are not null-terminated! Use one of the cstr functions
7769 * to get a null-terminated string.
7770 *
7771 * The pointer is valid as long as the data backing the tree is valid.
7772 *
7773 * If this node is not of a str, bin or ext, @ref mpack_error_type is raised, and
7774 * @c NULL is returned.
7775 *
7776 * @see mpack_node_copy_cstr()
7777 * @see mpack_node_cstr_alloc()
7778 * @see mpack_node_utf8_cstr_alloc()
7779 */
7781
7782/**
7783 * Returns a pointer to the data contained by this bin node.
7784 *
7785 * The pointer is valid as long as the data backing the tree is valid.
7786 *
7787 * If this node is not a bin, @ref mpack_error_type is raised and @c NULL is
7788 * returned.
7789 */
7791
7792/**
7793 * Copies the bytes contained by this node into the given buffer, returning the
7794 * number of bytes in the node.
7795 *
7796 * @throws mpack_error_type If this node is not a str, bin or ext type
7797 * @throws mpack_error_too_big If the string does not fit in the given buffer
7798 *
7799 * @param node The string node from which to copy data
7800 * @param buffer A buffer in which to copy the node's bytes
7801 * @param bufsize The size of the given buffer
7802 *
7803 * @return The number of bytes in the node, or zero if an error occurs.
7804 */
7805size_t mpack_node_copy_data(mpack_node_t node, char* buffer, size_t bufsize);
7806
7807/**
7808 * Checks that the given node contains a valid UTF-8 string and copies the
7809 * string into the given buffer, returning the number of bytes in the string.
7810 *
7811 * @throws mpack_error_type If this node is not a string
7812 * @throws mpack_error_too_big If the string does not fit in the given buffer
7813 *
7814 * @param node The string node from which to copy data
7815 * @param buffer A buffer in which to copy the node's bytes
7816 * @param bufsize The size of the given buffer
7817 *
7818 * @return The number of bytes in the node, or zero if an error occurs.
7819 */
7820size_t mpack_node_copy_utf8(mpack_node_t node, char* buffer, size_t bufsize);
7821
7822/**
7823 * Checks that the given node contains a string with no NUL bytes, copies the string
7824 * into the given buffer, and adds a null terminator.
7825 *
7826 * If this node is not of a string type, @ref mpack_error_type is raised. If the string
7827 * does not fit, @ref mpack_error_data is raised.
7828 *
7829 * If any error occurs, the buffer will contain an empty null-terminated string.
7830 *
7831 * @param node The string node from which to copy data
7832 * @param buffer A buffer in which to copy the node's string
7833 * @param size The size of the given buffer
7834 */
7835void mpack_node_copy_cstr(mpack_node_t node, char* buffer, size_t size);
7836
7837/**
7838 * Checks that the given node contains a valid UTF-8 string with no NUL bytes,
7839 * copies the string into the given buffer, and adds a null terminator.
7840 *
7841 * If this node is not of a string type, @ref mpack_error_type is raised. If the string
7842 * does not fit, @ref mpack_error_data is raised.
7843 *
7844 * If any error occurs, the buffer will contain an empty null-terminated string.
7845 *
7846 * @param node The string node from which to copy data
7847 * @param buffer A buffer in which to copy the node's string
7848 * @param size The size of the given buffer
7849 */
7850void mpack_node_copy_utf8_cstr(mpack_node_t node, char* buffer, size_t size);
7851
7852#ifdef MPACK_MALLOC
7853/**
7854 * Allocates a new chunk of data using MPACK_MALLOC() with the bytes
7855 * contained by this node.
7856 *
7857 * The allocated data must be freed with MPACK_FREE() (or simply free()
7858 * if MPack's allocator hasn't been customized.)
7859 *
7860 * @throws mpack_error_type If this node is not a str, bin or ext type
7861 * @throws mpack_error_too_big If the size of the data is larger than the
7862 * given maximum size
7863 * @throws mpack_error_memory If an allocation failure occurs
7864 *
7865 * @param node The node from which to allocate and copy data
7866 * @param maxsize The maximum size to allocate
7867 *
7868 * @return The allocated data, or NULL if any error occurs.
7869 */
7870char* mpack_node_data_alloc(mpack_node_t node, size_t maxsize);
7871
7872/**
7873 * Allocates a new null-terminated string using MPACK_MALLOC() with the string
7874 * contained by this node.
7875 *
7876 * The allocated string must be freed with MPACK_FREE() (or simply free()
7877 * if MPack's allocator hasn't been customized.)
7878 *
7879 * @throws mpack_error_type If this node is not a string or contains NUL bytes
7880 * @throws mpack_error_too_big If the size of the string plus null-terminator
7881 * is larger than the given maximum size
7882 * @throws mpack_error_memory If an allocation failure occurs
7883 *
7884 * @param node The node from which to allocate and copy string data
7885 * @param maxsize The maximum size to allocate, including the null-terminator
7886 *
7887 * @return The allocated string, or NULL if any error occurs.
7888 */
7889char* mpack_node_cstr_alloc(mpack_node_t node, size_t maxsize);
7890
7891/**
7892 * Allocates a new null-terminated string using MPACK_MALLOC() with the UTF-8
7893 * string contained by this node.
7894 *
7895 * The allocated string must be freed with MPACK_FREE() (or simply free()
7896 * if MPack's allocator hasn't been customized.)
7897 *
7898 * @throws mpack_error_type If this node is not a string, is not valid UTF-8,
7899 * or contains NUL bytes
7900 * @throws mpack_error_too_big If the size of the string plus null-terminator
7901 * is larger than the given maximum size
7902 * @throws mpack_error_memory If an allocation failure occurs
7903 *
7904 * @param node The node from which to allocate and copy string data
7905 * @param maxsize The maximum size to allocate, including the null-terminator
7906 *
7907 * @return The allocated string, or NULL if any error occurs.
7908 */
7909char* mpack_node_utf8_cstr_alloc(mpack_node_t node, size_t maxsize);
7910#endif
7911
7912/**
7913 * Searches the given string array for a string matching the given
7914 * node and returns its index.
7915 *
7916 * If the node does not match any of the given strings,
7917 * @ref mpack_error_type is flagged. Use mpack_node_enum_optional()
7918 * if you want to allow values other than the given strings.
7919 *
7920 * If any error occurs or if the tree is in an error state, @a count
7921 * is returned.
7922 *
7923 * This can be used to quickly parse a string into an enum when the
7924 * enum values range from 0 to @a count-1. If the last value in the
7925 * enum is a special "count" value, it can be passed as the count,
7926 * and the return value can be cast directly to the enum type.
7927 *
7928 * @code{.c}
7929 * typedef enum { APPLE , BANANA , ORANGE , COUNT} fruit_t;
7930 * const char* fruits[] = {"apple", "banana", "orange"};
7931 *
7932 * fruit_t fruit = (fruit_t)mpack_node_enum(node, fruits, COUNT);
7933 * @endcode
7934 *
7935 * @param node The node
7936 * @param strings An array of expected strings of length count
7937 * @param count The number of strings
7938 * @return The index of the matched string, or @a count in case of error
7939 */
7940size_t mpack_node_enum(mpack_node_t node, const char* strings[], size_t count);
7941
7942/**
7943 * Searches the given string array for a string matching the given node,
7944 * returning its index or @a count if no strings match.
7945 *
7946 * If the value is not a string, or it does not match any of the
7947 * given strings, @a count is returned and no error is flagged.
7948 *
7949 * If any error occurs or if the tree is in an error state, @a count
7950 * is returned.
7951 *
7952 * This can be used to quickly parse a string into an enum when the
7953 * enum values range from 0 to @a count-1. If the last value in the
7954 * enum is a special "count" value, it can be passed as the count,
7955 * and the return value can be cast directly to the enum type.
7956 *
7957 * @code{.c}
7958 * typedef enum { APPLE , BANANA , ORANGE , COUNT} fruit_t;
7959 * const char* fruits[] = {"apple", "banana", "orange"};
7960 *
7961 * fruit_t fruit = (fruit_t)mpack_node_enum_optional(node, fruits, COUNT);
7962 * @endcode
7963 *
7964 * @param node The node
7965 * @param strings An array of expected strings of length count
7966 * @param count The number of strings
7967 * @return The index of the matched string, or @a count in case of error
7968 */
7969size_t mpack_node_enum_optional(mpack_node_t node, const char* strings[], size_t count);
7970
7971/**
7972 * @}
7973 */
7974
7975/**
7976 * @name Compound Node Functions
7977 * @{
7978 */
7979
7980/**
7981 * Returns the length of the given array node. Raises mpack_error_type
7982 * and returns 0 if the given node is not an array.
7983 */
7985
7986/**
7987 * Returns the node in the given array at the given index. If the node
7988 * is not an array, @ref mpack_error_type is raised and a nil node is returned.
7989 * If the given index is out of bounds, @ref mpack_error_data is raised and
7990 * a nil node is returned.
7991 */
7993
7994/**
7995 * Returns the number of key/value pairs in the given map node. Raises
7996 * mpack_error_type and returns 0 if the given node is not a map.
7997 */
7999
8000/**
8001 * Returns the key node in the given map at the given index.
8002 *
8003 * A nil node is returned in case of error.
8004 *
8005 * @throws mpack_error_type if the node is not a map
8006 * @throws mpack_error_data if the given index is out of bounds
8007 */
8009
8010/**
8011 * Returns the value node in the given map at the given index.
8012 *
8013 * A nil node is returned in case of error.
8014 *
8015 * @throws mpack_error_type if the node is not a map
8016 * @throws mpack_error_data if the given index is out of bounds
8017 */
8019
8020/**
8021 * Returns the value node in the given map for the given integer key.
8022 *
8023 * The key must exist within the map. Use mpack_node_map_int_optional() to
8024 * check for optional keys.
8025 *
8026 * The key must be unique. An error is flagged if the node has multiple
8027 * entries with the given key.
8028 *
8029 * @throws mpack_error_type If the node is not a map
8030 * @throws mpack_error_data If the node does not contain exactly one entry with the given key
8031 *
8032 * @return The value node for the given key, or a nil node in case of error
8033 */
8035
8036/**
8037 * Returns the value node in the given map for the given integer key, or a
8038 * missing node if the map does not contain the given key.
8039 *
8040 * The key must be unique. An error is flagged if the node has multiple
8041 * entries with the given key.
8042 *
8043 * @throws mpack_error_type If the node is not a map
8044 * @throws mpack_error_data If the node contains more than one entry with the given key
8045 *
8046 * @return The value node for the given key, or a missing node if the key does
8047 * not exist, or a nil node in case of error
8048 *
8049 * @see mpack_node_is_missing()
8050 */
8052
8053/**
8054 * Returns the value node in the given map for the given unsigned integer key.
8055 *
8056 * The key must exist within the map. Use mpack_node_map_uint_optional() to
8057 * check for optional keys.
8058 *
8059 * The key must be unique. An error is flagged if the node has multiple
8060 * entries with the given key.
8061 *
8062 * @throws mpack_error_type If the node is not a map
8063 * @throws mpack_error_data If the node does not contain exactly one entry with the given key
8064 *
8065 * @return The value node for the given key, or a nil node in case of error
8066 */
8068
8069/**
8070 * Returns the value node in the given map for the given unsigned integer
8071 * key, or a missing node if the map does not contain the given key.
8072 *
8073 * The key must be unique. An error is flagged if the node has multiple
8074 * entries with the given key.
8075 *
8076 * @throws mpack_error_type If the node is not a map
8077 * @throws mpack_error_data If the node contains more than one entry with the given key
8078 *
8079 * @return The value node for the given key, or a missing node if the key does
8080 * not exist, or a nil node in case of error
8081 *
8082 * @see mpack_node_is_missing()
8083 */
8085
8086/**
8087 * Returns the value node in the given map for the given string key.
8088 *
8089 * The key must exist within the map. Use mpack_node_map_str_optional() to
8090 * check for optional keys.
8091 *
8092 * The key must be unique. An error is flagged if the node has multiple
8093 * entries with the given key.
8094 *
8095 * @throws mpack_error_type If the node is not a map
8096 * @throws mpack_error_data If the node does not contain exactly one entry with the given key
8097 *
8098 * @return The value node for the given key, or a nil node in case of error
8099 */
8100mpack_node_t mpack_node_map_str(mpack_node_t node, const char* str, size_t length);
8101
8102/**
8103 * Returns the value node in the given map for the given string key, or a missing
8104 * node if the map does not contain the given key.
8105 *
8106 * The key must be unique. An error is flagged if the node has multiple
8107 * entries with the given key.
8108 *
8109 * @throws mpack_error_type If the node is not a map
8110 * @throws mpack_error_data If the node contains more than one entry with the given key
8111 *
8112 * @return The value node for the given key, or a missing node if the key does
8113 * not exist, or a nil node in case of error
8114 *
8115 * @see mpack_node_is_missing()
8116 */
8117mpack_node_t mpack_node_map_str_optional(mpack_node_t node, const char* str, size_t length);
8118
8119/**
8120 * Returns the value node in the given map for the given null-terminated
8121 * string key.
8122 *
8123 * The key must exist within the map. Use mpack_node_map_cstr_optional() to
8124 * check for optional keys.
8125 *
8126 * The key must be unique. An error is flagged if the node has multiple
8127 * entries with the given key.
8128 *
8129 * @throws mpack_error_type If the node is not a map
8130 * @throws mpack_error_data If the node does not contain exactly one entry with the given key
8131 *
8132 * @return The value node for the given key, or a nil node in case of error
8133 */
8135
8136/**
8137 * Returns the value node in the given map for the given null-terminated
8138 * string key, or a missing node if the map does not contain the given key.
8139 *
8140 * The key must be unique. An error is flagged if the node has multiple
8141 * entries with the given key.
8142 *
8143 * @throws mpack_error_type If the node is not a map
8144 * @throws mpack_error_data If the node contains more than one entry with the given key
8145 *
8146 * @return The value node for the given key, or a missing node if the key does
8147 * not exist, or a nil node in case of error
8148 *
8149 * @see mpack_node_is_missing()
8150 */
8152
8153/**
8154 * Returns true if the given node map contains exactly one entry with the
8155 * given integer key.
8156 *
8157 * The key must be unique. An error is flagged if the node has multiple
8158 * entries with the given key.
8159 *
8160 * @throws mpack_error_type If the node is not a map
8161 * @throws mpack_error_data If the node contains more than one entry with the given key
8162 */
8164
8165/**
8166 * Returns true if the given node map contains exactly one entry with the
8167 * given unsigned integer key.
8168 *
8169 * The key must be unique. An error is flagged if the node has multiple
8170 * entries with the given key.
8171 *
8172 * @throws mpack_error_type If the node is not a map
8173 * @throws mpack_error_data If the node contains more than one entry with the given key
8174 */
8176
8177/**
8178 * Returns true if the given node map contains exactly one entry with the
8179 * given string key.
8180 *
8181 * The key must be unique. An error is flagged if the node has multiple
8182 * entries with the given key.
8183 *
8184 * @throws mpack_error_type If the node is not a map
8185 * @throws mpack_error_data If the node contains more than one entry with the given key
8186 */
8187bool mpack_node_map_contains_str(mpack_node_t node, const char* str, size_t length);
8188
8189/**
8190 * Returns true if the given node map contains exactly one entry with the
8191 * given null-terminated string key.
8192 *
8193 * The key must be unique. An error is flagged if the node has multiple
8194 * entries with the given key.
8195 *
8196 * @throws mpack_error_type If the node is not a map
8197 * @throws mpack_error_data If the node contains more than one entry with the given key
8198 */
8199bool mpack_node_map_contains_cstr(mpack_node_t node, const char* cstr);
8200
8201/**
8202 * @}
8203 */
8204
8205/**
8206 * @}
8207 */
8208
8209#endif
8210
8211MPACK_EXTERN_C_END
8212MPACK_SILENCE_WARNINGS_END
8213
8214#endif
8215
8216
8217#endif
8218
then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file
Definition: ThirdPartyNotices.txt:192
Definition: format.h:4134
struct mpack_tag_t mpack_tag_t
An MPack tag is a MessagePack object header.
Definition: mpack.h:2087
MPACK_INLINE mpack_tag_t mpack_tag_array(int32_t count)
Definition: mpack.h:2653
MPACK_INLINE mpack_tag_t mpack_tag_make_double(double value)
Generates a double tag.
Definition: mpack.h:2208
MPACK_INLINE uint32_t mpack_tag_bytes(mpack_tag_t *tag)
Gets the length in bytes of a str-, bin- or ext-type tag.
Definition: mpack.h:2470
#define MPACK_TAG_ZERO
An mpack_tag_t initializer that zeroes the given tag.
Definition: mpack.h:2142
MPACK_INLINE mpack_tag_t mpack_tag_false(void)
Definition: mpack.h:2624
MPACK_INLINE mpack_tag_t mpack_tag_int(int64_t value)
Definition: mpack.h:2629
mpack_type_t
Defines the type of a MessagePack tag.
Definition: mpack.h:2034
MPACK_INLINE mpack_tag_t mpack_tag_make_uint(uint64_t value)
Generates an unsigned int tag.
Definition: mpack.h:2185
MPACK_INLINE mpack_tag_t mpack_tag_make_false(void)
Generates a bool tag with value false.
Definition: mpack.h:2169
MPACK_INLINE mpack_tag_t mpack_tag_uint(uint64_t value)
Definition: mpack.h:2634
MPACK_INLINE mpack_tag_t mpack_tag_bool(bool value)
Definition: mpack.h:2614
MPACK_INLINE mpack_tag_t mpack_tag_nil(void)
Definition: mpack.h:2609
MPACK_INLINE bool mpack_tag_equal(mpack_tag_t left, mpack_tag_t right)
Compares two tags for equality.
Definition: mpack.h:2531
MPACK_INLINE mpack_tag_t mpack_tag_make_array(uint32_t count)
Generates an array tag.
Definition: mpack.h:2221
MPACK_INLINE mpack_tag_t mpack_tag_make_true(void)
Generates a bool tag with value true.
Definition: mpack.h:2161
MPACK_INLINE float mpack_tag_float_value(mpack_tag_t *tag)
Gets the float value of a float-type tag.
Definition: mpack.h:2344
MPACK_INLINE mpack_tag_t mpack_tag_make_nil(void)
Generates a nil tag.
Definition: mpack.h:2146
const char * mpack_type_to_string(mpack_type_t type)
Converts an MPack type to a string.
MPACK_INLINE mpack_tag_t mpack_tag_str(int32_t length)
Definition: mpack.h:2663
MPACK_INLINE double mpack_tag_double_value(mpack_tag_t *tag)
Gets the double value of a double-type tag.
Definition: mpack.h:2366
MPACK_INLINE mpack_tag_t mpack_tag_make_str(uint32_t length)
Generates a str tag.
Definition: mpack.h:2237
MPACK_INLINE mpack_tag_t mpack_tag_bin(int32_t length)
Definition: mpack.h:2668
MPACK_INLINE uint32_t mpack_tag_bin_length(mpack_tag_t *tag)
Gets the length in bytes of a bin-type tag.
Definition: mpack.h:2422
MPACK_INLINE mpack_tag_t mpack_tag_true(void)
Definition: mpack.h:2619
MPACK_INLINE mpack_tag_t mpack_tag_map(int32_t count)
Definition: mpack.h:2658
MPACK_INLINE mpack_tag_t mpack_tag_make_int(int64_t value)
Generates a signed int tag.
Definition: mpack.h:2177
int mpack_tag_cmp(mpack_tag_t left, mpack_tag_t right)
Compares two tags with an arbitrary fixed ordering.
MPACK_INLINE bool mpack_tag_bool_value(mpack_tag_t *tag)
Gets the boolean value of a bool-type tag.
Definition: mpack.h:2290
MPACK_INLINE uint64_t mpack_tag_uint_value(mpack_tag_t *tag)
Gets the unsigned integer value of a uint-type tag.
Definition: mpack.h:2326
MPACK_INLINE mpack_type_t mpack_tag_type(mpack_tag_t *tag)
Gets the type of a tag.
Definition: mpack.h:2279
MPACK_INLINE mpack_tag_t mpack_tag_make_float(float value)
Generates a float tag.
Definition: mpack.h:2194
mpack_error_t
Error states for MPack objects.
Definition: mpack.h:2008
MPACK_INLINE int64_t mpack_tag_int_value(mpack_tag_t *tag)
Gets the signed integer value of an int-type tag.
Definition: mpack.h:2308
MPACK_INLINE mpack_tag_t mpack_tag_make_map(uint32_t count)
Generates a map tag.
Definition: mpack.h:2229
MPACK_INLINE mpack_tag_t mpack_tag_double(double value)
Definition: mpack.h:2647
const char * mpack_error_to_string(mpack_error_t error)
Converts an MPack error to a string.
MPACK_INLINE mpack_tag_t mpack_tag_float(float value)
Definition: mpack.h:2640
MPACK_INLINE mpack_tag_t mpack_tag_make_bool(bool value)
Generates a bool tag.
Definition: mpack.h:2153
MPACK_INLINE uint32_t mpack_tag_array_count(mpack_tag_t *tag)
Gets the number of elements in an array tag.
Definition: mpack.h:2383
MPACK_INLINE uint32_t mpack_tag_str_length(mpack_tag_t *tag)
Gets the length in bytes of a str-type tag.
Definition: mpack.h:2409
MPACK_INLINE mpack_tag_t mpack_tag_make_bin(uint32_t length)
Generates a bin tag.
Definition: mpack.h:2245
MPACK_INLINE uint32_t mpack_tag_map_count(mpack_tag_t *tag)
Gets the number of key-value pairs in a map tag.
Definition: mpack.h:2396
@ mpack_type_bool
A boolean (true or false.)
Definition: mpack.h:2037
@ mpack_type_map
An ordered map of key/value pairs of MessagePack objects.
Definition: mpack.h:2045
@ mpack_type_missing
Special type indicating a missing optional value.
Definition: mpack.h:2035
@ mpack_type_str
A string.
Definition: mpack.h:2042
@ mpack_type_double
A 64-bit IEEE 754 floating point number.
Definition: mpack.h:2041
@ mpack_type_bin
A chunk of binary data.
Definition: mpack.h:2043
@ mpack_type_nil
A null value.
Definition: mpack.h:2036
@ mpack_type_float
A 32-bit IEEE 754 floating point number.
Definition: mpack.h:2040
@ mpack_type_int
A 64-bit signed integer.
Definition: mpack.h:2038
@ mpack_type_array
An array of MessagePack objects.
Definition: mpack.h:2044
@ mpack_type_uint
A 64-bit unsigned integer.
Definition: mpack.h:2039
@ mpack_error_eof
The reader failed to read because of file or socket EOF.
Definition: mpack.h:2018
@ mpack_error_memory
An allocation failure occurred.
Definition: mpack.h:2015
@ mpack_error_too_big
A read or write was bigger than the maximum size allowed for that operation.
Definition: mpack.h:2014
@ mpack_ok
No error.
Definition: mpack.h:2009
@ mpack_error_io
The reader or writer failed to fill or flush, or some other file or socket error occurred.
Definition: mpack.h:2010
@ mpack_error_invalid
The data read is not valid MessagePack.
Definition: mpack.h:2011
@ mpack_error_unsupported
The data read is not supported by this configuration of MPack.
Definition: mpack.h:2012
@ mpack_error_type
The type or value range did not match what was expected by the caller.
Definition: mpack.h:2013
@ mpack_error_bug
The MPack API was used incorrectly.
Definition: mpack.h:2016
@ mpack_error_data
The contained data is not valid.
Definition: mpack.h:2017
#define MPACK_REALLOC
Defines the realloc function used by MPack.
Definition: mpack.h:488
#define MPACK_NODE_MAX_DEPTH_WITHOUT_MALLOC
The maximum depth for the node parser if MPACK_MALLOC is not available.
Definition: mpack.h:890
#define MPACK_NODE_INITIAL_DEPTH
The initial depth for the node parser.
Definition: mpack.h:883
#define MPACK_BUILDER_INTERNAL_STORAGE_SIZE
Amount of space reserved inside mpack_writer_t for the Builders.
Definition: mpack.h:874
void mpack_expect_uint_match(mpack_reader_t *reader, uint64_t value)
Reads an unsigned integer, ensuring that it exactly matches the given value.
MPACK_INLINE unsigned int mpack_expect_uint_range(mpack_reader_t *reader, unsigned int min_value, unsigned int max_value)
Reads an unsigned integer, ensuring that it falls within the given range.
Definition: mpack.h:5545
bool mpack_expect_array_max_or_nil(mpack_reader_t *reader, uint32_t max_count, uint32_t *count)
Reads a nil node or the start of an array with a number of elements at most max_count,...
float mpack_expect_float_range(mpack_reader_t *reader, float min_value, float max_value)
Reads a number, ensuring that it falls within the given range and returning the value as a float.
uint32_t mpack_expect_array(mpack_reader_t *reader)
Reads the start of an array, returning its element count.
uint32_t mpack_expect_u32_range(mpack_reader_t *reader, uint32_t min_value, uint32_t max_value)
Reads a 32-bit unsigned integer, ensuring that it falls within the given range.
MPACK_INLINE uint8_t mpack_expect_u8_max(mpack_reader_t *reader, uint8_t max_value)
Reads an 8-bit unsigned integer, ensuring that it is at most max_value.
Definition: mpack.h:5561
int32_t mpack_expect_i32_range(mpack_reader_t *reader, int32_t min_value, int32_t max_value)
Reads a 32-bit signed integer, ensuring that it falls within the given range.
MPACK_INLINE int8_t mpack_expect_i8_max(mpack_reader_t *reader, int8_t max_value)
Reads an 8-bit signed integer, ensuring that it is at least zero and at most max_value.
Definition: mpack.h:5678
bool mpack_expect_map_max_or_nil(mpack_reader_t *reader, uint32_t max_count, uint32_t *count)
Reads a nil node or the start of a map with a number of elements at most max_count,...
bool mpack_expect_array_or_nil(mpack_reader_t *reader, uint32_t *count)
Reads a nil node or the start of an array, returning whether an array was read and placing its number...
MPACK_INLINE uint32_t mpack_expect_map_max(mpack_reader_t *reader, uint32_t max_count)
Reads the start of a map with a number of elements at most max_count, returning its element count.
Definition: mpack.h:5964
void mpack_expect_str_match(mpack_reader_t *reader, const char *str, size_t length)
Reads a string, ensuring it exactly matches the given string.
uint32_t mpack_expect_map(mpack_reader_t *reader)
Reads the start of a map, returning its element count.
float mpack_expect_float(mpack_reader_t *reader)
Reads a number, returning the value as a float.
uint32_t mpack_expect_array_range(mpack_reader_t *reader, uint32_t min_count, uint32_t max_count)
Reads the start of an array with a number of elements in the given range, returning its element count...
float mpack_expect_float_strict(mpack_reader_t *reader)
Reads a float.
double mpack_expect_double(mpack_reader_t *reader)
Reads a number, returning the value as a double.
size_t mpack_expect_enum_optional(mpack_reader_t *reader, const char *strings[], size_t count)
Expects a string matching one of the strings in the given array returning its array index,...
MPACK_INLINE int mpack_expect_int_max(mpack_reader_t *reader, int max_value)
Reads an int, ensuring that it is at least zero and at most max_value.
Definition: mpack.h:5729
void mpack_expect_utf8_cstr(mpack_reader_t *reader, char *buf, size_t size)
Reads a string into the given buffer, ensures it is a valid UTF-8 string without NUL characters,...
double mpack_expect_double_range(mpack_reader_t *reader, double min_value, double max_value)
Reads a number, ensuring that it falls within the given range and returning the value as a double.
size_t mpack_expect_str_buf(mpack_reader_t *reader, char *buf, size_t bufsize)
Reads a string of at most the given size, writing it into the given buffer and returning its size in ...
size_t mpack_expect_enum(mpack_reader_t *reader, const char *strings[], size_t count)
Expects a string matching one of the strings in the given array, returning its array index.
MPACK_INLINE int16_t mpack_expect_i16_max(mpack_reader_t *reader, int16_t max_value)
Reads a 16-bit signed integer, ensuring that it is at least zero and at most max_value.
Definition: mpack.h:5691
MPACK_INLINE void mpack_expect_str_length(mpack_reader_t *reader, uint32_t count)
Reads the start of a string, raising an error if its length is not exactly the given number of bytes ...
Definition: mpack.h:6270
uint32_t mpack_expect_str(mpack_reader_t *reader)
Reads the start of a string, returning its size in bytes.
MPACK_INLINE int mpack_expect_int_range(mpack_reader_t *reader, int min_value, int max_value)
Reads a signed integer, ensuring that it falls within the given range.
Definition: mpack.h:5661
int16_t mpack_expect_i16_range(mpack_reader_t *reader, int16_t min_value, int16_t max_value)
Reads a 16-bit signed integer, ensuring that it falls within the given range.
void mpack_expect_tag(mpack_reader_t *reader, mpack_tag_t tag)
Reads a MessagePack object header (an MPack tag), expecting it to exactly match the given tag.
uint64_t mpack_expect_u64_range(mpack_reader_t *reader, uint64_t min_value, uint64_t max_value)
Reads a 64-bit unsigned integer, ensuring that it falls within the given range.
MPACK_INLINE int32_t mpack_expect_i32_max(mpack_reader_t *reader, int32_t max_value)
Reads a 32-bit signed integer, ensuring that it is at least zero and at most max_value.
Definition: mpack.h:5704
int8_t mpack_expect_i8(mpack_reader_t *reader)
Reads an 8-bit signed integer.
size_t mpack_expect_key_uint(mpack_reader_t *reader, bool found[], size_t count)
Expects an unsigned integer map key between 0 and count-1, marking it as found in the given bool arra...
void mpack_expect_array_match(mpack_reader_t *reader, uint32_t count)
Reads the start of an array of the exact size given.
MPACK_INLINE uint32_t mpack_expect_array_max(mpack_reader_t *reader, uint32_t max_count)
Reads the start of an array with a number of elements at most max_count, returning its element count.
Definition: mpack.h:6074
MPACK_INLINE uint32_t mpack_expect_str_max(mpack_reader_t *reader, uint32_t maxsize)
Reads the start of a string, raising an error if its length is not at most the given number of bytes ...
Definition: mpack.h:6250
int64_t mpack_expect_i64_range(mpack_reader_t *reader, int64_t min_value, int64_t max_value)
Reads a 64-bit signed integer, ensuring that it falls within the given range.
MPACK_INLINE uint32_t mpack_expect_bin_max(mpack_reader_t *reader, uint32_t maxsize)
Reads the start of a binary blob, raising an error if its length is not at most the given number of b...
Definition: mpack.h:6388
void mpack_expect_int_match(mpack_reader_t *reader, int64_t value)
Reads a signed integer, ensuring that it exactly matches the given value.
size_t mpack_expect_utf8(mpack_reader_t *reader, char *buf, size_t bufsize)
Reads a string into the given buffer, ensuring it is a valid UTF-8 string and returning its size in b...
void mpack_expect_cstr(mpack_reader_t *reader, char *buf, size_t size)
Reads a string into the given buffer, ensures it has no null bytes, and adds a null-terminator at the...
size_t mpack_expect_bin_buf(mpack_reader_t *reader, char *buf, size_t size)
Reads a binary blob into the given buffer, returning its size in bytes.
uint32_t mpack_expect_map_range(mpack_reader_t *reader, uint32_t min_count, uint32_t max_count)
Reads the start of a map with a number of elements in the given range, returning its element count.
int8_t mpack_expect_i8_range(mpack_reader_t *reader, int8_t min_value, int8_t max_value)
Reads an 8-bit signed integer, ensuring that it falls within the given range.
MPACK_INLINE int mpack_expect_int(mpack_reader_t *reader)
Reads a signed int.
Definition: mpack.h:5801
uint8_t mpack_expect_u8(mpack_reader_t *reader)
Reads an 8-bit unsigned integer.
uint64_t mpack_expect_u64(mpack_reader_t *reader)
Reads a 64-bit unsigned integer.
uint8_t mpack_expect_u8_range(mpack_reader_t *reader, uint8_t min_value, uint8_t max_value)
Reads an 8-bit unsigned integer, ensuring that it falls within the given range.
char * mpack_expect_utf8_cstr_alloc(mpack_reader_t *reader, size_t maxsize)
Reads a string with the given total maximum size (including space for a null-terminator),...
void mpack_expect_map_match(mpack_reader_t *reader, uint32_t count)
Reads the start of a map of the exact size given.
MPACK_INLINE unsigned int mpack_expect_uint(mpack_reader_t *reader)
Reads an unsigned int.
Definition: mpack.h:5782
MPACK_INLINE uint32_t mpack_expect_u32_max(mpack_reader_t *reader, uint32_t max_value)
Reads a 32-bit unsigned integer, ensuring that it is at most max_value.
Definition: mpack.h:5585
void mpack_expect_bin_size_buf(mpack_reader_t *reader, char *buf, uint32_t size)
Reads a binary blob with the exact given size into the given buffer.
char * mpack_expect_bin_alloc(mpack_reader_t *reader, size_t maxsize, size_t *size)
Reads a binary blob with the given total maximum size, allocating storage for it.
uint32_t mpack_expect_u32(mpack_reader_t *reader)
Reads a 32-bit unsigned integer.
uint16_t mpack_expect_u16(mpack_reader_t *reader)
Reads a 16-bit unsigned integer.
double mpack_expect_double_strict(mpack_reader_t *reader)
Reads a double.
uint16_t mpack_expect_u16_range(mpack_reader_t *reader, uint16_t min_value, uint16_t max_value)
Reads a 16-bit unsigned integer, ensuring that it falls within the given range.
int16_t mpack_expect_i16(mpack_reader_t *reader)
Reads a 16-bit signed integer.
int64_t mpack_expect_i64(mpack_reader_t *reader)
Reads a 64-bit signed integer.
size_t mpack_expect_key_cstr(mpack_reader_t *reader, const char *keys[], bool found[], size_t count)
Expects a string map key matching one of the strings in the given key list, marking it as found in th...
MPACK_INLINE void mpack_expect_bin_size(mpack_reader_t *reader, uint32_t count)
Reads the start of a binary blob, raising an error if its length is not exactly the given number of b...
Definition: mpack.h:6408
MPACK_INLINE unsigned int mpack_expect_uint_max(mpack_reader_t *reader, unsigned int max_value)
Reads an unsigned integer, ensuring that it is at most max_value.
Definition: mpack.h:5609
uint32_t mpack_expect_bin(mpack_reader_t *reader)
Reads the start of a binary blob, returning its size in bytes.
int32_t mpack_expect_i32(mpack_reader_t *reader)
Reads a 32-bit signed integer.
MPACK_INLINE uint64_t mpack_expect_u64_max(mpack_reader_t *reader, uint64_t max_value)
Reads a 64-bit unsigned integer, ensuring that it is at most max_value.
Definition: mpack.h:5597
MPACK_INLINE uint16_t mpack_expect_u16_max(mpack_reader_t *reader, uint16_t max_value)
Reads a 16-bit unsigned integer, ensuring that it is at most max_value.
Definition: mpack.h:5573
char * mpack_expect_cstr_alloc(mpack_reader_t *reader, size_t maxsize)
Reads a string with the given total maximum size (including space for a null-terminator),...
MPACK_INLINE void mpack_expect_cstr_match(mpack_reader_t *reader, const char *cstr)
Reads a string, ensuring it exactly matches the given null-terminated string.
Definition: mpack.h:6352
bool mpack_expect_map_or_nil(mpack_reader_t *reader, uint32_t *count)
Reads a nil node or the start of a map, returning whether a map was read and placing its number of ke...
MPACK_INLINE int64_t mpack_expect_i64_max(mpack_reader_t *reader, int64_t max_value)
Reads a 64-bit signed integer, ensuring that it is at least zero and at most max_value.
Definition: mpack.h:5717
int32_t mpack_node_i32(mpack_node_t node)
Returns the 32-bit signed value of the node.
size_t mpack_node_map_count(mpack_node_t node)
Returns the number of key/value pairs in the given map node.
void mpack_tree_init_filename(mpack_tree_t *tree, const char *filename, size_t max_bytes)
Initializes a tree to parse the given file.
struct mpack_node_t mpack_node_t
A handle to node data in a parsed MPack tree.
Definition: mpack.h:6808
bool mpack_node_is_nil(mpack_node_t node)
Returns true if the given node is a nil node; false otherwise.
mpack_node_t mpack_node_map_int_optional(mpack_node_t node, int64_t num)
Returns the value node in the given map for the given integer key, or a missing node if the map does ...
size_t mpack_node_copy_data(mpack_node_t node, char *buffer, size_t bufsize)
Copies the bytes contained by this node into the given buffer, returning the number of bytes in the n...
bool mpack_node_is_missing(mpack_node_t node)
Returns true if the given node handle indicates a missing node; false otherwise.
void(* mpack_tree_error_t)(mpack_tree_t *tree, mpack_error_t error)
An error handler function to be called when an error is flagged on the tree.
Definition: mpack.h:6853
bool mpack_node_map_contains_cstr(mpack_node_t node, const char *cstr)
Returns true if the given node map contains exactly one entry with the given null-terminated string k...
void(* mpack_tree_teardown_t)(mpack_tree_t *tree)
A teardown function to be called when the tree is destroyed.
Definition: mpack.h:6881
double mpack_node_double(mpack_node_t node)
Returns the double value of the node.
unsigned int mpack_node_uint(mpack_node_t node)
Returns the unsigned int value of the node.
char * mpack_node_cstr_alloc(mpack_node_t node, size_t maxsize)
Allocates a new null-terminated string using MPACK_MALLOC() with the string contained by this node.
float mpack_node_float_strict(mpack_node_t node)
Returns the float value of the node.
uint32_t mpack_node_data_len(mpack_node_t node)
Returns the length of the given str, bin or ext node.
mpack_node_t mpack_tree_root(mpack_tree_t *tree)
Returns the root node of the tree, if the tree is not in an error state.
MPACK_INLINE void mpack_tree_set_context(mpack_tree_t *tree, void *context)
Sets the custom pointer to pass to the tree callbacks, such as teardown.
Definition: mpack.h:7284
mpack_node_t mpack_node_map_cstr_optional(mpack_node_t node, const char *cstr)
Returns the value node in the given map for the given null-terminated string key, or a missing node i...
struct mpack_node_data_t mpack_node_data_t
The storage for nodes in an MPack tree.
Definition: mpack.h:6819
size_t mpack_node_enum(mpack_node_t node, const char *strings[], size_t count)
Searches the given string array for a string matching the given node and returns its index.
size_t mpack_node_copy_utf8(mpack_node_t node, char *buffer, size_t bufsize)
Checks that the given node contains a valid UTF-8 string and copies the string into the given buffer,...
void mpack_tree_init_pool(mpack_tree_t *tree, const char *data, size_t length, mpack_node_data_t *node_pool, size_t node_pool_count)
Initializes a tree parser with the given data, using the given node data pool to store the results.
uint64_t mpack_node_u64(mpack_node_t node)
Returns the 64-bit unsigned value of the node.
void mpack_tree_init_stream(mpack_tree_t *tree, mpack_tree_read_t read_fn, void *context, size_t max_message_size, size_t max_message_nodes)
Initializes a tree parser from an unbounded stream, or a stream of unknown length.
void mpack_node_nil(mpack_node_t node)
Checks that the given node is of nil type, raising mpack_error_type otherwise.
void mpack_node_flag_error(mpack_node_t node, mpack_error_t error)
Places the node's tree in the given error state, calling the error callback if one is set.
void mpack_tree_flag_error(mpack_tree_t *tree, mpack_error_t error)
Places the tree in the given error state, calling the error callback if one is set.
int8_t mpack_node_i8(mpack_node_t node)
Returns the 8-bit signed value of the node.
bool mpack_node_map_contains_str(mpack_node_t node, const char *str, size_t length)
Returns true if the given node map contains exactly one entry with the given string key.
MPACK_INLINE mpack_error_t mpack_tree_error(mpack_tree_t *tree)
Returns the error state of the tree.
Definition: mpack.h:7253
MPACK_INLINE void mpack_tree_init_file(mpack_tree_t *tree, const char *filename, size_t max_bytes)
Deprecated.
Definition: mpack.h:7145
float mpack_node_float(mpack_node_t node)
Returns the float value of the node.
mpack_node_t mpack_node_map_str_optional(mpack_node_t node, const char *str, size_t length)
Returns the value node in the given map for the given string key, or a missing node if the map does n...
mpack_node_t mpack_node_map_cstr(mpack_node_t node, const char *cstr)
Returns the value node in the given map for the given null-terminated string key.
double mpack_node_double_strict(mpack_node_t node)
Returns the double value of the node.
mpack_node_t mpack_node_map_key_at(mpack_node_t node, size_t index)
Returns the key node in the given map at the given index.
void mpack_tree_init_data(mpack_tree_t *tree, const char *data, size_t length)
Initializes a tree parser with the given data.
const char * mpack_node_str(mpack_node_t node)
Returns a pointer to the data contained by this node, ensuring the node is a string.
const char * mpack_node_data(mpack_node_t node)
Returns a pointer to the data contained by this node.
int mpack_node_int(mpack_node_t node)
Returns the int value of the node.
char * mpack_node_data_alloc(mpack_node_t node, size_t maxsize)
Allocates a new chunk of data using MPACK_MALLOC() with the bytes contained by this node.
void mpack_tree_init_stdfile(mpack_tree_t *tree, FILE *stdfile, size_t max_bytes, bool close_when_done)
Initializes a tree to parse the given libc FILE.
size_t mpack_node_array_length(mpack_node_t node)
Returns the length of the given array node.
MPACK_INLINE void * mpack_tree_context(mpack_tree_t *tree)
Returns the custom context for tree callbacks.
Definition: mpack.h:7294
mpack_node_t mpack_node_map_value_at(mpack_node_t node, size_t index)
Returns the value node in the given map at the given index.
void mpack_node_missing(mpack_node_t node)
Checks that the given node indicates a missing node, raising mpack_error_type otherwise.
MPACK_INLINE void mpack_tree_init(mpack_tree_t *tree, const char *data, size_t length)
Deprecated.
Definition: mpack.h:7070
MPACK_INLINE void mpack_tree_set_teardown(mpack_tree_t *tree, mpack_tree_teardown_t teardown)
Sets the teardown function to call when the tree is destroyed.
Definition: mpack.h:7324
void mpack_tree_parse(mpack_tree_t *tree)
Parses a MessagePack message into a tree of immutable nodes.
bool mpack_tree_try_parse(mpack_tree_t *tree)
Attempts to parse a MessagePack message from a non-blocking stream into a tree of immutable nodes.
uint32_t mpack_node_u32(mpack_node_t node)
Returns the 32-bit unsigned value of the node.
bool mpack_node_map_contains_uint(mpack_node_t node, uint64_t num)
Returns true if the given node map contains exactly one entry with the given unsigned integer key.
mpack_tag_t mpack_node_tag(mpack_node_t node)
Returns a tag describing the given node, or a nil tag if the tree is in an error state.
struct mpack_tree_t mpack_tree_t
An MPack tree parser to parse a blob or stream of MessagePack.
Definition: mpack.h:6827
mpack_node_t mpack_node_array_at(mpack_node_t node, size_t index)
Returns the node in the given array at the given index.
void mpack_node_check_utf8_cstr(mpack_node_t node)
Checks that the given node contains a valid UTF-8 string with no NUL bytes.
mpack_node_t mpack_node_map_uint_optional(mpack_node_t node, uint64_t num)
Returns the value node in the given map for the given unsigned integer key, or a missing node if the ...
mpack_node_t mpack_node_map_uint(mpack_node_t node, uint64_t num)
Returns the value node in the given map for the given unsigned integer key.
void mpack_node_true(mpack_node_t node)
Checks if the given node is of bool type with value true, raising mpack_error_type otherwise.
MPACK_INLINE size_t mpack_tree_size(mpack_tree_t *tree)
Returns the size in bytes of the current parsed message.
Definition: mpack.h:7267
void mpack_node_false(mpack_node_t node)
Checks if the given node is of bool type with value false, raising mpack_error_type otherwise.
mpack_error_t mpack_tree_destroy(mpack_tree_t *tree)
Destroys the tree.
mpack_type_t mpack_node_type(mpack_node_t node)
Returns the type of the node.
void mpack_node_check_utf8(mpack_node_t node)
Checks that the given node contains a valid UTF-8 string.
bool mpack_node_bool(mpack_node_t node)
Returns the bool value of the node.
MPACK_INLINE mpack_error_t mpack_node_error(mpack_node_t node)
Returns the error state of the node's tree.
Definition: mpack.h:7364
uint8_t mpack_node_u8(mpack_node_t node)
Returns the 8-bit unsigned value of the node.
MPACK_INLINE void mpack_tree_set_error_handler(mpack_tree_t *tree, mpack_tree_error_t error_fn)
Sets the error function to call when an error is flagged on the tree.
Definition: mpack.h:7311
void mpack_tree_init_error(mpack_tree_t *tree, mpack_error_t error)
Initializes an MPack tree directly into an error state.
mpack_node_t mpack_node_map_int(mpack_node_t node, int64_t num)
Returns the value node in the given map for the given integer key.
size_t mpack_node_enum_optional(mpack_node_t node, const char *strings[], size_t count)
Searches the given string array for a string matching the given node, returning its index or count if...
size_t mpack_node_bin_size(mpack_node_t node)
Returns the number of bytes in the given bin node.
uint16_t mpack_node_u16(mpack_node_t node)
Returns the 16-bit unsigned value of the node.
int64_t mpack_node_i64(mpack_node_t node)
Returns the 64-bit signed value of the node.
mpack_node_t mpack_node_map_str(mpack_node_t node, const char *str, size_t length)
Returns the value node in the given map for the given string key.
size_t mpack_node_strlen(mpack_node_t node)
Returns the length in bytes of the given string node.
char * mpack_node_utf8_cstr_alloc(mpack_node_t node, size_t maxsize)
Allocates a new null-terminated string using MPACK_MALLOC() with the UTF-8 string contained by this n...
void mpack_node_copy_cstr(mpack_node_t node, char *buffer, size_t size)
Checks that the given node contains a string with no NUL bytes, copies the string into the given buff...
const char * mpack_node_bin_data(mpack_node_t node)
Returns a pointer to the data contained by this bin node.
size_t(* mpack_tree_read_t)(mpack_tree_t *tree, char *buffer, size_t count)
The MPack tree's read function.
Definition: mpack.h:6876
bool mpack_node_map_contains_int(mpack_node_t node, int64_t num)
Returns true if the given node map contains exactly one entry with the given integer key.
void mpack_node_copy_utf8_cstr(mpack_node_t node, char *buffer, size_t size)
Checks that the given node contains a valid UTF-8 string with no NUL bytes, copies the string into th...
void mpack_tree_set_limits(mpack_tree_t *tree, size_t max_message_size, size_t max_message_nodes)
Sets the maximum byte size and maximum number of nodes allowed per message.
int16_t mpack_node_i16(mpack_node_t node)
Returns the 16-bit signed value of the node.
void mpack_writer_init_growable(mpack_writer_t *writer, char **data, size_t *size)
Initializes an MPack writer using a growable buffer.
MPACK_INLINE void mpack_reader_set_context(mpack_reader_t *reader, void *context)
Sets the custom pointer to pass to the reader callbacks, such as fill or teardown.
Definition: mpack.h:4620
void mpack_skip_bytes(mpack_reader_t *reader, size_t count)
Skips bytes from the underlying stream.
MPACK_INLINE void mpack_writer_init_file(mpack_writer_t *writer, const char *filename)
Deprecated.
Definition: mpack.h:3311
MPACK_INLINE mpack_error_t mpack_reader_flag_if_error(mpack_reader_t *reader, mpack_error_t error)
Places the reader in the given error state if the given error is not mpack_ok, returning the resultin...
Definition: mpack.h:4743
void mpack_reader_init_data(mpack_reader_t *reader, const char *data, size_t count)
Initializes an MPack reader to parse a pre-loaded contiguous chunk of data.
mpack_error_t mpack_writer_destroy(mpack_writer_t *writer)
Cleans up the MPack writer, flushing and closing the underlying stream, if any.
void mpack_reader_init(mpack_reader_t *reader, char *buffer, size_t size, size_t count)
Initializes an MPack reader with the given buffer.
size_t mpack_reader_remaining(mpack_reader_t *reader, const char **data)
Returns bytes left in the reader's buffer.
MPACK_INLINE void mpack_done_array(mpack_reader_t *reader)
Finishes reading an array.
Definition: mpack.h:5087
mpack_tag_t mpack_peek_tag(mpack_reader_t *reader)
Parses the next MessagePack object header (an MPack tag) without advancing the reader.
void mpack_discard(mpack_reader_t *reader)
Reads and discards the next object.
const char * mpack_read_bytes_inplace(mpack_reader_t *reader, size_t count)
Reads bytes from a string, binary blob or extension object in-place in the buffer.
MPACK_INLINE void mpack_reader_init_file(mpack_reader_t *reader, const char *filename)
Deprecated.
Definition: mpack.h:4543
void mpack_reader_flag_error(mpack_reader_t *reader, mpack_error_t error)
Places the reader in the given error state, calling the error callback if one is set.
void mpack_read_cstr(mpack_reader_t *reader, char *buf, size_t buffer_size, size_t byte_count)
Reads bytes from a string, ensures that the string contains no NUL bytes, copies the bytes into the g...
MPACK_INLINE void mpack_done_type(mpack_reader_t *reader, mpack_type_t type)
Definition: mpack.h:5076
void(* mpack_reader_skip_t)(mpack_reader_t *reader, size_t count)
The MPack reader's skip function.
Definition: mpack.h:4439
mpack_tag_t mpack_read_tag(mpack_reader_t *reader)
Reads a MessagePack object header (an MPack tag.)
void mpack_reader_init_error(mpack_reader_t *reader, mpack_error_t error)
Initializes an MPack reader directly into an error state.
const char * mpack_read_utf8_inplace(mpack_reader_t *reader, size_t count)
Reads bytes from a string in-place in the buffer and ensures they are valid UTF-8.
void(* mpack_reader_error_t)(mpack_reader_t *reader, mpack_error_t error)
An error handler function to be called when an error is flagged on the reader.
Definition: mpack.h:4465
MPACK_INLINE void * mpack_reader_context(mpack_reader_t *reader)
Returns the custom context for reader callbacks.
Definition: mpack.h:4631
MPACK_INLINE mpack_error_t mpack_reader_error(mpack_reader_t *reader)
Queries the error state of the MPack reader.
Definition: mpack.h:4717
void mpack_writer_init_filename(mpack_writer_t *writer, const char *filename)
Initializes an MPack writer that writes to a file.
MPACK_INLINE void mpack_done_map(mpack_reader_t *reader)
Finishes reading a map.
Definition: mpack.h:5098
MPACK_INLINE char * mpack_read_bytes_alloc(mpack_reader_t *reader, size_t count)
Reads bytes from a string, binary blob or extension object, allocating storage for them and returning...
Definition: mpack.h:4947
void mpack_reader_init_stdfile(mpack_reader_t *reader, FILE *stdfile, bool close_when_done)
Initializes an MPack reader that reads from a libc FILE.
size_t(* mpack_reader_fill_t)(mpack_reader_t *reader, char *buffer, size_t count)
The MPack reader's fill function.
Definition: mpack.h:4429
MPACK_INLINE void mpack_reader_set_error_handler(mpack_reader_t *reader, mpack_reader_error_t error_fn)
Sets the error function to call when an error is flagged on the reader.
Definition: mpack.h:4685
MPACK_INLINE void mpack_done_bin(mpack_reader_t *reader)
Finishes reading a binary data blob.
Definition: mpack.h:5120
void mpack_reader_set_skip(mpack_reader_t *reader, mpack_reader_skip_t skip)
Sets the skip function to discard bytes from the source stream.
MPACK_INLINE void mpack_done_str(mpack_reader_t *reader)
Finishes reading a string.
Definition: mpack.h:5109
void mpack_writer_init_error(mpack_writer_t *writer, mpack_error_t error)
Initializes an MPack writer directly into an error state.
void mpack_writer_init_stdfile(mpack_writer_t *writer, FILE *stdfile, bool close_when_done)
Initializes an MPack writer that writes to a libc FILE.
void mpack_writer_init(mpack_writer_t *writer, char *buffer, size_t size)
Initializes an MPack writer with the given buffer.
mpack_error_t mpack_reader_destroy(mpack_reader_t *reader)
Cleans up the MPack reader, ensuring that all compound elements have been completely read.
MPACK_INLINE bool mpack_should_read_bytes_inplace(mpack_reader_t *reader, size_t count)
Returns true if it's a good idea to read the given number of bytes in-place.
Definition: mpack.h:5034
void mpack_read_utf8_cstr(mpack_reader_t *reader, char *buf, size_t buffer_size, size_t byte_count)
Reads bytes from a string, ensures that the string is valid UTF-8 with no NUL bytes,...
void(* mpack_reader_teardown_t)(mpack_reader_t *reader)
A teardown function to be called when the reader is destroyed.
Definition: mpack.h:4470
void mpack_reader_init_filename(mpack_reader_t *reader, const char *filename)
Initializes an MPack reader that reads from a file.
void mpack_read_bytes(mpack_reader_t *reader, char *p, size_t count)
Reads bytes from a string, binary blob or extension object, copying them into the given buffer.
struct mpack_reader_t mpack_reader_t
A buffered MessagePack decoder.
Definition: mpack.h:4410
void mpack_read_utf8(mpack_reader_t *reader, char *p, size_t byte_count)
Reads bytes from a string, ensures that the string is valid UTF-8, and copies the bytes into the give...
MPACK_INLINE void mpack_reader_set_teardown(mpack_reader_t *reader, mpack_reader_teardown_t teardown)
Sets the teardown function to call when the reader is destroyed.
Definition: mpack.h:4698
void mpack_reader_set_fill(mpack_reader_t *reader, mpack_reader_fill_t fill)
Sets the fill function to refill the data buffer when it runs out of data.
void mpack_writer_flush_message(mpack_writer_t *writer)
Flushes any buffered data to the underlying stream.
void mpack_start_str(mpack_writer_t *writer, uint32_t count)
Opens a string.
void mpack_complete_map(struct mpack_writer_t *writer)
Completes a map being built.
void mpack_writer_set_flush(mpack_writer_t *writer, mpack_writer_flush_t flush)
Sets the flush function to write out the data when the buffer is full.
void mpack_write_tag(mpack_writer_t *writer, mpack_tag_t tag)
Writes a MessagePack object header (an MPack Tag.)
MPACK_INLINE void mpack_finish_array(mpack_writer_t *writer)
Finishes writing an array.
Definition: mpack.h:3766
MPACK_INLINE void * mpack_writer_context(mpack_writer_t *writer)
Returns the custom context for writer callbacks.
Definition: mpack.h:3424
MPACK_INLINE mpack_error_t mpack_writer_error(mpack_writer_t *writer)
Queries the error state of the MPack writer.
Definition: mpack.h:3552
MPACK_INLINE void mpack_writer_set_teardown(mpack_writer_t *writer, mpack_writer_teardown_t teardown)
Sets the teardown function to call when the writer is destroyed.
Definition: mpack.h:3470
void mpack_write_float(mpack_writer_t *writer, float value)
Writes a float.
void mpack_write_double(mpack_writer_t *writer, double value)
Writes a double.
void mpack_write_utf8_cstr_or_nil(mpack_writer_t *writer, const char *cstr)
Writes a null-terminated string ensuring that it is valid UTF-8, or writes nil if the given cstr poin...
void mpack_write_bin(mpack_writer_t *writer, const char *data, uint32_t count)
Writes a binary blob.
void mpack_write_i32(mpack_writer_t *writer, int32_t value)
Writes a 32-bit integer in the most efficient packing available.
void mpack_write_cstr(mpack_writer_t *writer, const char *cstr)
Writes a null-terminated string.
MPACK_INLINE void mpack_write_int(mpack_writer_t *writer, int64_t value)
Writes an integer in the most efficient packing available.
Definition: mpack.h:3596
void mpack_start_array(mpack_writer_t *writer, uint32_t count)
Opens an array.
MPACK_INLINE void mpack_finish_map(mpack_writer_t *writer)
Finishes writing a map.
Definition: mpack.h:3782
void mpack_write_u64(mpack_writer_t *writer, uint64_t value)
Writes an 64-bit unsigned integer in the most efficient packing available.
void mpack_write_i8(mpack_writer_t *writer, int8_t value)
Writes an 8-bit integer in the most efficient packing available.
MPACK_INLINE void mpack_write_uint(mpack_writer_t *writer, uint64_t value)
Writes an unsigned integer in the most efficient packing available.
Definition: mpack.h:3613
void mpack_write_utf8(mpack_writer_t *writer, const char *str, uint32_t length)
Writes a string, ensuring that it is valid UTF-8.
MPACK_INLINE size_t mpack_writer_buffer_size(mpack_writer_t *writer)
Returns the (current) size of the buffer.
Definition: mpack.h:3524
void mpack_write_u8(mpack_writer_t *writer, uint8_t value)
Writes an 8-bit unsigned integer in the most efficient packing available.
void mpack_build_map(struct mpack_writer_t *writer)
Starts building a map.
void mpack_start_map(mpack_writer_t *writer, uint32_t count)
Opens a map.
void mpack_write_utf8_cstr(mpack_writer_t *writer, const char *cstr)
Writes a null-terminated string, ensuring that it is valid UTF-8.
void mpack_write_bool(mpack_writer_t *writer, bool value)
Writes a boolean.
void mpack_write_true(mpack_writer_t *writer)
Writes a boolean with value true.
void mpack_build_array(struct mpack_writer_t *writer)
Starts building an array.
void(* mpack_writer_error_t)(mpack_writer_t *writer, mpack_error_t error)
An error handler function to be called when an error is flagged on the writer.
Definition: mpack.h:3125
void mpack_complete_array(struct mpack_writer_t *writer)
Completes an array being built.
void mpack_write_cstr_or_nil(mpack_writer_t *writer, const char *cstr)
Writes a null-terminated string, or a nil node if the given cstr pointer is NULL.
void mpack_write_u32(mpack_writer_t *writer, uint32_t value)
Writes an 32-bit unsigned integer in the most efficient packing available.
void mpack_write_object_bytes(mpack_writer_t *writer, const char *data, size_t bytes)
Write a pre-encoded messagepack object.
void mpack_write_bytes(mpack_writer_t *writer, const char *data, size_t count)
Writes a portion of bytes for a string, binary blob or extension type which was opened by mpack_write...
MPACK_INLINE void mpack_builder_compound_push(mpack_writer_t *writer)
Definition: mpack.h:3732
MPACK_INLINE void mpack_finish_type(mpack_writer_t *writer, mpack_type_t type)
Finishes writing the given compound type.
Definition: mpack.h:4106
void(* mpack_writer_teardown_t)(mpack_writer_t *writer)
A teardown function to be called when the writer is destroyed.
Definition: mpack.h:3130
void mpack_start_bin(mpack_writer_t *writer, uint32_t count)
Opens a binary blob.
MPACK_INLINE void mpack_builder_compound_pop(mpack_writer_t *writer)
Definition: mpack.h:3743
void mpack_expect_false(mpack_reader_t *reader)
Reads a boolean, raising mpack_error_type if its value is not false.
MPACK_INLINE size_t mpack_writer_buffer_left(mpack_writer_t *writer)
Returns the amount of space left in the buffer.
Definition: mpack.h:3516
void mpack_expect_true(mpack_reader_t *reader)
Reads a boolean, raising mpack_error_type if its value is not true.
void mpack_write_false(mpack_writer_t *writer)
Writes a boolean with value false.
MPACK_INLINE void mpack_writer_set_error_handler(mpack_writer_t *writer, mpack_writer_error_t error_fn)
Sets the error function to call when an error is flagged on the writer.
Definition: mpack.h:3457
void mpack_write_i64(mpack_writer_t *writer, int64_t value)
Writes a 64-bit integer in the most efficient packing available.
struct mpack_writer_t mpack_writer_t
A buffered MessagePack encoder.
Definition: mpack.h:3090
void mpack_write_str(mpack_writer_t *writer, const char *str, uint32_t length)
Writes a string.
void mpack_write_i16(mpack_writer_t *writer, int16_t value)
Writes a 16-bit integer in the most efficient packing available.
void mpack_write_u16(mpack_writer_t *writer, uint16_t value)
Writes an 16-bit unsigned integer in the most efficient packing available.
MPACK_INLINE size_t mpack_writer_buffer_used(mpack_writer_t *writer)
Returns the number of bytes currently stored in the buffer.
Definition: mpack.h:3508
void(* mpack_writer_flush_t)(mpack_writer_t *writer, const char *buffer, size_t count)
The MPack writer's flush function to flush the buffer to the output stream.
Definition: mpack.h:3099
void mpack_expect_nil(mpack_reader_t *reader)
Reads a nil, raising mpack_error_type if the value is not nil.
void mpack_write_nil(mpack_writer_t *writer)
Writes a nil.
bool mpack_expect_bool(mpack_reader_t *reader)
Reads a boolean.
MPACK_INLINE void mpack_finish_str(mpack_writer_t *writer)
Finishes writing a string.
Definition: mpack.h:4059
MPACK_INLINE void mpack_finish_bin(mpack_writer_t *writer)
Finishes writing a binary blob.
Definition: mpack.h:4074
void mpack_writer_flag_error(mpack_writer_t *writer, mpack_error_t error)
Places the writer in the given error state, calling the error callback if one is set.
MPACK_INLINE void mpack_writer_set_context(mpack_writer_t *writer, void *context)
Sets the custom pointer to pass to the writer callbacks, such as flush or teardown.
Definition: mpack.h:3414
void print(wpi::raw_ostream &os, const S &format_str, Args &&... args)
Prints formatted data to the stream os.
Definition: raw_ostream.h:25
#define MPACK_READER_SMALL_FRACTION_DENOMINATOR
Definition: mpack.h:4369
constexpr auto max_value() -> T
Definition: format.h:489
@ value
the parser finished reading a JSON value
FMT_NOINLINE FMT_CONSTEXPR auto fill(OutputIt it, size_t n, const fill_t< Char > &fill) -> OutputIt
Definition: format.h:1779
@ error
throw a parse_error exception in case of a tag
constexpr auto count() -> size_t
Definition: core.h:1203
state
Definition: core.h:2271
type
Definition: core.h:556
Definition: MessagePack.h:15
MPACK_INLINE void mpack_write(mpack_writer_t *writer, int8_t value)
Definition: mpack.h:4210
MPACK_INLINE void mpack_write_kv(mpack_writer_t *writer, const char *key, int8_t value)
Definition: mpack.h:4264
static constexpr const velocity::meters_per_second_t c(299792458.0)
Speed of light in vacuum.
b
Definition: data.h:44
value_type read(const void *memory, endianness endian)
Read a value of a particular endianness from memory.
Definition: Endian.h:65
auto printf(string_view fmt, const T &... args) -> int
\rst Prints formatted data to stdout.
Definition: printf.h:655
auto format(wformat_string< T... > fmt, T &&... args) -> std::wstring
Definition: xchar.h:108