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