#pragma once #ifndef RYML_SINGLE_HEADER_AMALGAMATED_HPP_ #define RYML_SINGLE_HEADER_AMALGAMATED_HPP_ // // Rapid YAML - a library to parse and emit YAML, and do it fast. // // https://github.com/biojppm/rapidyaml // // DO NOT EDIT. This file is generated automatically. // // // This is an amalgamated single-header version of the library. // // INSTRUCTIONS: // // - Copy this file to you project. // // - Include at will in any header of your project. Because the // amalgamated header file is large, to speed up compilation of // your project, protect the include with its include guard // `RYML_SINGLE_HEADER_AMALGAMATED_HPP_`, ie like this: // ``` // #ifndef RYML_SINGLE_HEADER_AMALGAMATED_HPP_ // #include // #endif // ``` // // - In one -- and only one -- of your project source files, #define // RYML_SINGLE_HDR_DEFINE_NOW and then include this header before any // other include. This will enable the function and class definitions // in the header file. // // - To compile into a shared library, define the preprocessor symbol // RYML_SHARED before including the header. This will take care of // symbol export/import. // //******************************************************************************** //-------------------------------------------------------------------------------- // LICENSE.txt //-------------------------------------------------------------------------------- //******************************************************************************** // Copyright (c) 2018, Joao Paulo Magalhaes // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // // shared library: export when defining #if defined(RYML_SHARED) && defined(RYML_SINGLE_HDR_DEFINE_NOW) && !defined(RYML_EXPORTS) #define RYML_EXPORTS #endif // propagate defines to c4core #if defined(RYML_SINGLE_HDR_DEFINE_NOW) && !defined(C4CORE_SINGLE_HDR_DEFINE_NOW) #define C4CORE_SINGLE_HDR_DEFINE_NOW #endif #if defined(RYML_SHARED) && !defined(C4CORE_SHARED) #define C4CORE_SHARED #endif #if defined(RYML_EXPORTS) && !defined(C4CORE_EXPORTS) #define C4CORE_EXPORTS #endif //----------------------------------------------------------------------------- // (amalgamate) workarounds for include removal // missing in arm-none-eabi-g++ // https://github.com/biojppm/rapidyaml/issues/193 #include // conditional includes in the gcc4.8 shim #include #include #include // conditional includes in charconv.hpp #if (defined(_MSVC_LANG) && (_MSVC_LANG >= 201703L)) || (__cplusplus >= 201703L) #include #endif //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/export.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_EXPORT_HPP_ #define C4_EXPORT_HPP_ #ifdef _WIN32 #ifdef C4CORE_SHARED #ifdef C4CORE_EXPORTS #define C4CORE_EXPORT __declspec(dllexport) #define C4CORE_EXPORT_EXTERN #else #define C4CORE_EXPORT __declspec(dllimport) #define C4CORE_EXPORT_EXTERN extern #endif #else #define C4CORE_EXPORT #define C4CORE_EXPORT_EXTERN #endif #else #define C4CORE_EXPORT #define C4CORE_EXPORT_EXTERN #endif #endif /* C4CORE_EXPORT_HPP_ */ // (end ext/c4core.src/c4/export.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/version.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_VERSION_HPP_ #define C4_VERSION_HPP_ /** @file version.hpp */ #define C4CORE_VERSION "0.6.0" #define C4CORE_VERSION_MAJOR 0 #define C4CORE_VERSION_MINOR 6 #define C4CORE_VERSION_PATCH 0 #ifndef C4_EXPORT_HPP_ //#include // amalgamate: remove include #error "amalgamate: c4/export.hpp must have been amalgamated before this point" #endif /* C4_EXPORT_HPP_ */ namespace c4 { C4CORE_EXPORT const char* version(); C4CORE_EXPORT int version_major(); C4CORE_EXPORT int version_minor(); C4CORE_EXPORT int version_patch(); } // namespace c4 #endif /* C4_VERSION_HPP_ */ // (end ext/c4core.src/c4/version.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/preprocessor.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_PREPROCESSOR_HPP_ #define C4_PREPROCESSOR_HPP_ /** @file preprocessor.hpp Contains basic macros and preprocessor utilities. * @ingroup basic_headers */ #ifdef __clang__ /* NOTE: using , ## __VA_ARGS__ to deal with zero-args calls to * variadic macros is not portable, but works in clang, gcc, msvc, icc. * clang requires switching off compiler warnings for pedantic mode. * @see http://stackoverflow.com/questions/32047685/variadic-macro-without-arguments */ # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments" // warning: token pasting of ',' and __VA_ARGS__ is a GNU extension #elif defined(__GNUC__) /* GCC also issues a warning for zero-args calls to variadic macros. * This warning is switched on with -pedantic and apparently there is no * easy way to turn it off as with clang. But marking this as a system * header works. * @see https://gcc.gnu.org/onlinedocs/cpp/System-Headers.html * @see http://stackoverflow.com/questions/35587137/ */ # pragma GCC system_header #endif #define C4_WIDEN(str) L"" str #define C4_COUNTOF(arr) (sizeof(arr)/sizeof((arr)[0])) #define C4_EXPAND(arg) arg /** useful in some macro calls with template arguments */ #define C4_COMMA , /** useful in some macro calls with template arguments * @see C4_COMMA */ #define C4_COMMA_X C4_COMMA /** expand and quote */ #define C4_XQUOTE(arg) C4_XQUOTE_(arg) #define C4_XQUOTE_(arg) C4_QUOTE(arg) #define C4_QUOTE(arg) #arg /** expand and concatenate */ #define C4_XCAT(arg1, arg2) C4_XCAT_(arg1, arg2) #define C4_XCAT_(arg1, arg2) C4_CAT(arg1, arg2) #define C4_CAT(arg1, arg2) arg1##arg2 #define C4_VERSION_CAT(major, minor, patch) ((major)*10000 + (minor)*100 + (patch)) /** A preprocessor foreach. Spectacular trick taken from: * http://stackoverflow.com/a/1872506/5875572 * The first argument is for a macro receiving a single argument, * which will be called with every subsequent argument. There is * currently a limit of 32 arguments, and at least 1 must be provided. * Example: @code{.cpp} struct Example { int a; int b; int c; }; // define a one-arg macro to be called #define PRN_STRUCT_OFFSETS(field) PRN_STRUCT_OFFSETS_(Example, field) #define PRN_STRUCT_OFFSETS_(structure, field) printf(C4_XQUOTE(structure) ":" C4_XQUOTE(field)" - offset=%zu\n", offsetof(structure, field)); // now call the macro for a, b and c C4_FOR_EACH(PRN_STRUCT_OFFSETS, a, b, c); @endcode */ #define C4_FOR_EACH(what, ...) C4_FOR_EACH_SEP(what, ;, __VA_ARGS__) /** same as C4_FOR_EACH(), but use a custom separator between statements. * If a comma is needed as the separator, use the C4_COMMA macro. * @see C4_FOR_EACH * @see C4_COMMA */ #define C4_FOR_EACH_SEP(what, sep, ...) C4_FOR_EACH_(C4_FOR_EACH_NARG(__VA_ARGS__), what, sep, __VA_ARGS__) /// @cond dev #define C4_FOR_EACH_01(what, sep, x) what(x) sep #define C4_FOR_EACH_02(what, sep, x, ...) what(x) sep C4_FOR_EACH_01(what, sep, __VA_ARGS__) #define C4_FOR_EACH_03(what, sep, x, ...) what(x) sep C4_FOR_EACH_02(what, sep, __VA_ARGS__) #define C4_FOR_EACH_04(what, sep, x, ...) what(x) sep C4_FOR_EACH_03(what, sep, __VA_ARGS__) #define C4_FOR_EACH_05(what, sep, x, ...) what(x) sep C4_FOR_EACH_04(what, sep, __VA_ARGS__) #define C4_FOR_EACH_06(what, sep, x, ...) what(x) sep C4_FOR_EACH_05(what, sep, __VA_ARGS__) #define C4_FOR_EACH_07(what, sep, x, ...) what(x) sep C4_FOR_EACH_06(what, sep, __VA_ARGS__) #define C4_FOR_EACH_08(what, sep, x, ...) what(x) sep C4_FOR_EACH_07(what, sep, __VA_ARGS__) #define C4_FOR_EACH_09(what, sep, x, ...) what(x) sep C4_FOR_EACH_08(what, sep, __VA_ARGS__) #define C4_FOR_EACH_10(what, sep, x, ...) what(x) sep C4_FOR_EACH_09(what, sep, __VA_ARGS__) #define C4_FOR_EACH_11(what, sep, x, ...) what(x) sep C4_FOR_EACH_10(what, sep, __VA_ARGS__) #define C4_FOR_EACH_12(what, sep, x, ...) what(x) sep C4_FOR_EACH_11(what, sep, __VA_ARGS__) #define C4_FOR_EACH_13(what, sep, x, ...) what(x) sep C4_FOR_EACH_12(what, sep, __VA_ARGS__) #define C4_FOR_EACH_14(what, sep, x, ...) what(x) sep C4_FOR_EACH_13(what, sep, __VA_ARGS__) #define C4_FOR_EACH_15(what, sep, x, ...) what(x) sep C4_FOR_EACH_14(what, sep, __VA_ARGS__) #define C4_FOR_EACH_16(what, sep, x, ...) what(x) sep C4_FOR_EACH_15(what, sep, __VA_ARGS__) #define C4_FOR_EACH_17(what, sep, x, ...) what(x) sep C4_FOR_EACH_16(what, sep, __VA_ARGS__) #define C4_FOR_EACH_18(what, sep, x, ...) what(x) sep C4_FOR_EACH_17(what, sep, __VA_ARGS__) #define C4_FOR_EACH_19(what, sep, x, ...) what(x) sep C4_FOR_EACH_18(what, sep, __VA_ARGS__) #define C4_FOR_EACH_20(what, sep, x, ...) what(x) sep C4_FOR_EACH_19(what, sep, __VA_ARGS__) #define C4_FOR_EACH_21(what, sep, x, ...) what(x) sep C4_FOR_EACH_20(what, sep, __VA_ARGS__) #define C4_FOR_EACH_22(what, sep, x, ...) what(x) sep C4_FOR_EACH_21(what, sep, __VA_ARGS__) #define C4_FOR_EACH_23(what, sep, x, ...) what(x) sep C4_FOR_EACH_22(what, sep, __VA_ARGS__) #define C4_FOR_EACH_24(what, sep, x, ...) what(x) sep C4_FOR_EACH_23(what, sep, __VA_ARGS__) #define C4_FOR_EACH_25(what, sep, x, ...) what(x) sep C4_FOR_EACH_24(what, sep, __VA_ARGS__) #define C4_FOR_EACH_26(what, sep, x, ...) what(x) sep C4_FOR_EACH_25(what, sep, __VA_ARGS__) #define C4_FOR_EACH_27(what, sep, x, ...) what(x) sep C4_FOR_EACH_26(what, sep, __VA_ARGS__) #define C4_FOR_EACH_28(what, sep, x, ...) what(x) sep C4_FOR_EACH_27(what, sep, __VA_ARGS__) #define C4_FOR_EACH_29(what, sep, x, ...) what(x) sep C4_FOR_EACH_28(what, sep, __VA_ARGS__) #define C4_FOR_EACH_30(what, sep, x, ...) what(x) sep C4_FOR_EACH_29(what, sep, __VA_ARGS__) #define C4_FOR_EACH_31(what, sep, x, ...) what(x) sep C4_FOR_EACH_30(what, sep, __VA_ARGS__) #define C4_FOR_EACH_32(what, sep, x, ...) what(x) sep C4_FOR_EACH_31(what, sep, __VA_ARGS__) #define C4_FOR_EACH_NARG(...) C4_FOR_EACH_NARG_(__VA_ARGS__, C4_FOR_EACH_RSEQ_N()) #define C4_FOR_EACH_NARG_(...) C4_FOR_EACH_ARG_N(__VA_ARGS__) #define C4_FOR_EACH_ARG_N(_01, _02, _03, _04, _05, _06, _07, _08, _09, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, N, ...) N #define C4_FOR_EACH_RSEQ_N() 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 09, 08, 07, 06, 05, 04, 03, 02, 01 #define C4_FOR_EACH_(N, what, sep, ...) C4_XCAT(C4_FOR_EACH_, N)(what, sep, __VA_ARGS__) /// @endcond #ifdef __clang__ # pragma clang diagnostic pop #endif #endif /* C4_PREPROCESSOR_HPP_ */ // (end ext/c4core.src/c4/preprocessor.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/platform.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_PLATFORM_HPP_ #define C4_PLATFORM_HPP_ /** @file platform.hpp Provides platform information macros * @ingroup basic_headers */ // see also https://sourceforge.net/p/predef/wiki/OperatingSystems/ #if defined(_WIN64) # define C4_WIN # define C4_WIN64 #elif defined(_WIN32) # define C4_WIN # define C4_WIN32 #elif defined(__ANDROID__) # define C4_ANDROID #elif defined(__APPLE__) # include "TargetConditionals.h" # if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR # define C4_IOS # elif TARGET_OS_MAC || TARGET_OS_OSX # define C4_MACOS # else # error "Unknown Apple platform" # endif #elif defined(__linux__) || defined(__linux) # define C4_UNIX # define C4_LINUX #elif defined(__unix__) || defined(__unix) # define C4_UNIX #elif defined(__arm__) || defined(__aarch64__) # define C4_ARM #elif defined(__xtensa__) || defined(__XTENSA__) # define C4_XTENSA #elif defined(SWIG) # define C4_SWIG #else # error "unknown platform" #endif #if defined(__posix) || defined(C4_UNIX) || defined(C4_LINUX) # define C4_POSIX #endif #endif /* C4_PLATFORM_HPP_ */ // (end ext/c4core.src/c4/platform.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/cpu.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_CPU_HPP_ #define C4_CPU_HPP_ /** @file cpu.hpp Provides processor information macros * @ingroup basic_headers */ // see also https://sourceforge.net/p/predef/wiki/Architectures/ // see also https://sourceforge.net/p/predef/wiki/Endianness/ // see also https://github.com/googlesamples/android-ndk/blob/android-mk/hello-jni/jni/hello-jni.c // see also http://code.qt.io/cgit/qt/qtbase.git/tree/src/corelib/global/qprocessordetection.h #ifdef __ORDER_LITTLE_ENDIAN__ # define C4EL_ __ORDER_LITTLE_ENDIAN__ #else # define C4EL_ 1234 #endif #ifdef __ORDER_BIG_ENDIAN__ # define C4EB_ __ORDER_BIG_ENDIAN__ #else # define C4EB_ 4321 #endif // mixed byte order (eg, PowerPC or ia64) #define C4EM_ 1111 // NOLINT // NOTE: to find defined macros in a platform, // g++ -dM -E - = 8) \ || (defined(__TARGET_ARCH_ARM) && __TARGET_ARCH_ARM >= 8) # define C4_CPU_ARMV8 # elif defined(__ARM_ARCH_7__) || defined(_ARM_ARCH_7) \ || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) \ || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__) \ || defined(__ARM_ARCH_7EM__) \ || (defined(__TARGET_ARCH_ARM) && __TARGET_ARCH_ARM >= 7) \ || (defined(_M_ARM) && _M_ARM >= 7) # define C4_CPU_ARMV7 # elif defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) \ || defined(__ARM_ARCH_6T2__) || defined(__ARM_ARCH_6Z__) \ || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6ZK__) \ || defined(__ARM_ARCH_6M__) || defined(__ARM_ARCH_6KZ__) \ || (defined(__TARGET_ARCH_ARM) && __TARGET_ARCH_ARM >= 6) # define C4_CPU_ARMV6 # elif (defined(__ARM_ARCH) && __ARM_ARCH == 5) \ || defined(__ARM_ARCH_5TEJ__) \ || defined(__ARM_ARCH_5TE__) \ || defined(__ARM_ARCH_5T__) \ || (defined(__TARGET_ARCH_ARM) && __TARGET_ARCH_ARM >= 5) # define C4_CPU_ARMV5 # elif (defined(__ARM_ARCH) && __ARM_ARCH == 4) \ || defined(__ARM_ARCH_4T__) \ || defined(__ARM_ARCH_4__) \ || (defined(__TARGET_ARCH_ARM) && __TARGET_ARCH_ARM >= 4) # define C4_CPU_ARMV4 # else # error "unknown CPU architecture: ARM" # endif # endif # if defined(__ARMEL__) || defined(__LITTLE_ENDIAN__) || defined(__AARCH64EL__) \ || (defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) \ || defined(_MSC_VER) // winarm64 does not provide any of the above macros, // but advises little-endianess: // https://docs.microsoft.com/en-us/cpp/build/overview-of-arm-abi-conventions?view=msvc-170 // So if it is visual studio compiling, we'll assume little endian. # define C4_BYTE_ORDER C4EL_ # elif defined(__ARMEB__) || defined(__BIG_ENDIAN__) || defined(__AARCH64EB__) \ || (defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)) # define C4_BYTE_ORDER C4EB_ # elif defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_PDP_ENDIAN__) # define C4_BYTE_ORDER C4EM_ # else # error "unknown endianness" # endif #elif defined(__ia64) || defined(__ia64__) || defined(_M_IA64) # define C4_CPU_IA64 # define C4_WORDSIZE 8 # define C4_BYTE_ORDER C4EM_ // itanium is bi-endian - check byte order below #elif defined(__ppc__) || defined(__ppc) || defined(__powerpc__) \ || defined(_ARCH_COM) || defined(_ARCH_PWR) || defined(_ARCH_PPC) \ || defined(_M_MPPC) || defined(_M_PPC) # if defined(__ppc64__) || defined(__powerpc64__) || defined(__64BIT__) # define C4_CPU_PPC64 # define C4_WORDSIZE 8 # else # define C4_CPU_PPC # define C4_WORDSIZE 4 # endif # define C4_BYTE_ORDER C4EM_ #elif defined(__s390x__) || defined(__zarch__) || defined(__SYSC_ZARCH_) # define C4_CPU_S390_X # define C4_WORDSIZE 8 # define C4_BYTE_ORDER C4EB_ #elif defined(__xtensa__) || defined(__XTENSA__) # define C4_CPU_XTENSA # define C4_WORDSIZE 4 // not sure about this... # if defined(__XTENSA_EL__) || defined(__xtensa_el__) # define C4_BYTE_ORDER C4EL_ # else # define C4_BYTE_ORDER C4EB_ # endif #elif defined(__riscv) # if __riscv_xlen == 64 # define C4_CPU_RISCV64 # define C4_WORDSIZE 8 # else # define C4_CPU_RISCV32 # define C4_WORDSIZE 4 # endif # define C4_BYTE_ORDER C4EL_ #elif defined(__EMSCRIPTEN__) # define C4_BYTE_ORDER C4EL_ # define C4_WORDSIZE 4 #elif defined(__loongarch__) # if defined(__loongarch64) # define C4_CPU_LOONGARCH64 # define C4_WORDSIZE 8 # else # define C4_CPU_LOONGARCH # define C4_WORDSIZE 4 # endif # define C4_BYTE_ORDER C4EL_ #elif defined(__mips__) || defined(_mips) || defined(mips) # if defined(__mips) # if __mips == 64 # define C4_CPU_MIPS64 # define C4_WORDSIZE 8 # elif __mips == 32 # define C4_CPU_MIPS32 # define C4_WORDSIZE 4 # endif # elif defined(__arch64__) || (defined(__SIZE_WIDTH__) && __SIZE_WIDTH__ == 64) || (defined(__LP64__) && __LP64__) # define C4_CPU_MIPS64 # define C4_WORDSIZE 8 # elif defined(__arch32__) || (defined(__SIZE_WIDTH__) && __SIZE_WIDTH__ == 32) || (defined(__LP32__) && __LP32__) # define C4_CPU_MIPS32 # define C4_WORDSIZE 4 # else # error "unknown mips architecture" # endif # if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ # define C4_BYTE_ORDER C4EB_ # elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ # define C4_BYTE_ORDER C4EL_ # else # error "unknown mips endianness" # endif #elif defined(__sparc__) || defined(__sparc) || defined(sparc) # if defined(__arch64__) || (defined(__SIZE_WIDTH__) && __SIZE_WIDTH__ == 64) || (defined(__LP64__) && __LP64__) # define C4_CPU_SPARC64 # define C4_WORDSIZE 8 # elif defined(__arch32__) || (defined(__SIZE_WIDTH__) && __SIZE_WIDTH__ == 32) || (defined(__LP32__) && __LP32__) # define C4_CPU_SPARC32 # define C4_WORDSIZE 4 # else # error "unknown sparc architecture" # endif # define C4_BYTE_ORDER C4EB_ #elif defined(SWIG) # error "please define CPU architecture macros when compiling with swig" #else # error "unknown CPU architecture" #endif #define C4_LITTLE_ENDIAN (C4_BYTE_ORDER == C4EL_) #define C4_BIG_ENDIAN (C4_BYTE_ORDER == C4EB_) #define C4_MIXED_ENDIAN (C4_BYTE_ORDER == C4EM_) #endif /* C4_CPU_HPP_ */ // (end ext/c4core.src/c4/cpu.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/gcc-4.8.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_GCC_4_8_HPP_ #define C4_GCC_4_8_HPP_ #if __GNUC__ == 4 && __GNUC_MINOR__ >= 8 /* STL polyfills for old GNU compilers */ _Pragma("GCC diagnostic ignored \"-Wshadow\"") _Pragma("GCC diagnostic ignored \"-Wmissing-field-initializers\"") #if __cplusplus //#include // amalgamate: included above //#include // amalgamate: included above namespace std { template struct is_trivially_copyable : public integral_constant::value && __has_trivial_destructor(_Tp) && (__has_trivial_constructor(_Tp) || __has_trivial_copy(_Tp) || __has_trivial_assign(_Tp))> { }; template using is_trivially_copy_constructible = has_trivial_copy_constructor<_Tp>; template using is_trivially_default_constructible = has_trivial_default_constructor<_Tp>; template using is_trivially_copy_assignable = has_trivial_copy_assign<_Tp>; /* not supported */ template struct is_trivially_move_constructible : false_type { }; /* not supported */ template struct is_trivially_move_assignable : false_type { }; inline void *align(size_t __align, size_t __size, void*& __ptr, size_t& __space) noexcept { if (__space < __size) return nullptr; const auto __intptr = reinterpret_cast(__ptr); const auto __aligned = (__intptr - 1u + __align) & -__align; const auto __diff = __aligned - __intptr; if (__diff > (__space - __size)) return nullptr; else { __space -= __diff; return __ptr = reinterpret_cast(__aligned); } } #if __GNUC__ == 4 && __GNUC_MINOR__ == 8 typedef long double max_align_t ; #endif } #else // __cplusplus //#include // amalgamate: included above // see https://sourceware.org/bugzilla/show_bug.cgi?id=25399 (ubuntu gcc-4.8) #define memset(s, c, count) __builtin_memset(s, c, count) #endif // __cplusplus #endif // __GNUC__ == 4 && __GNUC_MINOR__ >= 8 #endif // C4_GCC_4_8_HPP_ // (end ext/c4core.src/c4/gcc-4.8.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/compiler.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_COMPILER_HPP_ #define C4_COMPILER_HPP_ /** @file compiler.hpp Provides compiler information macros * @ingroup basic_headers */ #ifndef C4_PLATFORM_HPP_ //#include "c4/platform.hpp" // amalgamate: remove include #error "amalgamate: c4/platform.hpp must have been amalgamated before this point" #endif /* C4_PLATFORM_HPP_ */ // Compilers: // C4_MSVC // Visual Studio 2026: MSVC++ 18, 1950 // Visual Studio 2022: MSVC++ 17, 1930 // Visual Studio 2019: MSVC++ 16, 1920 // Visual Studio 2017: MSVC++ 15 // Visual Studio 2015: MSVC++ 14 // Visual Studio 2013: MSVC++ 13 // Visual Studio 2013: MSVC++ 12 // Visual Studio 2012: MSVC++ 11 // Visual Studio 2010: MSVC++ 10 // Visual Studio 2008: MSVC++ 09 // Visual Studio 2005: MSVC++ 08 // C4_CLANG // C4_GCC // C4_ICC (intel compiler) /** @see http://sourceforge.net/p/predef/wiki/Compilers/ for a list of compiler identifier macros */ /** @see https://msdn.microsoft.com/en-us/library/b0084kay.aspx for VS2013 predefined macros */ #if defined(_MSC_VER) # define C4_MSVC # define C4_MSVC_VERSION_2026 18 # define C4_MSVC_VERSION_2022 17 # define C4_MSVC_VERSION_2019 16 # define C4_MSVC_VERSION_2017 15 # define C4_MSVC_VERSION_2015 14 # define C4_MSVC_VERSION_2013 12 # define C4_MSVC_VERSION_2012 11 # if _MSC_VER >= 1950 # define C4_MSVC_VERSION C4_MSVC_VERSION_2026 // visual studio 2026 # define C4_MSVC_2026 # elif _MSC_VER >= 1930 # define C4_MSVC_VERSION C4_MSVC_VERSION_2022 // visual studio 2022 # define C4_MSVC_2022 # elif _MSC_VER >= 1920 # define C4_MSVC_VERSION C4_MSVC_VERSION_2019 // visual studio 2019 # define C4_MSVC_2019 # elif _MSC_VER >= 1910 # define C4_MSVC_VERSION C4_MSVC_VERSION_2017 // visual studio 2017 # define C4_MSVC_2017 # elif _MSC_VER == 1900 # define C4_MSVC_VERSION C4_MSVC_VERSION_2015 // visual studio 2015 # define C4_MSVC_2015 # elif _MSC_VER == 1800 # error "MSVC version not supported" # define C4_MSVC_VERSION C4_MSVC_VERSION_2013 // visual studio 2013 # define C4_MSVC_2013 # elif _MSC_VER == 1700 # error "MSVC version not supported" # define C4_MSVC_VERSION C4_MSVC_VERSION_2012 // visual studio 2012 # define C4_MSVC_2012 # elif _MSC_VER == 1600 # error "MSVC version not supported" # define C4_MSVC_VERSION 10 // visual studio 2010 # define C4_MSVC_2010 # elif _MSC_VER == 1500 # error "MSVC version not supported" # define C4_MSVC_VERSION 09 // visual studio 2008 # define C4_MSVC_2008 # elif _MSC_VER == 1400 # error "MSVC version not supported" # define C4_MSVC_VERSION 08 // visual studio 2005 # define C4_MSVC_2005 # else # error "MSVC version not supported" # endif // _MSC_VER #else # define C4_MSVC_VERSION 0 // visual studio not present # define C4_GCC_LIKE # ifdef __INTEL_COMPILER // check ICC before checking GCC, as ICC defines __GNUC__ too # define C4_ICC # define C4_ICC_VERSION __INTEL_COMPILER # elif defined(__APPLE_CC__) # define C4_XCODE # if defined(__clang__) # define C4_CLANG # ifndef __apple_build_version__ # define C4_CLANG_VERSION C4_VERSION_ENCODED(__clang_major__, __clang_minor__, __clang_patchlevel__) # else # define C4_CLANG_VERSION __apple_build_version__ # endif # else # define C4_XCODE_VERSION __APPLE_CC__ # endif # elif defined(__clang__) # define C4_CLANG # ifndef __apple_build_version__ # define C4_CLANG_VERSION C4_VERSION_ENCODED(__clang_major__, __clang_minor__, __clang_patchlevel__) # else # define C4_CLANG_VERSION __apple_build_version__ # endif # elif defined(__GNUC__) # ifdef __MINGW32__ # define C4_MINGW # endif # define C4_GCC # if defined(__GNUC_PATCHLEVEL__) # define C4_GCC_VERSION C4_VERSION_ENCODED(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) # else # define C4_GCC_VERSION C4_VERSION_ENCODED(__GNUC__, __GNUC_MINOR__, 0) # endif # if __GNUC__ < 5 # if __GNUC__ == 4 && __GNUC_MINOR__ >= 8 // provided by cmake sub-project #ifndef C4_GCC_4_8_HPP_ //# include "c4/gcc-4.8.hpp" // amalgamate: remove include #error "amalgamate: c4/gcc-4.8.hpp must have been amalgamated before this point" #endif /* C4_GCC_4_8_HPP_ */ # else // we do not support GCC < 4.8: // * misses std::is_trivially_copyable // * misses std::align // * -Wshadow has false positives when a local function parameter has the same name as a method # error "GCC < 4.8 is not supported" # endif # endif # endif #endif // defined(C4_WIN) && defined(_MSC_VER) #endif /* C4_COMPILER_HPP_ */ // (end ext/c4core.src/c4/compiler.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/language.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_LANGUAGE_HPP_ #define C4_LANGUAGE_HPP_ /** @file language.hpp Provides language standard information macros and * compiler agnostic utility macros: namespace facilities, function attributes, * variable attributes, etc. * @ingroup basic_headers */ #ifndef C4_PREPROCESSOR_HPP_ //#include "c4/preprocessor.hpp" // amalgamate: remove include #error "amalgamate: c4/preprocessor.hpp must have been amalgamated before this point" #endif /* C4_PREPROCESSOR_HPP_ */ #ifndef C4_COMPILER_HPP_ //#include "c4/compiler.hpp" // amalgamate: remove include #error "amalgamate: c4/compiler.hpp must have been amalgamated before this point" #endif /* C4_COMPILER_HPP_ */ #ifndef C4_EXPORT_HPP_ //#include "c4/export.hpp" // amalgamate: remove include #error "amalgamate: c4/export.hpp must have been amalgamated before this point" #endif /* C4_EXPORT_HPP_ */ /* Detect C++ standard. * @see http://stackoverflow.com/a/7132549/5875572 */ #ifndef C4_CPP # if defined(_MSC_VER) && !defined(__clang__) # if _MSC_VER >= 1910 // >VS2015: VS2017, VS2019, VS2022 # if (!defined(_MSVC_LANG)) # error _MSVC not defined # endif # if _MSVC_LANG >= 202302L # define C4_CPP 23 # elif _MSVC_LANG >= 202002L # define C4_CPP 20 # elif _MSVC_LANG == 201703L # define C4_CPP 17 # elif _MSVC_LANG >= 201402L # define C4_CPP 14 # elif _MSVC_LANG >= 201103L # define C4_CPP 11 # else # error C++ lesser than C++11 not supported # endif # else # if _MSC_VER == 1900 # define C4_CPP 14 // VS2015 is c++14 https://devblogs.microsoft.com/cppblog/c111417-features-in-vs-2015-rtm/ # elif _MSC_VER == 1800 // VS2013 # define C4_CPP 11 # else # error C++ lesser than C++11 not supported # endif # endif # elif defined(__INTEL_COMPILER) // not sure about this https://software.intel.com/en-us/node/524490 # ifdef __INTEL_CXX23_MODE__ # define C4_CPP 23 # elif defined __INTEL_CXX20_MODE__ # define C4_CPP 20 # elif defined __INTEL_CXX17_MODE__ # define C4_CPP 17 # elif defined __INTEL_CXX14_MODE__ # define C4_CPP 14 # elif defined __INTEL_CXX11_MODE__ # define C4_CPP 11 # else # error C++ lesser than C++11 not supported # endif # else # ifndef __cplusplus # error __cplusplus is not defined? # endif # if __cplusplus == 1 # error cannot handle __cplusplus==1 # elif __cplusplus >= 202302L # define C4_CPP 23 # elif __cplusplus >= 202002L # define C4_CPP 20 # elif __cplusplus >= 201703L # define C4_CPP 17 # elif __cplusplus >= 201402L # define C4_CPP 14 # elif __cplusplus >= 201103L # define C4_CPP 11 # elif __cplusplus >= 199711L # error C++ lesser than C++11 not supported # endif # endif #endif #if C4_CPP >= 23 # define C4_CPP23 #endif #if C4_CPP >= 20 # define C4_CPP20 #endif #if C4_CPP >= 17 # define C4_CPP17 #endif #if C4_CPP >= 14 # define C4_CPP14 #endif #if C4_CPP >= 11 # define C4_CPP11 #endif /** lifted from this answer: http://stackoverflow.com/a/20170989/5875572 */ #if defined(_MSC_VER) && !defined(__clang__) # if _MSC_VER < 1900 # define C4_CONSTEXPR11 # define C4_CONSTEXPR14 # elif _MSC_VER < 2000 # define C4_CONSTEXPR11 constexpr # define C4_CONSTEXPR14 # else # define C4_CONSTEXPR11 constexpr # define C4_CONSTEXPR14 constexpr # endif #else # if __cplusplus < 201103 # define C4_CONSTEXPR11 # define C4_CONSTEXPR14 # elif __cplusplus == 201103 # define C4_CONSTEXPR11 constexpr # define C4_CONSTEXPR14 # else # define C4_CONSTEXPR11 constexpr # define C4_CONSTEXPR14 constexpr # endif #endif // _MSC_VER #if C4_CPP < 17 #define C4_IF_CONSTEXPR #define C4_INLINE_CONSTEXPR constexpr #else #define C4_IF_CONSTEXPR constexpr #define C4_INLINE_CONSTEXPR inline constexpr #endif #if defined(_MSC_VER) && !defined(__clang__) # if (defined(_CPPUNWIND) && (_CPPUNWIND == 1)) # define C4_EXCEPTIONS # endif #else # if defined(__EXCEPTIONS) || defined(__cpp_exceptions) # define C4_EXCEPTIONS # endif #endif #ifdef C4_EXCEPTIONS # define C4_IF_EXCEPTIONS_(exc_code, setjmp_code) exc_code # define C4_IF_EXCEPTIONS(exc_code, setjmp_code) do { exc_code } while(0) #else # define C4_IF_EXCEPTIONS_(exc_code, setjmp_code) setjmp_code # define C4_IF_EXCEPTIONS(exc_code, setjmp_code) do { setjmp_code } while(0) #endif #if defined(_MSC_VER) && !defined(__clang__) # if defined(_CPPRTTI) # define C4_RTTI # endif #else # if defined(__GXX_RTTI) # define C4_RTTI # endif #endif #ifdef C4_RTTI # define C4_IF_RTTI_(code_rtti, code_no_rtti) code_rtti # define C4_IF_RTTI(code_rtti, code_no_rtti) do { code_rtti } while(0) #else # define C4_IF_RTTI_(code_rtti, code_no_rtti) code_no_rtti # define C4_IF_RTTI(code_rtti, code_no_rtti) do { code_no_rtti } while(0) #endif //------------------------------------------------------------ #define C4_BEGIN_NAMESPACE(ns) namespace ns { #define C4_END_NAMESPACE(ns) } // MSVC cant handle the C4_FOR_EACH macro... need to fix this //#define C4_BEGIN_NAMESPACE(...) C4_FOR_EACH_SEP(C4_BEGIN_NAMESPACE, , __VA_ARGS__) //#define C4_END_NAMESPACE(...) C4_FOR_EACH_SEP(C4_END_NAMESPACE, , __VA_ARGS__) #define C4_BEGIN_NAMESPACE(ns) namespace ns { #define C4_END_NAMESPACE(ns) } #define C4_BEGIN_HIDDEN_NAMESPACE namespace /*hidden*/ { #define C4_END_HIDDEN_NAMESPACE } /* namespace hidden */ //------------------------------------------------------------ #ifndef C4_API # if defined(_MSC_VER) && !defined(__clang__) # if defined(C4_EXPORT) # define C4_API __declspec(dllexport) # elif defined(C4_IMPORT) # define C4_API __declspec(dllimport) # else # define C4_API # endif # else # define C4_API # endif #endif #if defined(_MSC_VER) && !defined(__clang__) # define C4_RESTRICT __restrict # define C4_RESTRICT_FN __declspec(restrict) # define C4_NO_INLINE __declspec(noinline) # define C4_ALWAYS_INLINE inline __forceinline /** these are not available in VS AFAIK */ # define C4_CONST # define C4_PURE # define C4_FLATTEN # define C4_HOT /** @todo */ # define C4_COLD /** @todo */ # define C4_ASSUME(...) __assume(__VA_ARGS__) # define C4_EXPECT(x, y) x /** @todo */ # define C4_UNREACHABLE() _c4_msvc_unreachable() # define C4_ATTR_FORMAT(...) /** */ # define C4_NORETURN [[noreturn]] # if _MSC_VER >= 1700 // VS2012 # define C4_NODISCARD _Check_return_ # else # define C4_NODISCARD # endif #if C4_CPP >= 17 # define C4_MAYBE_UNUSED [[maybe_unused]] #else # define C4_MAYBE_UNUSED #endif [[noreturn]] __forceinline void _c4_msvc_unreachable() { __assume(false); } ///< https://stackoverflow.com/questions/60802864/emulating-gccs-builtin-unreachable-in-visual-studio # define C4_UNREACHABLE_AFTER_ERR() /* */ #else ///< @todo assuming gcc-like compiler. check it is actually so. /** for function attributes in GCC, * @see https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes */ /** for __builtin functions in GCC, * @see https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html */ # define C4_RESTRICT __restrict__ # define C4_RESTRICT_FN __attribute__((restrict)) # define C4_NO_INLINE __attribute__((noinline)) # define C4_ALWAYS_INLINE inline __attribute__((always_inline)) # define C4_CONST __attribute__((const)) # define C4_PURE __attribute__((pure)) /** force inlining of every callee function */ # define C4_FLATTEN __atribute__((flatten)) /** mark a function as hot, ie as having a visible impact in CPU time * thus making it more likely to inline, etc * @see http://stackoverflow.com/questions/15028990/semantics-of-gcc-hot-attribute */ # define C4_HOT __attribute__((hot)) /** mark a function as cold, ie as NOT having a visible impact in CPU time * @see http://stackoverflow.com/questions/15028990/semantics-of-gcc-hot-attribute */ # define C4_COLD __attribute__((cold)) # define C4_EXPECT(x, y) __builtin_expect(x, y) ///< @see https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html # define C4_UNREACHABLE() __builtin_unreachable() # define C4_ATTR_FORMAT(...) //__attribute__((format (__VA_ARGS__))) ///< @see https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes # define C4_NORETURN __attribute__((noreturn)) # define C4_NODISCARD __attribute__((warn_unused_result)) #if C4_CPP >= 17 # define C4_MAYBE_UNUSED [[maybe_unused]] #else # define C4_MAYBE_UNUSED __attribute__((unused)) #endif # define C4_UNREACHABLE_AFTER_ERR() C4_UNREACHABLE() // C4_ASSUME // see https://stackoverflow.com/questions/63493968/reproducing-clangs-builtin-assume-for-gcc // preferred option: C++ standard attribute # ifdef __has_cpp_attribute # if __has_cpp_attribute(assume) >= 202207L # define C4_ASSUME(...) [[assume(__VA_ARGS__)]] # endif # endif // first fallback: compiler intrinsics/attributes for assumptions # ifndef C4_ASSUME # if defined(__clang__) # define C4_ASSUME(...) __builtin_assume(__VA_ARGS__) # elif defined(__GNUC__) # if __GNUC__ >= 13 # define C4_ASSUME(...) __attribute__((__assume__(__VA_ARGS__))) # endif # endif # endif // second fallback: possibly evaluating uses of unreachable() // Set this to 1 if you want to allow assumptions to possibly evaluate. # ifndef C4_ASSUME_ALLOW_EVAL # define C4_ASSUME_ALLOW_EVAL 0 # endif # if !defined(C4_ASSUME) && (C4_ASSUME_ALLOW_EVAL) # define C4_ASSUME(...) do { if (!bool(__VA_ARGS__)) C4_UNREACHABLE(); ) while(0) # endif // last fallback: define macro as doing nothing # ifndef C4_ASSUME # define C4_ASSUME(...) # endif #endif #ifdef __has_cpp_attribute # if (__has_cpp_attribute(unlikely) >= 201803L) && (C4_CPP >= 20) # define C4_UNLIKELY_IS_ATTR_ # endif #endif #ifdef C4_UNLIKELY_IS_ATTR_ # define C4_LIKELY(x) (x) [[likely]] # define C4_UNLIKELY(x) (x) [[unlikely]] # define C4_LIKELY20 [[likely]] # define C4_UNLIKELY20 [[unlikely]] #elif defined(__clang__) || defined(__GNUC__) # define C4_LIKELY(x) (__builtin_expect(x, 1)) # define C4_UNLIKELY(x) (__builtin_expect(x, 0)) # define C4_LIKELY20 # define C4_UNLIKELY20 #elif defined(_MSC_VER) # define C4_LIKELY(x) (x) # define C4_UNLIKELY(x) (x) # define C4_LIKELY20 # define C4_UNLIKELY20 #endif #if C4_CPP >= 14 # define C4_DEPRECATED(msg) [[deprecated(msg)]] #else # if defined(_MSC_VER) # define C4_DEPRECATED(msg) __declspec(deprecated(msg)) # else // defined(__GNUC__) || defined(__clang__) # define C4_DEPRECATED(msg) __attribute__((deprecated(msg))) # endif #endif #ifdef _MSC_VER # define C4_FUNC __FUNCTION__ # define C4_PRETTY_FUNC __FUNCSIG__ #else /// @todo assuming gcc-like compiler. check it is actually so. # define C4_FUNC __FUNCTION__ # define C4_PRETTY_FUNC __PRETTY_FUNCTION__ #endif /** prevent compiler warnings about a specific var being unused */ #define C4_UNUSED(var) (void)var #if C4_CPP >= 17 #define C4_STATIC_ASSERT(cond) static_assert(cond) #else #define C4_STATIC_ASSERT(cond) static_assert((cond), #cond) #endif #define C4_STATIC_ASSERT_MSG(cond, msg) static_assert((cond), #cond ": " msg) /** @def C4_DONT_OPTIMIZE() idea taken from GoogleBenchmark. * @see https://github.com/google/benchmark/blob/master/include/benchmark/benchmark_api.h */ namespace c4 { namespace detail { #if defined(__GNUC__) # define C4_DONT_OPTIMIZE(var) c4::detail::dont_optimize(var) template< class T > C4_ALWAYS_INLINE void dont_optimize(T const& value) { asm volatile("" : : "g"(value) : "memory"); } // NOLINT #else # define C4_DONT_OPTIMIZE(var) c4::detail::use_char_pointer(reinterpret_cast< const char* >(&var)) C4CORE_EXPORT void use_char_pointer(char const volatile*); #endif } // namespace detail } // namespace c4 /** @def C4_KEEP_EMPTY_LOOP() prevent an empty loop from being optimized out. * @see http://stackoverflow.com/a/7084193/5875572 */ #if defined(_MSC_VER) && !defined(__clang__) # define C4_KEEP_EMPTY_LOOP { char c; C4_DONT_OPTIMIZE(c); } #else # define C4_KEEP_EMPTY_LOOP { asm(""); } #endif #endif /* C4_LANGUAGE_HPP_ */ // (end ext/c4core.src/c4/language.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/types.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_TYPES_HPP_ #define C4_TYPES_HPP_ //#include // amalgamate: included above #include //#include // amalgamate: included above #if __cplusplus >= 201103L #include // for integer_sequence and friends #endif #ifndef C4_PREPROCESSOR_HPP_ //#include "c4/preprocessor.hpp" // amalgamate: remove include #error "amalgamate: c4/preprocessor.hpp must have been amalgamated before this point" #endif /* C4_PREPROCESSOR_HPP_ */ #ifndef C4_LANGUAGE_HPP_ //#include "c4/language.hpp" // amalgamate: remove include #error "amalgamate: c4/language.hpp must have been amalgamated before this point" #endif /* C4_LANGUAGE_HPP_ */ /** @file types.hpp basic types, and utility macros and traits for types. * @ingroup basic_headers */ /** @defgroup types Type utilities */ // NOLINTBEGIN(bugprone-macro-parentheses) namespace c4 { /** @defgroup intrinsic_types Intrinsic types * @ingroup types * @{ */ using cbyte = const char; /**< a constant byte */ using byte = char; /**< a mutable byte */ using i8 = int8_t; using i16 = int16_t; using i32 = int32_t; using i64 = int64_t; using u8 = uint8_t; using u16 = uint16_t; using u32 = uint32_t; using u64 = uint64_t; using f32 = float; using f64 = double; using ssize_t = typename std::make_signed::type; // NOLINT /** @} */ //-------------------------------------------------- /** @defgroup utility_types Utility types * @ingroup types * @{ */ // some tag types #if !defined(__clang__) && defined(__GNUC__) #pragma GCC diagnostic push #if __GNUC__ >= 6 #pragma GCC diagnostic ignored "-Wunused-const-variable" #endif #endif /** a tag type for initializing the containers with variadic arguments a la * initializer_list, minus the initializer_list overload problems. */ struct aggregate_t {}; /** @see aggregate_t */ constexpr const aggregate_t aggregate{}; /** a tag type for specifying the initial capacity of allocatable contiguous storage */ struct with_capacity_t {}; /** @see with_capacity_t */ constexpr const with_capacity_t with_capacity{}; /** a tag type for disambiguating template parameter packs in variadic template overloads */ struct varargs_t {}; /** @see with_capacity_t */ constexpr const varargs_t varargs{}; #if !defined(__clang__) && defined(__GNUC__) #pragma GCC diagnostic pop #endif //-------------------------------------------------- /** whether a value should be used in place of a const-reference in argument passing. */ template struct cref_uses_val { enum { value = ( std::is_scalar::value || ( #if C4_CPP >= 20 (std::is_trivially_copyable::value && std::is_standard_layout::value) #else std::is_pod::value #endif && sizeof(T) <= sizeof(size_t))) }; }; /** utility macro to override the default behaviour for c4::fastcref @see fastcref */ #define C4_CREF_USES_VAL(T) \ template<> \ struct cref_uses_val \ { \ enum { value = true }; \ }; /** Whether to use pass-by-value or pass-by-const-reference in a function argument * or return type. */ template using fastcref = typename std::conditional::value, T, T const&>::type; //-------------------------------------------------- /** Just what its name says. Useful sometimes as a default empty policy class. */ struct EmptyStruct // NOLINT { template EmptyStruct(T && ...){} // NOLINT }; /** Just what its name says. Useful sometimes as a default policy class to * be inherited from. */ struct EmptyStructVirtual // NOLINT { virtual ~EmptyStructVirtual() = default; template EmptyStructVirtual(T && ...){} // NOLINT }; /** */ template struct inheritfrom : public T {}; //-------------------------------------------------- // Utilities to make a class obey size restrictions (eg, min size or size multiple of). // DirectX usually makes this restriction with uniform buffers. // This is also useful for padding to prevent false-sharing. /** how many bytes must be added to size such that the result is at least minsize? */ C4_ALWAYS_INLINE constexpr size_t min_remainder(size_t size, size_t minsize) noexcept { return size < minsize ? minsize-size : 0; } /** how many bytes must be added to size such that the result is a multiple of multipleof? */ C4_ALWAYS_INLINE constexpr size_t mult_remainder(size_t size, size_t multipleof) noexcept { return (((size % multipleof) != 0) ? (multipleof-(size % multipleof)) : 0); } /* force the following class to be tightly packed. */ #pragma pack(push, 1) /** pad a class with more bytes at the end. * @see http://stackoverflow.com/questions/21092415/force-c-structure-to-pack-tightly */ template struct Padded : public T { using T::T; using T::operator=; Padded(T const& val) : T(val) {} Padded(T && val) : T(std::forward(val)) {} // NOLINT char Padded_pad_space_[BytesToPadAtEnd]; }; #pragma pack(pop) /** When the padding argument is 0, we cannot declare the char[] array. */ template struct Padded : public T { using T::T; using T::operator=; Padded(T const& val) : T(val) {} Padded(T && val) : T(std::forward(val)) {} // NOLINT }; /** make T have a size which is at least Min bytes */ template using MinSized = Padded; /** make T have a size which is a multiple of Mult bytes */ template using MultSized = Padded; /** make T have a size which is simultaneously: * -bigger or equal than Min * -a multiple of Mult */ template using MinMultSized = MultSized, Mult>; /** make T be suitable for use as a uniform buffer. (at least with DirectX). */ template using UbufSized = MinMultSized; //----------------------------------------------------------------------------- #define C4_NO_COPY_CTOR(ty) ty(ty const&) = delete #define C4_NO_MOVE_CTOR(ty) ty(ty &&) = delete #define C4_NO_COPY_ASSIGN(ty) ty& operator=(ty const&) = delete #define C4_NO_MOVE_ASSIGN(ty) ty& operator=(ty &&) = delete #define C4_DEFAULT_COPY_CTOR(ty) ty(ty const&) noexcept = default #define C4_DEFAULT_MOVE_CTOR(ty) ty(ty &&) noexcept = default #define C4_DEFAULT_COPY_ASSIGN(ty) ty& operator=(ty const&) noexcept = default #define C4_DEFAULT_MOVE_ASSIGN(ty) ty& operator=(ty &&) noexcept = default #define C4_NO_COPY_OR_MOVE_CTOR(ty) \ C4_NO_COPY_CTOR(ty); \ C4_NO_MOVE_CTOR(ty) #define C4_NO_COPY_OR_MOVE_ASSIGN(ty) \ C4_NO_COPY_ASSIGN(ty); \ C4_NO_MOVE_ASSIGN(ty) #define C4_NO_COPY_OR_MOVE(ty) \ C4_NO_COPY_OR_MOVE_CTOR(ty); \ C4_NO_COPY_OR_MOVE_ASSIGN(ty) #define C4_DEFAULT_COPY_AND_MOVE_CTOR(ty) \ C4_DEFAULT_COPY_CTOR(ty); \ C4_DEFAULT_MOVE_CTOR(ty) #define C4_DEFAULT_COPY_AND_MOVE_ASSIGN(ty) \ C4_DEFAULT_COPY_ASSIGN(ty); \ C4_DEFAULT_MOVE_ASSIGN(ty) #define C4_DEFAULT_COPY_AND_MOVE(ty) \ C4_DEFAULT_COPY_AND_MOVE_CTOR(ty); \ C4_DEFAULT_COPY_AND_MOVE_ASSIGN(ty) /** @see https://en.cppreference.com/w/cpp/named_req/TriviallyCopyable */ #define C4_MUST_BE_TRIVIAL_COPY(ty) \ static_assert(std::is_trivially_copyable::value, #ty " must be trivially copyable") /** @} */ //----------------------------------------------------------------------------- /** @defgroup traits_types Type traits utilities * @ingroup types * @{ */ // http://stackoverflow.com/questions/10821380/is-t-an-instance-of-a-template-in-c template class X, typename T> struct is_instance_of_tpl : std::false_type {}; template class X, typename... Y> struct is_instance_of_tpl> : std::true_type {}; //----------------------------------------------------------------------------- /** SFINAE. use this macro to enable a template function overload based on a compile-time condition. @code // define an overload for a non-pod type template::value)> void foo() { std::cout << "pod type\n"; } // define an overload for a non-pod type template::value)> void foo() { std::cout << "nonpod type\n"; } struct non_pod { non_pod() : name("asdfkjhasdkjh") {} const char *name; }; int main() { foo(); // prints "pod type" foo(); // prints "nonpod type" } @endcode */ #define C4_REQUIRE_T(cond) typename std::enable_if::type* = nullptr /** enable_if for a return type * @see C4_REQUIRE_T */ #define C4_REQUIRE_R(cond, type_) typename std::enable_if::type //----------------------------------------------------------------------------- /** define a traits class reporting whether a type provides a member typedef */ #define C4_DEFINE_HAS_TYPEDEF(member_typedef) \ template \ struct has_##stype \ { \ private: \ \ typedef char yes; \ typedef struct { char array[2]; } no; \ \ template \ static yes _test(typename C::member_typedef*); \ \ template \ static no _test(...); \ \ public: \ \ enum { value = (sizeof(_test(0)) == sizeof(yes)) }; \ \ } /** @} */ //----------------------------------------------------------------------------- /** @defgroup type_declarations Type declaration utilities * @ingroup types * @{ */ #define _c4_DEFINE_ARRAY_TYPES_WITHOUT_ITERATOR(T, I) \ \ using size_type = I; \ using ssize_type = typename std::make_signed::type; \ using difference_type = typename std::make_signed::type; \ \ using value_type = T; \ using pointer = T*; \ using const_pointer = T const*; \ using reference = T&; \ using const_reference = T const& #define _c4_DEFINE_TUPLE_ARRAY_TYPES_WITHOUT_ITERATOR(interior_types, I) \ \ using size_type = I; \ using ssize_type = typename std::make_signed::type; \ using difference_type = typename std::make_signed::type; \ \ template using value_type = typename std::tuple_element< n, std::tuple>::type; \ template using pointer = value_type*; \ template using const_pointer = value_type const*; \ template using reference = value_type&; \ template using const_reference = value_type const& #define _c4_DEFINE_ARRAY_TYPES(T, I) \ \ _c4_DEFINE_ARRAY_TYPES_WITHOUT_ITERATOR(T, I); \ \ using iterator = T*; \ using const_iterator = T const*; \ using reverse_iterator = std::reverse_iterator; \ using const_reverse_iterator = std::reverse_iterator #define _c4_DEFINE_TUPLE_ARRAY_TYPES(interior_types, I) \ \ _c4_DEFINE_TUPLE_ARRAY_TYPES_WITHOUT_ITERATOR(interior_types, I); \ \ template using iterator = value_type*; \ template using const_iterator = value_type const*; \ template using reverse_iterator = std::reverse_iterator< value_type*>; \ template using const_reverse_iterator = std::reverse_iterator< value_type const*> /** @} */ //----------------------------------------------------------------------------- /** @defgroup compatility_utilities Backport implementation of some Modern C++ utilities * @ingroup types * @{ */ //----------------------------------------------------------------------------- // index_sequence and friends are available only for C++14 and later. // A C++11 implementation is provided here. // This implementation was copied over from clang. // see http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/utility?revision=211563&view=markup#l687 #if __cplusplus > 201103L using std::integer_sequence; using std::index_sequence; using std::make_integer_sequence; using std::make_index_sequence; using std::index_sequence_for; #else # if (defined(__clang_major__) && (__clang_major__ >= 13)) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wreserved-identifier" # endif /** C++11 implementation of integer sequence * @see https://en.cppreference.com/w/cpp/utility/integer_sequence * @see taken from clang: http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/utility?revision=211563&view=markup#l687 */ template struct integer_sequence { static_assert(std::is_integral<_Tp>::value, "std::integer_sequence can only be instantiated with an integral type" ); using value_type = _Tp; static constexpr size_t size() noexcept { return sizeof...(_Ip); } }; /** C++11 implementation of index sequence * @see https://en.cppreference.com/w/cpp/utility/integer_sequence * @see taken from clang: http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/utility?revision=211563&view=markup#l687 */ template using index_sequence = integer_sequence; /** @cond DONT_DOCUMENT_THIS */ namespace __detail { template struct __repeat; template struct __repeat, _Extra...> { using type = integer_sequence<_Tp, _Np..., sizeof...(_Np) + _Np..., (2 * sizeof...(_Np)) + _Np..., (3 * sizeof...(_Np)) + _Np..., (4 * sizeof...(_Np)) + _Np..., (5 * sizeof...(_Np)) + _Np..., (6 * sizeof...(_Np)) + _Np..., (7 * sizeof...(_Np)) + _Np..., _Extra...>; }; template struct __parity; template struct __make : __parity<_Np % 8>::template __pmake<_Np> {}; template<> struct __make<0> { using type = integer_sequence; }; template<> struct __make<1> { using type = integer_sequence; }; template<> struct __make<2> { using type = integer_sequence; }; template<> struct __make<3> { using type = integer_sequence; }; template<> struct __make<4> { using type = integer_sequence; }; template<> struct __make<5> { using type = integer_sequence; }; template<> struct __make<6> { using type = integer_sequence; }; template<> struct __make<7> { using type = integer_sequence; }; template<> struct __parity<0> { template struct __pmake : __repeat::type> {}; }; template<> struct __parity<1> { template struct __pmake : __repeat::type, _Np - 1> {}; }; template<> struct __parity<2> { template struct __pmake : __repeat::type, _Np - 2, _Np - 1> {}; }; template<> struct __parity<3> { template struct __pmake : __repeat::type, _Np - 3, _Np - 2, _Np - 1> {}; }; template<> struct __parity<4> { template struct __pmake : __repeat::type, _Np - 4, _Np - 3, _Np - 2, _Np - 1> {}; }; template<> struct __parity<5> { template struct __pmake : __repeat::type, _Np - 5, _Np - 4, _Np - 3, _Np - 2, _Np - 1> {}; }; template<> struct __parity<6> { template struct __pmake : __repeat::type, _Np - 6, _Np - 5, _Np - 4, _Np - 3, _Np - 2, _Np - 1> {}; }; template<> struct __parity<7> { template struct __pmake : __repeat::type, _Np - 7, _Np - 6, _Np - 5, _Np - 4, _Np - 3, _Np - 2, _Np - 1> {}; }; template struct __convert { template struct __result; template<_Tp ..._Np> struct __result> { using type = integer_sequence<_Up, _Np...>; }; }; template struct __convert<_Tp, _Tp> { template struct __result { using type = _Up; }; }; template using __make_integer_sequence_unchecked = typename __detail::__convert::template __result::type>::type; template struct __make_integer_sequence { static_assert(std::is_integral<_Tp>::value, "std::make_integer_sequence can only be instantiated with an integral type" ); static_assert(0 <= _Ep, "std::make_integer_sequence input shall not be negative"); typedef __make_integer_sequence_unchecked<_Tp, _Ep> type; }; } // namespace __detail /** @endcond */ /** C++11 implementation of index sequence * @see https://en.cppreference.com/w/cpp/utility/integer_sequence * @see taken from clang: http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/utility?revision=211563&view=markup#l687 */ template using make_integer_sequence = typename __detail::__make_integer_sequence<_Tp, _Np>::type; /** C++11 implementation of index sequence * @see https://en.cppreference.com/w/cpp/utility/integer_sequence * @see taken from clang: http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/utility?revision=211563&view=markup#l687 */ template using make_index_sequence = make_integer_sequence; /** C++11 implementation of index sequence * @see https://en.cppreference.com/w/cpp/utility/integer_sequence * @see taken from clang: http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/utility?revision=211563&view=markup#l687 */ template using index_sequence_for = make_index_sequence; # if (defined(__clang_major__) && (__clang_major__ >= 13)) # pragma clang diagnostic pop # endif #endif /** @} */ } // namespace c4 // NOLINTEND(bugprone-macro-parentheses) #endif /* C4_TYPES_HPP_ */ // (end ext/c4core.src/c4/types.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/config.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_CONFIG_HPP_ #define C4_CONFIG_HPP_ /** @defgroup basic_headers Basic headers * @brief Headers providing basic macros, platform+cpu+compiler information, * C++ facilities and basic typedefs. */ /** @file config.hpp Contains configuration defines and includes the basic_headers. * @ingroup basic_headers */ //#define C4_DEBUG #define C4_ERROR_SHOWS_FILELINE //#define C4_ERROR_SHOWS_FUNC //#define C4_ERROR_THROWS_EXCEPTION //#define C4_NO_ALLOC_DEFAULTS //#define C4_REDEFINE_CPPNEW #ifndef C4_SIZE_TYPE # define C4_SIZE_TYPE size_t #endif #ifndef C4_STR_SIZE_TYPE # define C4_STR_SIZE_TYPE C4_SIZE_TYPE #endif #ifndef C4_TIME_TYPE # define C4_TIME_TYPE double #endif #ifndef C4_EXPORT_HPP_ //#include "c4/export.hpp" // amalgamate: remove include #error "amalgamate: c4/export.hpp must have been amalgamated before this point" #endif /* C4_EXPORT_HPP_ */ #ifndef C4_PREPROCESSOR_HPP_ //#include "c4/preprocessor.hpp" // amalgamate: remove include #error "amalgamate: c4/preprocessor.hpp must have been amalgamated before this point" #endif /* C4_PREPROCESSOR_HPP_ */ #ifndef C4_PLATFORM_HPP_ //#include "c4/platform.hpp" // amalgamate: remove include #error "amalgamate: c4/platform.hpp must have been amalgamated before this point" #endif /* C4_PLATFORM_HPP_ */ #ifndef C4_CPU_HPP_ //#include "c4/cpu.hpp" // amalgamate: remove include #error "amalgamate: c4/cpu.hpp must have been amalgamated before this point" #endif /* C4_CPU_HPP_ */ #ifndef C4_COMPILER_HPP_ //#include "c4/compiler.hpp" // amalgamate: remove include #error "amalgamate: c4/compiler.hpp must have been amalgamated before this point" #endif /* C4_COMPILER_HPP_ */ #ifndef C4_LANGUAGE_HPP_ //#include "c4/language.hpp" // amalgamate: remove include #error "amalgamate: c4/language.hpp must have been amalgamated before this point" #endif /* C4_LANGUAGE_HPP_ */ #endif // C4_CONFIG_HPP_ // (end ext/c4core.src/c4/config.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/ext/debugbreak/debugbreak.h //-------------------------------------------------------------------------------- //******************************************************************************** /* Copyright (c) 2011-2021, Scott Tsai * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef DEBUG_BREAK_H #define DEBUG_BREAK_H #ifdef _MSC_VER #define debug_break __debugbreak #else #ifdef __cplusplus extern "C" { #endif #define DEBUG_BREAK_USE_TRAP_INSTRUCTION 1 #define DEBUG_BREAK_USE_BUILTIN_TRAP 2 #define DEBUG_BREAK_USE_SIGTRAP 3 #define DEBUG_BREAK_USE_BUILTIN_DEBUGTRAP 4 #if defined(__i386__) || defined(__x86_64__) #define DEBUG_BREAK_IMPL DEBUG_BREAK_USE_TRAP_INSTRUCTION __inline__ static void trap_instruction(void) { __asm__ volatile("int $0x03"); } #elif defined(__thumb__) #define DEBUG_BREAK_IMPL DEBUG_BREAK_USE_TRAP_INSTRUCTION /* FIXME: handle __THUMB_INTERWORK__ */ __attribute__((always_inline)) __inline__ static void trap_instruction(void) { /* See 'arm-linux-tdep.c' in GDB source. * Both instruction sequences below work. */ #if 1 /* 'eabi_linux_thumb_le_breakpoint' */ __asm__ volatile(".inst 0xde01"); #else /* 'eabi_linux_thumb2_le_breakpoint' */ __asm__ volatile(".inst.w 0xf7f0a000"); #endif /* Known problem: * After a breakpoint hit, can't 'stepi', 'step', or 'continue' in GDB. * 'step' would keep getting stuck on the same instruction. * * Workaround: use the new GDB commands 'debugbreak-step' and * 'debugbreak-continue' that become available * after you source the script from GDB: * * $ gdb -x debugbreak-gdb.py <... USUAL ARGUMENTS ...> * * 'debugbreak-step' would jump over the breakpoint instruction with * roughly equivalent of: * (gdb) set $instruction_len = 2 * (gdb) tbreak *($pc + $instruction_len) * (gdb) jump *($pc + $instruction_len) */ } #elif defined(__arm__) && !defined(__thumb__) #define DEBUG_BREAK_IMPL DEBUG_BREAK_USE_TRAP_INSTRUCTION __attribute__((always_inline)) __inline__ static void trap_instruction(void) { /* See 'arm-linux-tdep.c' in GDB source, * 'eabi_linux_arm_le_breakpoint' */ __asm__ volatile(".inst 0xe7f001f0"); /* Known problem: * Same problem and workaround as Thumb mode */ } #elif defined(__aarch64__) && defined(__APPLE__) #define DEBUG_BREAK_IMPL DEBUG_BREAK_USE_BUILTIN_DEBUGTRAP #elif defined(__aarch64__) #define DEBUG_BREAK_IMPL DEBUG_BREAK_USE_TRAP_INSTRUCTION __attribute__((always_inline)) __inline__ static void trap_instruction(void) { /* See 'aarch64-tdep.c' in GDB source, * 'aarch64_default_breakpoint' */ __asm__ volatile(".inst 0xd4200000"); } #elif defined(__powerpc__) /* PPC 32 or 64-bit, big or little endian */ #define DEBUG_BREAK_IMPL DEBUG_BREAK_USE_TRAP_INSTRUCTION __attribute__((always_inline)) __inline__ static void trap_instruction(void) { /* See 'rs6000-tdep.c' in GDB source, * 'rs6000_breakpoint' */ __asm__ volatile(".4byte 0x7d821008"); /* Known problem: * After a breakpoint hit, can't 'stepi', 'step', or 'continue' in GDB. * 'step' stuck on the same instruction ("twge r2,r2"). * * The workaround is the same as ARM Thumb mode: use debugbreak-gdb.py * or manually jump over the instruction. */ } #elif defined(__riscv) /* RISC-V 32 or 64-bit, whether the "C" extension * for compressed, 16-bit instructions are supported or not */ #define DEBUG_BREAK_IMPL DEBUG_BREAK_USE_TRAP_INSTRUCTION __attribute__((always_inline)) __inline__ static void trap_instruction(void) { /* See 'riscv-tdep.c' in GDB source, * 'riscv_sw_breakpoint_from_kind' */ __asm__ volatile(".4byte 0x00100073"); } #else #define DEBUG_BREAK_IMPL DEBUG_BREAK_USE_SIGTRAP #endif #ifndef DEBUG_BREAK_IMPL #error "debugbreak.h is not supported on this target" #elif DEBUG_BREAK_IMPL == DEBUG_BREAK_USE_TRAP_INSTRUCTION __attribute__((always_inline)) __inline__ static void debug_break(void) { trap_instruction(); } #elif DEBUG_BREAK_IMPL == DEBUG_BREAK_USE_BUILTIN_DEBUGTRAP __attribute__((always_inline)) __inline__ static void debug_break(void) { __builtin_debugtrap(); } #elif DEBUG_BREAK_IMPL == DEBUG_BREAK_USE_BUILTIN_TRAP __attribute__((always_inline)) __inline__ static void debug_break(void) { __builtin_trap(); } #elif DEBUG_BREAK_IMPL == DEBUG_BREAK_USE_SIGTRAP #include __attribute__((always_inline)) __inline__ static void debug_break(void) { raise(SIGTRAP); } #else #error "invalid DEBUG_BREAK_IMPL value" #endif #ifdef __cplusplus } #endif #endif /* ifdef _MSC_VER */ #endif /* ifndef DEBUG_BREAK_H */ // (end ext/c4core.src/c4/ext/debugbreak/debugbreak.h) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/error.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_ERROR_HPP_ #define C4_ERROR_HPP_ /** @file error.hpp Facilities for error reporting and runtime assertions. */ /** @defgroup error_checking Error checking */ //#include // amalgamate: included above //#include // amalgamate: included above #ifndef C4_CONFIG_HPP_ //#include "c4/config.hpp" // amalgamate: remove include #error "amalgamate: c4/config.hpp must have been amalgamated before this point" #endif /* C4_CONFIG_HPP_ */ #ifndef C4_EXPORT_HPP_ //#include "c4/export.hpp" // amalgamate: remove include #error "amalgamate: c4/export.hpp must have been amalgamated before this point" #endif /* C4_EXPORT_HPP_ */ #ifndef C4_COMPILER_HPP_ //#include "c4/compiler.hpp" // amalgamate: remove include #error "amalgamate: c4/compiler.hpp must have been amalgamated before this point" #endif /* C4_COMPILER_HPP_ */ #ifndef C4_LANGUAGE_HPP_ //#include "c4/language.hpp" // amalgamate: remove include #error "amalgamate: c4/language.hpp must have been amalgamated before this point" #endif /* C4_LANGUAGE_HPP_ */ #ifdef _DOXYGEN_ /** if this is defined and exceptions are enabled, then calls to C4_ERROR() * will throw an exception * @ingroup error_checking */ # define C4_EXCEPTIONS_ENABLED /** if this is defined and exceptions are enabled, then calls to C4_ERROR() * will throw an exception * @see C4_EXCEPTIONS_ENABLED * @ingroup error_checking */ # define C4_ERROR_THROWS_EXCEPTION /** evaluates to noexcept when C4_ERROR might be called and * exceptions are disabled. Otherwise, defaults to nothing. * @ingroup error_checking */ # define C4_NOEXCEPT #endif // _DOXYGEN_ #if defined(C4_EXCEPTIONS_ENABLED) && defined(C4_ERROR_THROWS_EXCEPTION) # define C4_NOEXCEPT #else # define C4_NOEXCEPT noexcept #endif namespace c4 { namespace detail { struct fail_type_ {}; } // detail } // c4 #define C4_STATIC_ERROR(dummy_type, errmsg) \ static_assert(std::is_same::value, errmsg) //----------------------------------------------------------------------------- #define C4_ASSERT_SAME_TYPE(ty1, ty2) \ C4_STATIC_ASSERT(std::is_same::value) #define C4_ASSERT_DIFF_TYPE(ty1, ty2) \ C4_STATIC_ASSERT( ! std::is_same::value) //----------------------------------------------------------------------------- #ifdef _DOXYGEN_ /** utility macro that triggers a breakpoint when * the debugger is attached and NDEBUG is not defined. * @ingroup error_checking */ # define C4_DEBUG_BREAK() #endif // _DOXYGEN_ #if defined(NDEBUG) || defined(C4_NO_DEBUG_BREAK) # define C4_DEBUG_BREAK() #else # ifdef __clang__ # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wundef" # if !defined(__APPLE_CC__) # if __clang_major__ >= 10 # pragma clang diagnostic ignored "-Wgnu-inline-cpp-without-extern" // debugbreak/debugbreak.h:50:16: error: 'gnu_inline' attribute without 'extern' in C++ treated as externally available, this changed in Clang 10 [-Werror,-Wgnu-inline-cpp-without-extern] # endif # else # if __clang_major__ >= 13 # pragma clang diagnostic ignored "-Wgnu-inline-cpp-without-extern" // debugbreak/debugbreak.h:50:16: error: 'gnu_inline' attribute without 'extern' in C++ treated as externally available, this changed in Clang 10 [-Werror,-Wgnu-inline-cpp-without-extern] # endif # endif # elif defined(__GNUC__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wundef" # endif #ifndef DEBUG_BREAK_H //# include // amalgamate: remove include #error "amalgamate: c4/ext/debugbreak/debugbreak.h must have been amalgamated before this point" #endif /* DEBUG_BREAK_H */ # define C4_DEBUG_BREAK() if(c4::is_debugger_attached()) { ::debug_break(); } # ifdef __clang__ # pragma clang diagnostic pop # elif defined(__GNUC__) # pragma GCC diagnostic pop # endif #endif namespace c4 { C4CORE_EXPORT bool is_debugger_attached(); } // namespace c4 //----------------------------------------------------------------------------- #ifdef __clang__ /* NOTE: using , ## __VA_ARGS__ to deal with zero-args calls to * variadic macros is not portable, but works in clang, gcc, msvc, icc. * clang requires switching off compiler warnings for pedantic mode. * @see http://stackoverflow.com/questions/32047685/variadic-macro-without-arguments */ # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments" // warning: token pasting of ',' and __VA_ARGS__ is a GNU extension #elif defined(__GNUC__) /* GCC also issues a warning for zero-args calls to variadic macros. * This warning is switched on with -pedantic and apparently there is no * easy way to turn it off as with clang. But marking this as a system * header works. * @see https://gcc.gnu.org/onlinedocs/cpp/System-Headers.html * @see http://stackoverflow.com/questions/35587137/ */ # pragma GCC system_header #endif //----------------------------------------------------------------------------- namespace c4 { typedef enum : uint32_t { /** when an error happens and the debugger is attached, call C4_DEBUG_BREAK(). * Without effect otherwise. */ ON_ERROR_DEBUGBREAK = 0x01u << 0u, /** when an error happens log a message. */ ON_ERROR_LOG = 0x01u << 1u, /** when an error happens invoke a callback if it was set with * set_error_callback(). */ ON_ERROR_CALLBACK = 0x01u << 2u, /** when an error happens call std::terminate(). */ ON_ERROR_ABORT = 0x01u << 3u, /** when an error happens and exceptions are enabled throw an exception. * Without effect otherwise. */ ON_ERROR_THROW = 0x01u << 4u, /** the default flags. */ ON_ERROR_DEFAULTS = ON_ERROR_DEBUGBREAK|ON_ERROR_LOG|ON_ERROR_CALLBACK|ON_ERROR_ABORT } ErrorFlags_e; using error_flags = uint32_t; C4CORE_EXPORT void set_error_flags(error_flags f); C4CORE_EXPORT error_flags get_error_flags(); using error_callback_type = void (*)(const char* msg, size_t msg_size); C4CORE_EXPORT void set_error_callback(error_callback_type cb); C4CORE_EXPORT error_callback_type get_error_callback(); //----------------------------------------------------------------------------- /** RAII class controling the error settings inside a scope. */ struct ScopedErrorSettings // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions) { error_flags m_flags; error_callback_type m_callback; explicit ScopedErrorSettings(error_callback_type cb) : m_flags(get_error_flags()), m_callback(get_error_callback()) { set_error_callback(cb); } explicit ScopedErrorSettings(error_flags flags) : m_flags(get_error_flags()), m_callback(get_error_callback()) { set_error_flags(flags); } explicit ScopedErrorSettings(error_flags flags, error_callback_type cb) : m_flags(get_error_flags()), m_callback(get_error_callback()) { set_error_flags(flags); set_error_callback(cb); } ~ScopedErrorSettings() { set_error_flags(m_flags); set_error_callback(m_callback); } }; //----------------------------------------------------------------------------- #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif /** source location */ struct C4CORE_EXPORT srcloc { const char *file; const char *func; int line; srcloc(const char *file_="", const char *func_="", int line_=0) noexcept : file(file_), func(func_), line(line_) {} }; #ifdef __clang__ #pragma clang diagnostic pop #endif #if defined(C4_ERROR_SHOWS_FILELINE) && defined(C4_ERROR_SHOWS_FUNC) #define C4_SRCLOC() c4::srcloc(__FILE__, C4_PRETTY_FUNC, __LINE__) #elif defined(C4_ERROR_SHOWS_FILELINE) #define C4_SRCLOC() c4::srcloc(__FILE__, "", __LINE__) #elif ! defined(C4_ERROR_SHOWS_FUNC) #define C4_SRCLOC() c4::srcloc{} #else # error not implemented #endif #define C4_ERROR(msg, ...) \ do { \ if(c4::get_error_flags() & c4::ON_ERROR_DEBUGBREAK) \ { \ C4_DEBUG_BREAK() \ } \ c4::handle_error(C4_SRCLOC(), msg, ## __VA_ARGS__); \ } while(0) #define C4_WARNING(msg, ...) \ c4::handle_warning(C4_SRCLOC(), msg, ## __VA_ARGS__) // watchout: for VS the [[noreturn]] needs to come before other annotations like C4CORE_EXPORT [[noreturn]] C4CORE_EXPORT void handle_error(srcloc s, const char *fmt, ...); C4CORE_EXPORT void handle_warning(srcloc s, const char *fmt, ...); //----------------------------------------------------------------------------- // assertions // Doxygen needs this so that only one definition counts #ifdef _DOXYGEN_ /** Explicitly enables assertions, independently of NDEBUG status. * This is meant to allow enabling assertions even when NDEBUG is defined. * Defaults to undefined. * @ingroup error_checking */ # define C4_USE_ASSERT /** assert that a condition is true; this is turned off when NDEBUG * is defined and C4_USE_ASSERT is not true. * @ingroup error_checking */ # define C4_ASSERT /** same as C4_ASSERT(), additionally prints a printf-formatted message * @ingroup error_checking */ # define C4_ASSERT_MSG /** evaluates to C4_NOEXCEPT when C4_XASSERT is disabled; otherwise, defaults * to noexcept * @ingroup error_checking */ # define C4_NOEXCEPT_A #endif // _DOXYGEN_ #ifndef C4_USE_ASSERT # ifdef NDEBUG # define C4_USE_ASSERT 0 # else # define C4_USE_ASSERT 1 # endif #endif #if C4_USE_ASSERT # define C4_ASSERT(cond) C4_CHECK(cond) # define C4_ASSERT_MSG(cond, /*fmt, */...) C4_CHECK_MSG(cond, ## __VA_ARGS__) # define C4_ASSERT_IF(predicate, cond) if(predicate) { C4_ASSERT(cond); } # define C4_NOEXCEPT_A C4_NOEXCEPT #else # define C4_ASSERT(cond) # define C4_ASSERT_MSG(cond, /*fmt, */...) # define C4_ASSERT_IF(predicate, cond) # define C4_NOEXCEPT_A noexcept #endif //----------------------------------------------------------------------------- // extreme assertions // Doxygen needs this so that only one definition counts #ifdef _DOXYGEN_ /** Explicitly enables extreme assertions; this is meant to allow enabling * assertions even when NDEBUG is defined. Defaults to undefined. * @ingroup error_checking */ # define C4_USE_XASSERT /** extreme assertion: can be switched off independently of * the regular assertion; use for example for bounds checking in hot code. * Turned on only when C4_USE_XASSERT is defined * @ingroup error_checking */ # define C4_XASSERT /** same as C4_XASSERT(), and additionally prints a printf-formatted message * @ingroup error_checking */ # define C4_XASSERT_MSG /** evaluates to C4_NOEXCEPT when C4_XASSERT is disabled; otherwise, defaults to noexcept * @ingroup error_checking */ # define C4_NOEXCEPT_X #endif // _DOXYGEN_ #ifndef C4_USE_XASSERT # define C4_USE_XASSERT C4_USE_ASSERT #endif #if C4_USE_XASSERT # define C4_XASSERT(cond) C4_CHECK(cond) # define C4_XASSERT_MSG(cond, /*fmt, */...) C4_CHECK_MSG(cond, ## __VA_ARGS__) # define C4_XASSERT_IF(predicate, cond) if(predicate) { C4_XASSERT(cond); } # define C4_NOEXCEPT_X C4_NOEXCEPT #else # define C4_XASSERT(cond) # define C4_XASSERT_MSG(cond, /*fmt, */...) # define C4_XASSERT_IF(predicate, cond) # define C4_NOEXCEPT_X noexcept #endif //----------------------------------------------------------------------------- // checks: never switched-off /** Check that a condition is true, or raise an error when not * true. Unlike C4_ASSERT(), this check is not disabled in non-debug * builds. * @see C4_ASSERT * @ingroup error_checking * * @todo add constexpr-compatible compile-time assert: * https://akrzemi1.wordpress.com/2017/05/18/asserts-in-constexpr-functions/ */ #define C4_CHECK(cond) \ do { \ if C4_UNLIKELY(!(cond)) \ { \ C4_ERROR("check failed: %s", #cond); \ } \ } while(0) /** like C4_CHECK(), and additionally log a printf-style message. * @see C4_CHECK * @ingroup error_checking */ #define C4_CHECK_MSG(cond, fmt, ...) \ do { \ if C4_UNLIKELY(!(cond)) \ { \ C4_ERROR("check failed: " #cond "\n" fmt, ## __VA_ARGS__); \ } \ } while(0) //----------------------------------------------------------------------------- // Common error conditions #define C4_NOT_IMPLEMENTED() C4_ERROR("NOT IMPLEMENTED") #define C4_NOT_IMPLEMENTED_MSG(/*msg, */...) C4_ERROR("NOT IMPLEMENTED: " __VA_ARGS__) #define C4_NOT_IMPLEMENTED_IF(condition) do { if(C4_UNLIKELY(condition)) { C4_ERROR("NOT IMPLEMENTED"); } } while(0) #define C4_NOT_IMPLEMENTED_IF_MSG(condition, /*msg, */...) do { if(C4_UNLIKELY(condition)) { C4_ERROR("NOT IMPLEMENTED: " __VA_ARGS__); } } while(0) #define C4_NEVER_REACH() do { C4_ERROR("never reach this point"); C4_UNREACHABLE(); } while(0) #define C4_NEVER_REACH_MSG(/*msg, */...) do { C4_ERROR("never reach this point: " __VA_ARGS__); C4_UNREACHABLE(); } while(0) //----------------------------------------------------------------------------- // helpers for warning suppression // idea adapted from https://github.com/onqtam/doctest/ // TODO: add C4_MESSAGE() https://stackoverflow.com/questions/18252351/custom-preprocessor-macro-for-a-conditional-pragma-message-xxx?rq=1 #if defined(C4_MSVC) && !defined(__clang__) #define C4_SUPPRESS_WARNING_MSVC_PUSH __pragma(warning(push)) #define C4_SUPPRESS_WARNING_MSVC(w) __pragma(warning(disable : w)) #define C4_SUPPRESS_WARNING_MSVC_POP __pragma(warning(pop)) #else // C4_MSVC #define C4_SUPPRESS_WARNING_MSVC_PUSH #define C4_SUPPRESS_WARNING_MSVC(w) #define C4_SUPPRESS_WARNING_MSVC_POP #endif // C4_MSVC #if defined(C4_CLANG) || defined(__clang__) #define C4_PRAGMA_TO_STR(x) _Pragma(#x) #define C4_SUPPRESS_WARNING_CLANG_PUSH _Pragma("clang diagnostic push") #define C4_SUPPRESS_WARNING_CLANG(w) C4_PRAGMA_TO_STR(clang diagnostic ignored w) #define C4_SUPPRESS_WARNING_CLANG_POP _Pragma("clang diagnostic pop") #else // C4_CLANG #define C4_SUPPRESS_WARNING_CLANG_PUSH #define C4_SUPPRESS_WARNING_CLANG(w) #define C4_SUPPRESS_WARNING_CLANG_POP #endif // C4_CLANG #ifdef C4_GCC #define C4_PRAGMA_TO_STR(x) _Pragma(#x) #define C4_SUPPRESS_WARNING_GCC_PUSH _Pragma("GCC diagnostic push") #define C4_SUPPRESS_WARNING_GCC(w) C4_PRAGMA_TO_STR(GCC diagnostic ignored w) #define C4_SUPPRESS_WARNING_GCC_POP _Pragma("GCC diagnostic pop") #else // C4_GCC #define C4_SUPPRESS_WARNING_GCC_PUSH #define C4_SUPPRESS_WARNING_GCC(w) #define C4_SUPPRESS_WARNING_GCC_POP #endif // C4_GCC #define C4_SUPPRESS_WARNING_MSVC_WITH_PUSH(w) \ C4_SUPPRESS_WARNING_MSVC_PUSH \ C4_SUPPRESS_WARNING_MSVC(w) #define C4_SUPPRESS_WARNING_CLANG_WITH_PUSH(w) \ C4_SUPPRESS_WARNING_CLANG_PUSH \ C4_SUPPRESS_WARNING_CLANG(w) #define C4_SUPPRESS_WARNING_GCC_WITH_PUSH(w) \ C4_SUPPRESS_WARNING_GCC_PUSH \ C4_SUPPRESS_WARNING_GCC(w) #define C4_SUPPRESS_WARNING_PUSH \ C4_SUPPRESS_WARNING_GCC_PUSH \ C4_SUPPRESS_WARNING_CLANG_PUSH \ C4_SUPPRESS_WARNING_MSVC_PUSH #define C4_SUPPRESS_WARNING_GCC_CLANG_PUSH \ C4_SUPPRESS_WARNING_GCC_PUSH \ C4_SUPPRESS_WARNING_CLANG_PUSH #define C4_SUPPRESS_WARNING_GCC_CLANG(w) \ C4_SUPPRESS_WARNING_GCC(w) \ C4_SUPPRESS_WARNING_CLANG(w) #define C4_SUPPRESS_WARNING_GCC_CLANG_WITH_PUSH(w) \ C4_SUPPRESS_WARNING_GCC_WITH_PUSH(w) \ C4_SUPPRESS_WARNING_CLANG_WITH_PUSH(w) #define C4_SUPPRESS_WARNING_GCC_CLANG_POP \ C4_SUPPRESS_WARNING_GCC_POP \ C4_SUPPRESS_WARNING_CLANG_POP #define C4_SUPPRESS_WARNING_POP \ C4_SUPPRESS_WARNING_GCC_POP \ C4_SUPPRESS_WARNING_CLANG_POP \ C4_SUPPRESS_WARNING_MSVC_POP } // namespace c4 #ifdef __clang__ # pragma clang diagnostic pop #endif #endif /* C4_ERROR_HPP_ */ // (end ext/c4core.src/c4/error.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/memory_util.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_MEMORY_UTIL_HPP_ #define C4_MEMORY_UTIL_HPP_ #ifndef C4_CONFIG_HPP_ //#include "c4/config.hpp" // amalgamate: remove include #error "amalgamate: c4/config.hpp must have been amalgamated before this point" #endif /* C4_CONFIG_HPP_ */ #ifndef C4_ERROR_HPP_ //#include "c4/error.hpp" // amalgamate: remove include #error "amalgamate: c4/error.hpp must have been amalgamated before this point" #endif /* C4_ERROR_HPP_ */ #ifndef C4_COMPILER_HPP_ //#include "c4/compiler.hpp" // amalgamate: remove include #error "amalgamate: c4/compiler.hpp must have been amalgamated before this point" #endif /* C4_COMPILER_HPP_ */ #ifndef C4_CPU_HPP_ //#include "c4/cpu.hpp" // amalgamate: remove include #error "amalgamate: c4/cpu.hpp must have been amalgamated before this point" #endif /* C4_CPU_HPP_ */ //#include // amalgamate: included above #ifdef C4_MSVC #include #endif //#include // amalgamate: included above #if (defined(__GNUC__) && __GNUC__ >= 10) || defined(__has_builtin) #define C4_USE_LSB_INTRINSIC_(which) __has_builtin(which) #define C4_USE_MSB_INTRINSIC_(which) __has_builtin(which) #elif defined(C4_MSVC) #define C4_USE_LSB_INTRINSIC_(which) true #define C4_USE_MSB_INTRINSIC_(which) true #else // let's try our luck #define C4_USE_LSB_INTRINSIC_(which) true #define C4_USE_MSB_INTRINSIC_(which) true #endif /** @file memory_util.hpp Some memory utilities. */ // NOLINTBEGIN(google-runtime-int) namespace c4 { C4_SUPPRESS_WARNING_GCC_CLANG_WITH_PUSH("-Wold-style-cast") /** set the given memory to zero */ C4_ALWAYS_INLINE void mem_zero(void* mem, size_t num_bytes) { memset(mem, 0, num_bytes); } /** set the given memory to zero */ template C4_ALWAYS_INLINE void mem_zero(T* mem, size_t num_elms) { memset(mem, 0, sizeof(T) * num_elms); } /** set the given memory to zero */ template C4_ALWAYS_INLINE void mem_zero(T* mem) { memset(mem, 0, sizeof(T)); } C4_ALWAYS_INLINE C4_CONST bool mem_overlaps(void const* a, void const* b, size_t sza, size_t szb) { // thanks @timwynants return (((const char*)b + szb) > a && b < ((const char*)a+sza)); } C4CORE_EXPORT void mem_repeat(void* dest, void const* pattern, size_t pattern_size, size_t num_times); //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- template C4_ALWAYS_INLINE C4_CONST bool is_aligned(T const* ptr, uintptr_t alignment=alignof(T)) { return (uintptr_t(ptr) & (alignment - uintptr_t(1))) == uintptr_t(0); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // least significant bit /** @name msb Compute the least significant bit * @note the input value must be nonzero * @note the input type must be unsigned */ /** @{ */ // https://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightLinear #define _c4_lsb_fallback \ unsigned c = 0; \ v = (v ^ (v - 1)) >> 1; /* Set v's trailing 0s to 1s and zero rest */ \ for(; v; ++c) \ v >>= 1; \ return (unsigned) c // u8 template C4_CONSTEXPR14 auto lsb(I v) noexcept -> typename std::enable_if::type { C4_STATIC_ASSERT(std::is_unsigned::value); C4_ASSERT(v != 0); #if C4_USE_LSB_INTRINSIC_(__builtin_ctz) // upcast to use the intrinsic, it's cheaper. #ifdef C4_MSVC #if !defined(C4_CPU_ARM64) && !defined(C4_CPU_ARM) unsigned long bit = {}; _BitScanForward(&bit, (unsigned long)v); return bit; #else _c4_lsb_fallback; #endif #else return (unsigned)__builtin_ctz((unsigned)v); #endif #else _c4_lsb_fallback; #endif } // u16 template C4_CONSTEXPR14 auto lsb(I v) noexcept -> typename std::enable_if::type { C4_STATIC_ASSERT(std::is_unsigned::value); C4_ASSERT(v != 0); #if C4_USE_LSB_INTRINSIC_(__builtin_ctz) // upcast to use the intrinsic, it's cheaper. // Then remember that the upcast makes it to 31bits #ifdef C4_MSVC #if !defined(C4_CPU_ARM64) && !defined(C4_CPU_ARM) unsigned long bit = {}; _BitScanForward(&bit, (unsigned long)v); return bit; #else _c4_lsb_fallback; #endif #else return (unsigned)__builtin_ctz((unsigned)v); #endif #else _c4_lsb_fallback; #endif } // u32 template C4_CONSTEXPR14 auto lsb(I v) noexcept -> typename std::enable_if::type { C4_STATIC_ASSERT(std::is_unsigned::value); C4_ASSERT(v != 0); #if C4_USE_LSB_INTRINSIC_(__builtin_ctz) #ifdef C4_MSVC #if !defined(C4_CPU_ARM64) && !defined(C4_CPU_ARM) unsigned long bit = {}; _BitScanForward(&bit, v); return bit; #else _c4_lsb_fallback; #endif #else return (unsigned)__builtin_ctz((unsigned)v); #endif #else _c4_lsb_fallback; #endif } // u64 in 64bits template C4_CONSTEXPR14 auto lsb(I v) noexcept -> typename std::enable_if::type { C4_STATIC_ASSERT(std::is_unsigned::value); C4_ASSERT(v != 0); #if C4_USE_LSB_INTRINSIC_(__builtin_ctzl) #if defined(C4_MSVC) #if !defined(C4_CPU_ARM64) && !defined(C4_CPU_ARM) unsigned long bit = {}; _BitScanForward64(&bit, v); return bit; #else _c4_lsb_fallback; #endif #else return (unsigned)__builtin_ctzl((unsigned long)v); #endif #else _c4_lsb_fallback; #endif } // u64 in 32bits template C4_CONSTEXPR14 auto lsb(I v) noexcept -> typename std::enable_if::type { C4_STATIC_ASSERT(std::is_unsigned::value); C4_ASSERT(v != 0); #if C4_USE_LSB_INTRINSIC_(__builtin_ctzll) #if defined(C4_MSVC) #if !defined(C4_CPU_X86) && !defined(C4_CPU_ARM64) && !defined(C4_CPU_ARM) unsigned long bit = {}; _BitScanForward64(&bit, v); return bit; #else _c4_lsb_fallback; #endif #else return (unsigned)__builtin_ctzll((unsigned long long)v); #endif #else _c4_lsb_fallback; #endif } #undef _c4_lsb_fallback /** @} */ namespace detail { template struct _lsb11; template struct _lsb11 { enum : unsigned { num = _lsb11>1), num_bits+I(1), (((val>>1)&I(1))!=I(0))>::num }; }; template struct _lsb11 { enum : unsigned { num = num_bits }; }; } // namespace detail /** TMP version of lsb(); this needs to be implemented with template * meta-programming because C++11 cannot use a constexpr function with * local variables * @see lsb */ template struct lsb11 { static_assert(number != 0, "lsb: number must be nonzero"); enum : unsigned { value = detail::_lsb11::num}; }; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // most significant bit /** @name msb Compute the most significant bit * @note the input value must be nonzero * @note the input type must be unsigned */ /** @{ */ #define _c4_msb8_fallback \ unsigned n = 0; \ if(v & I(0xf0)) v >>= 4, n |= I(4); \ if(v & I(0x0c)) v >>= 2, n |= I(2); \ if(v & I(0x02)) v >>= 1, n |= I(1); \ return n #define _c4_msb16_fallback \ unsigned n = 0; \ if(v & I(0xff00)) v >>= 8, n |= I(8); \ if(v & I(0x00f0)) v >>= 4, n |= I(4); \ if(v & I(0x000c)) v >>= 2, n |= I(2); \ if(v & I(0x0002)) v >>= 1, n |= I(1); \ return n #define _c4_msb32_fallback \ unsigned n = 0; \ if(v & I(0xffff0000)) v >>= 16, n |= 16; \ if(v & I(0x0000ff00)) v >>= 8, n |= 8; \ if(v & I(0x000000f0)) v >>= 4, n |= 4; \ if(v & I(0x0000000c)) v >>= 2, n |= 2; \ if(v & I(0x00000002)) v >>= 1, n |= 1; \ return n #define _c4_msb64_fallback \ unsigned n = 0; \ if(v & I(0xffffffff00000000)) v >>= 32, n |= I(32); \ if(v & I(0x00000000ffff0000)) v >>= 16, n |= I(16); \ if(v & I(0x000000000000ff00)) v >>= 8, n |= I(8); \ if(v & I(0x00000000000000f0)) v >>= 4, n |= I(4); \ if(v & I(0x000000000000000c)) v >>= 2, n |= I(2); \ if(v & I(0x0000000000000002)) v >>= 1, n |= I(1); \ return n // u8 template C4_CONSTEXPR14 auto msb(I v) noexcept -> typename std::enable_if::type { C4_STATIC_ASSERT(std::is_unsigned::value); C4_ASSERT(v != 0); #if C4_USE_MSB_INTRINSIC_(__builtin_clz) // upcast to use the intrinsic, it's cheaper. // Then remember that the upcast makes it to 31bits #ifdef C4_MSVC #if !defined(C4_CPU_ARM64) && !defined(C4_CPU_ARM) unsigned long bit = {}; _BitScanReverse(&bit, (unsigned long)v); return bit; #else _c4_msb8_fallback; #endif #else return 31u - (unsigned)__builtin_clz((unsigned)v); #endif #else _c4_msb8_fallback; #endif } // u16 template C4_CONSTEXPR14 auto msb(I v) noexcept -> typename std::enable_if::type { C4_STATIC_ASSERT(std::is_unsigned::value); C4_ASSERT(v != 0); #if C4_USE_MSB_INTRINSIC_(__builtin_clz) // upcast to use the intrinsic, it's cheaper. // Then remember that the upcast makes it to 31bits #ifdef C4_MSVC #if !defined(C4_CPU_ARM64) && !defined(C4_CPU_ARM) unsigned long bit = {}; _BitScanReverse(&bit, (unsigned long)v); return bit; #else _c4_msb16_fallback; #endif #else return 31u - (unsigned)__builtin_clz((unsigned)v); #endif #else _c4_msb16_fallback; #endif } // u32 template C4_CONSTEXPR14 auto msb(I v) noexcept -> typename std::enable_if::type { C4_STATIC_ASSERT(std::is_unsigned::value); C4_ASSERT(v != 0); #if C4_USE_MSB_INTRINSIC_(__builtin_clz) #ifdef C4_MSVC #if !defined(C4_CPU_ARM64) && !defined(C4_CPU_ARM) unsigned long bit = {}; _BitScanReverse(&bit, v); return bit; #else _c4_msb32_fallback; #endif #else return 31u - (unsigned)__builtin_clz((unsigned)v); #endif #else _c4_msb32_fallback; #endif } // u64 in 64bits template C4_CONSTEXPR14 auto msb(I v) noexcept -> typename std::enable_if::type { C4_STATIC_ASSERT(std::is_unsigned::value); C4_ASSERT(v != 0); #if C4_USE_MSB_INTRINSIC_(__builtin_clzl) #ifdef C4_MSVC #if !defined(C4_CPU_ARM64) && !defined(C4_CPU_ARM) unsigned long bit = {}; _BitScanReverse64(&bit, v); return bit; #else _c4_msb64_fallback; #endif #else return 63u - (unsigned)__builtin_clzl((unsigned long)v); #endif #else _c4_msb64_fallback; #endif } // u64 in 32bits template C4_CONSTEXPR14 auto msb(I v) noexcept -> typename std::enable_if::type { C4_STATIC_ASSERT(std::is_unsigned::value); C4_ASSERT(v != 0); #if C4_USE_MSB_INTRINSIC_(__builtin_clzll) #ifdef C4_MSVC #if !defined(C4_CPU_X86) && !defined(C4_CPU_ARM64) && !defined(C4_CPU_ARM) unsigned long bit = {}; _BitScanReverse64(&bit, v); return bit; #else _c4_msb64_fallback; #endif #else return 63u - (unsigned)__builtin_clzll((unsigned long long)v); #endif #else _c4_msb64_fallback; #endif } #undef _c4_msb8_fallback #undef _c4_msb16_fallback #undef _c4_msb32_fallback #undef _c4_msb64_fallback /** @} */ namespace detail { template struct _msb11; template struct _msb11< I, val, num_bits, false> { enum : unsigned { num = _msb11>1), num_bits+I(1), ((val>>1)==I(0))>::num }; }; template struct _msb11 { static_assert(val == 0, "bad implementation"); enum : unsigned { num = (unsigned)(num_bits-1) }; }; } // namespace detail /** TMP version of msb(); this needs to be implemented with template * meta-programming because C++11 cannot use a constexpr function with * local variables * @see msb */ template struct msb11 { enum : unsigned { value = detail::_msb11::num }; }; #undef C4_USE_LSB_INTRINSIC_ #undef C4_USE_MSB_INTRINSIC_ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // there is an implicit conversion below; it happens when E or B are // narrower than int, and thus any operation will upcast the result to // int, and then downcast to assign C4_SUPPRESS_WARNING_GCC_CLANG_WITH_PUSH("-Wconversion") /** integer power; this function is constexpr-14 because of the local * variables */ template C4_CONSTEXPR14 C4_CONST auto ipow(B base, E exponent) noexcept -> typename std::enable_if::value, B>::type { C4_STATIC_ASSERT(std::is_integral::value); B r = B(1); if(exponent >= 0) { for(E e = 0; e < exponent; ++e) r *= base; } else { exponent *= E(-1); for(E e = 0; e < exponent; ++e) r /= base; } return r; } /** integer power; this function is constexpr-14 because of the local * variables */ template C4_CONSTEXPR14 C4_CONST auto ipow(E exponent) noexcept -> typename std::enable_if::value, B>::type { C4_STATIC_ASSERT(std::is_integral::value); B r = B(1); if(exponent >= 0) { for(E e = 0; e < exponent; ++e) r *= base; } else { exponent *= E(-1); for(E e = 0; e < exponent; ++e) r /= base; } return r; } /** integer power; this function is constexpr-14 because of the local * variables */ template C4_CONSTEXPR14 C4_CONST auto ipow(E exponent) noexcept -> typename std::enable_if::value, B>::type { C4_STATIC_ASSERT(std::is_integral::value); B r = B(1); B bbase = B(base); if(exponent >= 0) { for(E e = 0; e < exponent; ++e) r *= bbase; } else { exponent *= E(-1); for(E e = 0; e < exponent; ++e) r /= bbase; } return r; } /** integer power; this function is constexpr-14 because of the local * variables */ template C4_CONSTEXPR14 C4_CONST auto ipow(B base, E exponent) noexcept -> typename std::enable_if::value, B>::type { C4_STATIC_ASSERT(std::is_integral::value); B r = B(1); for(E e = 0; e < exponent; ++e) r *= base; return r; } /** integer power; this function is constexpr-14 because of the local * variables */ template C4_CONSTEXPR14 C4_CONST auto ipow(E exponent) noexcept -> typename std::enable_if::value, B>::type { C4_STATIC_ASSERT(std::is_integral::value); B r = B(1); for(E e = 0; e < exponent; ++e) r *= base; return r; } /** integer power; this function is constexpr-14 because of the local * variables */ template C4_CONSTEXPR14 C4_CONST auto ipow(E exponent) noexcept -> typename std::enable_if::value, B>::type { C4_STATIC_ASSERT(std::is_integral::value); B r = B(1); B bbase = B(base); for(E e = 0; e < exponent; ++e) r *= bbase; return r; } C4_SUPPRESS_WARNING_GCC_CLANG_POP //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** return a mask with all bits set [first_bit,last_bit[; this function * is constexpr-14 because of the local variables */ template C4_CONSTEXPR14 I contiguous_mask(I first_bit, I last_bit) { I r = 0; for(I i = first_bit; i < last_bit; ++i) { r |= (I(1) << i); } return r; } namespace detail { template struct _ctgmsk11; template struct _ctgmsk11< I, val, first, last, true> { enum : I { value = _ctgmsk11::value }; }; template struct _ctgmsk11< I, val, first, last, false> { enum : I { value = val }; }; } // namespace detail /** TMP version of contiguous_mask(); this needs to be implemented with template * meta-programming because C++11 cannot use a constexpr function with * local variables * @see contiguous_mask */ template struct contiguous_mask11 { enum : I { value = detail::_ctgmsk11::value }; }; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** use Empty Base Class Optimization to reduce the size of a pair of * potentially empty types*/ namespace detail { typedef enum { tpc_same, tpc_same_empty, tpc_both_empty, tpc_first_empty, tpc_second_empty, tpc_general } TightPairCase_e; template constexpr TightPairCase_e tpc_which_case() { return std::is_same::value ? std::is_empty::value ? tpc_same_empty : tpc_same : std::is_empty::value && std::is_empty::value ? tpc_both_empty : std::is_empty::value ? tpc_first_empty : std::is_empty::value ? tpc_second_empty : tpc_general ; } template struct tight_pair { private: First m_first; Second m_second; public: using first_type = First; using second_type = Second; tight_pair() : m_first(), m_second() {} tight_pair(First const& f, Second const& s) : m_first(f), m_second(s) {} C4_ALWAYS_INLINE C4_CONSTEXPR14 First & first () { return m_first; } C4_ALWAYS_INLINE C4_CONSTEXPR14 First const& first () const { return m_first; } C4_ALWAYS_INLINE C4_CONSTEXPR14 Second & second() { return m_second; } C4_ALWAYS_INLINE C4_CONSTEXPR14 Second const& second() const { return m_second; } }; template struct tight_pair : public First { static_assert(std::is_same::value, "bad implementation"); using first_type = First; using second_type = Second; tight_pair() : First() {} tight_pair(First const& f, Second const& /*s*/) : First(f) {} C4_ALWAYS_INLINE C4_CONSTEXPR14 First & first () { return static_cast(*this); } C4_ALWAYS_INLINE C4_CONSTEXPR14 First const& first () const { return static_cast(*this); } C4_ALWAYS_INLINE C4_CONSTEXPR14 Second & second() { return reinterpret_cast(*this); } // NOLINT C4_ALWAYS_INLINE C4_CONSTEXPR14 Second const& second() const { return reinterpret_cast(*this); } // NOLINT }; template struct tight_pair : public First, public Second { using first_type = First; using second_type = Second; tight_pair() : First(), Second() {} tight_pair(First const& f, Second const& s) : First(f), Second(s) {} C4_ALWAYS_INLINE C4_CONSTEXPR14 First & first () { return static_cast(*this); } C4_ALWAYS_INLINE C4_CONSTEXPR14 First const& first () const { return static_cast(*this); } C4_ALWAYS_INLINE C4_CONSTEXPR14 Second & second() { return static_cast(*this); } C4_ALWAYS_INLINE C4_CONSTEXPR14 Second const& second() const { return static_cast(*this); } }; template struct tight_pair : public First { Second m_second; using first_type = First; using second_type = Second; tight_pair() : First() {} tight_pair(First const& f, Second const& s) : First(f), m_second(s) {} C4_ALWAYS_INLINE C4_CONSTEXPR14 First & first () { return static_cast(*this); } C4_ALWAYS_INLINE C4_CONSTEXPR14 First const& first () const { return static_cast(*this); } C4_ALWAYS_INLINE C4_CONSTEXPR14 Second & second() { return m_second; } C4_ALWAYS_INLINE C4_CONSTEXPR14 Second const& second() const { return m_second; } }; template struct tight_pair : public First { Second m_second; using first_type = First; using second_type = Second; tight_pair() : First(), m_second() {} tight_pair(First const& f, Second const& s) : First(f), m_second(s) {} C4_ALWAYS_INLINE C4_CONSTEXPR14 First & first () { return static_cast(*this); } C4_ALWAYS_INLINE C4_CONSTEXPR14 First const& first () const { return static_cast(*this); } C4_ALWAYS_INLINE C4_CONSTEXPR14 Second & second() { return m_second; } C4_ALWAYS_INLINE C4_CONSTEXPR14 Second const& second() const { return m_second; } }; template struct tight_pair : public Second { First m_first; using first_type = First; using second_type = Second; tight_pair() : Second(), m_first() {} tight_pair(First const& f, Second const& s) : Second(s), m_first(f) {} C4_ALWAYS_INLINE C4_CONSTEXPR14 First & first () { return m_first; } C4_ALWAYS_INLINE C4_CONSTEXPR14 First const& first () const { return m_first; } C4_ALWAYS_INLINE C4_CONSTEXPR14 Second & second() { return static_cast(*this); } C4_ALWAYS_INLINE C4_CONSTEXPR14 Second const& second() const { return static_cast(*this); } }; } // namespace detail template using tight_pair = detail::tight_pair()>; C4_SUPPRESS_WARNING_GCC_CLANG_POP } // namespace c4 // NOLINTEND(google-runtime-int) #endif /* C4_MEMORY_UTIL_HPP_ */ // (end ext/c4core.src/c4/memory_util.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/blob.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_BLOB_HPP_ #define C4_BLOB_HPP_ #ifndef C4_ERROR_HPP_ //#include "c4/error.hpp" // amalgamate: remove include #error "amalgamate: c4/error.hpp must have been amalgamated before this point" #endif #ifndef C4_TYPES_HPP_ //#include "c4/types.hpp" // amalgamate: remove include #error "amalgamate: c4/types.hpp must have been amalgamated before this point" #endif #ifndef C4_MEMORY_UTIL_HPP_ //#include "c4/memory_util.hpp" // amalgamate: remove include #error "amalgamate: c4/memory_util.hpp must have been amalgamated before this point" #endif /** @file blob.hpp Mutable and immutable binary data blobs. */ namespace c4 { template struct blob_; namespace detail { template struct is_blob_type : std::false_type {}; template struct is_blob_type> : std::true_type {}; template struct is_blob_value_type : std::integral_constant::value || std::is_trivially_copyable::value)> {}; } // namespace // NOLINTBEGIN(cppcoreguidelines-special-member-functions,hicpp-special-member-functions) template struct blob_ { static_assert(std::is_same::value || std::is_same::value, "must be either byte or cbyte"); static_assert(sizeof(T) == 1u, "must be either byte or cbyte"); public: T * buf; size_t len; public: C4_ALWAYS_INLINE blob_() noexcept = default; C4_ALWAYS_INLINE blob_(blob_ const& that) noexcept = default; C4_ALWAYS_INLINE blob_(blob_ && that) noexcept = default; C4_ALWAYS_INLINE blob_& operator=(blob_ && that) noexcept = default; C4_ALWAYS_INLINE blob_& operator=(blob_ const& that) noexcept = default; template::value && std::is_same::type, T>::value, U>::type> C4_ALWAYS_INLINE blob_(blob_ const& that) noexcept : buf(that.buf), len(that.len) {} // NOLINT template::value && std::is_same::type, T>::value, U>::type> C4_ALWAYS_INLINE blob_(blob_ && that) noexcept : buf(that.buf), len(that.len) {} // NOLINT template::value && std::is_same::type, T>::value, U>::type> C4_ALWAYS_INLINE blob_& operator=(blob_ && that) noexcept { buf = that.buf; len = that.len; } // NOLINT template::value && std::is_same::type, T>::value, U>::type> C4_ALWAYS_INLINE blob_& operator=(blob_ const& that) noexcept { buf = that.buf; len = that.len; } // NOLINT C4_ALWAYS_INLINE blob_(void *ptr, size_t n) noexcept : buf(reinterpret_cast(ptr)), len(n) {} // NOLINT C4_ALWAYS_INLINE blob_(void const *ptr, size_t n) noexcept : buf(reinterpret_cast(ptr)), len(n) {} // NOLINT #define C4_REQUIRE_BLOBTYPE_(ty) typename std::enable_if<((!detail::is_blob_type::value) && (detail::is_blob_value_type::value)), T>::type template C4_ALWAYS_INLINE blob_(U &var) noexcept : buf(reinterpret_cast(&var)), len(sizeof(U)) {} // NOLINT template C4_ALWAYS_INLINE blob_(U *ptr, size_t n) noexcept : buf(reinterpret_cast(ptr)), len(sizeof(U) * n) { C4_ASSERT(is_aligned(ptr)); } // NOLINT template C4_ALWAYS_INLINE blob_& operator= (U &var) noexcept { buf = reinterpret_cast(&var); len = sizeof(U); return *this; } // NOLINT template C4_ALWAYS_INLINE blob_(U (&arr)[N]) noexcept : buf(reinterpret_cast(arr)), len(sizeof(U) * N) {} // NOLINT template C4_ALWAYS_INLINE blob_& operator= (U (&arr)[N]) noexcept { buf = reinterpret_cast(arr); len = sizeof(U) * N; return *this; } // NOLINT #undef C4_REQUIRE_BLOBTYPE_ }; // NOLINTEND(cppcoreguidelines-special-member-functions,hicpp-special-member-functions) /** an immutable binary blob */ using cblob = blob_; /** a mutable binary blob */ using blob = blob_< byte>; C4_MUST_BE_TRIVIAL_COPY(blob); C4_MUST_BE_TRIVIAL_COPY(cblob); } // namespace c4 #endif // C4_BLOB_HPP_ // (end ext/c4core.src/c4/blob.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/substr_fwd.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_SUBSTR_FWD_HPP_ #define C4_SUBSTR_FWD_HPP_ namespace c4 { #ifndef __DOXYGEN__ template struct basic_substring; using csubstr = basic_substring; using substr = basic_substring; template struct is_string; template struct is_writeable_string; #endif // !__DOXYGEN__ } // namespace c4 #endif /* C4_SUBSTR_FWD_HPP_ */ // (end ext/c4core.src/c4/substr_fwd.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/substr.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_SUBSTR_HPP_ #define C4_SUBSTR_HPP_ /** @file substr.hpp read+write string views */ //#include // amalgamate: included above #include //#include // amalgamate: included above #ifndef C4_EXPORT_HPP_ //#include "c4/export.hpp" // amalgamate: remove include #error "amalgamate: c4/export.hpp must have been amalgamated before this point" #endif /* C4_EXPORT_HPP_ */ #ifndef C4_LANGUAGE_HPP_ //#include "c4/language.hpp" // amalgamate: remove include #error "amalgamate: c4/language.hpp must have been amalgamated before this point" #endif /* C4_LANGUAGE_HPP_ */ #ifndef C4_ERROR_HPP_ //#include "c4/error.hpp" // amalgamate: remove include #error "amalgamate: c4/error.hpp must have been amalgamated before this point" #endif /* C4_ERROR_HPP_ */ #ifndef C4_SUBSTR_FWD_HPP_ //#include "c4/substr_fwd.hpp" // amalgamate: remove include #error "amalgamate: c4/substr_fwd.hpp must have been amalgamated before this point" #endif /* C4_SUBSTR_FWD_HPP_ */ C4_SUPPRESS_WARNING_GCC_CLANG_PUSH C4_SUPPRESS_WARNING_GCC_CLANG("-Wold-style-cast") C4_SUPPRESS_WARNING_GCC("-Wuseless-cast") C4_SUPPRESS_WARNING_GCC("-Wtype-limits") // disable warnings on size_t>=0, used heavily in assertions below. These assertions are a preparation step for providing the index type as a template parameter. namespace c4 { /** @cond dev */ namespace detail { // implementation of is_string/is_writeable_string template struct is_string : public std::false_type {}; template struct is_writeable_string : public std::false_type {}; template<> struct is_string : public std::true_type {}; template<> struct is_writeable_string : public std::true_type {}; template<> struct is_string : public std::true_type {}; template<> struct is_writeable_string : public std::false_type {}; template struct is_string : public std::true_type {}; template struct is_writeable_string : public std::false_type {}; template struct is_string : public std::true_type {}; template struct is_writeable_string : public std::true_type {}; template struct is_string : public std::true_type {}; template struct is_writeable_string : public std::false_type {}; template struct is_string : public std::true_type {}; template struct is_writeable_string : public std::true_type {}; template struct is_string : public std::true_type {}; template struct is_writeable_string : public std::false_type {}; template struct is_string : public std::true_type {}; template struct is_writeable_string : public std::true_type {}; // utility trait to remove restrict keyword template struct remove_restrict { using type = T; }; template struct remove_restrict { using type = T*; }; template struct remove_restrict { using type = T&; }; // clang<8 does not match this!!! // utility trait to remove references from pointer reference template struct remove_ptrref { using type = T; }; template struct remove_ptrref { using type = T*; }; template struct remove_ptrref { using type = T* const; }; template struct remove_ptrref { using type = T *C4_RESTRICT; }; template struct remove_ptrref { using type = T *C4_RESTRICT const; }; // utility trait to remove const, but only from pointer types template struct remove_ptrconst { using type = T; }; template struct remove_ptrconst { using type = T*; }; template struct remove_ptrconst { using type = T* C4_RESTRICT; }; // clean a type of qualifiers for enabling // SFINAE on raw-pointer types irrespective of the qualifiers. template struct bare_pointer_type { using type = typename remove_restrict< typename remove_ptrconst< typename remove_ptrref< T>::type >::type >::type; }; template struct _is_comp_char_ptr : std::integral_constant< bool, std::is_same::type *>::value || std::is_same::value> {}; template struct _can_borrow_char_ptr : std::integral_constant< bool, _is_comp_char_ptr::value && ( std::is_const::value || ! std::is_const::type>::value )> {}; template static inline void _do_reverse(C *C4_RESTRICT first, C *C4_RESTRICT last) noexcept { while(last > first) { C tmp = *last; *last-- = *first; *first++ = tmp; } } } // namespace detail /** @endcond */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @defgroup string_traits String traits classes * @{ */ /** a traits class to mark a type as a string type, meaning @ref * c4::to_csubstr() can be used directly instead of @ref * c4::to_chars() when formatting the string. */ template struct is_string : public detail::is_string< typename detail::bare_pointer_type::type > {}; /** a traits class to mark a type as a writeable string type, meaning * @ref c4::to_substr() can be used directly instead of @ref * c4::from_chars() when reading the string. */ template struct is_writeable_string : public detail::is_writeable_string< typename detail::bare_pointer_type::type > {}; template struct is_string> : public std::true_type {}; template<> struct is_string> : public std::true_type {}; template<> struct is_string> : public std::true_type {}; template<> struct is_writeable_string> : public std::true_type {}; template<> struct is_writeable_string> : public std::true_type {}; /* traits class to query whether a pointer-type stripped of qualifiers * like `C4_RESTRICT` is one of `char*` or `const char*`, compatible * with a destination value type (one of char or const char). * * This is used in @ref c4::basic_substring to enable SFINAE on * `char*` and `const char*` overloads and prevent these of overriding * coexisting array overloads. * * FromPointerType is the SFINAE-d type, and ToValueType is the char * or const char destination type. See @ref c4::basic_substring below * for examples of usage. */ template struct is_compatible_char_ptr : detail::_is_comp_char_ptr< typename detail::bare_pointer_type::type, ToValueType> {}; /* traits class to query whether a pointer-type stripped of qualifiers * like or `C4_RESTRICT` is one of `char*` or `const char*`, * compatible with a destination value type (one of char or const * char) and further can be used to initialize a substring of that * destination value type. * * This is used in @ref c4::basic_substring to enable SFINAE on * `char*` and `const char*` overloads and prevent these of overriding * coexisting array overloads. * * FromPointerType is the SFINAE-d type, and ToValueType is the char * or const char destination type. See @ref c4::basic_substring below * for examples of usage. */ template struct can_borrow_char_ptr : detail::_can_borrow_char_ptr< typename detail::bare_pointer_type::type, ToValueType> {}; /** @} */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @defgroup doc_substr Substring: read/write string views * @{ */ /** a non-owning string-view, consisting of a character pointer * and a length. * * @note The pointer is explicitly restricted. * * @see a [quickstart * sample](https://rapidyaml.readthedocs.io/latest/doxygen/group__doc__quickstart.html#ga43e253da0692c13967019446809c1113) * in rapidyaml's documentation. */ template struct basic_substring // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions) { public: /** a restricted pointer to the first character of the substring */ C * C4_RESTRICT str; /** the length of the substring */ size_t len; public: /** @name Types */ /** @{ */ using CC = typename std::add_const::type; //!< CC=const char using NCC_ = typename std::remove_const::type; //!< NCC_=non const char using ro_substr = basic_substring; using rw_substr = basic_substring; using value_type = C; using char_type = C; using size_type = size_t; using iterator = C*; using const_iterator = CC*; enum : size_t { npos = (size_t)-1, NONE = (size_t)-1 }; /// convert automatically from substr (of C) to csubstr (of const C) template C4_ALWAYS_INLINE operator typename std::enable_if::value, ro_substr const&>::type () const noexcept { return *(ro_substr const*)this; // don't call the str+len ctor because it does a check } /** @} */ public: /** @name Default construction and assignment */ /** @{ */ C4_ALWAYS_INLINE constexpr basic_substring() noexcept : str(), len() {} C4_ALWAYS_INLINE basic_substring(basic_substring const&) noexcept = default; C4_ALWAYS_INLINE basic_substring(basic_substring &&) noexcept = default; C4_ALWAYS_INLINE basic_substring(std::nullptr_t) noexcept : str(nullptr), len(0) {} C4_ALWAYS_INLINE basic_substring& operator= (basic_substring const&) noexcept = default; C4_ALWAYS_INLINE basic_substring& operator= (basic_substring &&) noexcept = default; C4_ALWAYS_INLINE basic_substring& operator= (std::nullptr_t) noexcept { str = nullptr; len = 0; return *this; } C4_ALWAYS_INLINE void clear() noexcept { str = nullptr; len = 0; } /** @} */ public: /** @name Construction and assignment from characters with the same type */ /** @{ */ /** Construct from an array. * @warning the input string need not be zero terminated, but the * length is taken as if the string was zero terminated */ template C4_ALWAYS_INLINE constexpr basic_substring(C (&s_)[N]) noexcept : str(s_), len(N-1) {} /** Construct from a pointer and length. * @warning the input string need not be zero terminated. */ C4_ALWAYS_INLINE basic_substring(C *s_, size_t len_) noexcept : str(s_), len(len_) { C4_ASSERT(str || !len_); } /** Construct from two pointers. * @warning the end pointer MUST BE larger than or equal to the begin pointer * @warning the input string need not be zero terminated */ C4_ALWAYS_INLINE basic_substring(C *beg_, C *end_) noexcept : str(beg_), len(static_cast(end_ - beg_)) { C4_ASSERT(end_ >= beg_); } /** Construct from a C-string (zero-terminated string) * @warning the input string MUST BE zero terminated. * @warning will call strlen() * @note this overload uses SFINAE to prevent it from overriding the array ctor * @see For a more detailed explanation on why the plain overloads cannot * coexist, see http://cplusplus.bordoon.com/specializeForCharacterArrays.html */ template::value, int>::type=0> C4_ALWAYS_INLINE basic_substring(CharPtr s_) noexcept : str(s_), len(s_ ? strlen(s_) : 0) {} /** Assign from an array. * @warning the input string need not be zero terminated, but the * length is taken as if the string was zero terminated */ template C4_ALWAYS_INLINE void assign(C (&s_)[N]) noexcept { str = s_; len = (N-1); } /** Assign from a pointer and length. * @warning the input string need not be zero terminated. */ C4_ALWAYS_INLINE void assign(C *s_, size_t len_) noexcept { str = s_; len = len_; C4_ASSERT(str || !len_); } /** Assign from two pointers. * @warning the end pointer MUST BE larger than or equal to the begin pointer * @warning the input string need not be zero terminated. */ C4_ALWAYS_INLINE void assign(C *beg_, C *end_) noexcept { C4_ASSERT(end_ >= beg_); str = beg_; len = static_cast(end_ - beg_); } /** Assign from a C-string (zero-terminated string of type const C* or C*) * @warning the input string must be zero terminated. * @warning will call strlen() * @note this overload uses SFINAE to prevent it from overriding the array assignment * @see For a more detailed explanation on why the plain pointer overloads cannot * coexist with the array overloads, see http://cplusplus.bordoon.com/specializeForCharacterArrays.html */ template::value, int>::type=0> C4_ALWAYS_INLINE void assign(CharPtr s_) noexcept { // the SFINAE is catching const types, so that on calls like // s.assign(const char*) we can do a static_assert, and so // the user will see an informative error message static_assert(can_borrow_char_ptr::value, "string pointer is not mutable"); str = s_; len = (s_ ? strlen(s_) : 0); } /** Assign from an array. * @warning the input string need not be zero terminated. */ template C4_ALWAYS_INLINE basic_substring& operator= (C (&s_)[N]) noexcept { str = s_; len = (N-1); return *this; } /** Assign from a C-string (zero-terminated string of type const C* or C*) * @warning the input string MUST BE zero terminated. * @warning will call strlen() * @note this overload uses SFINAE to prevent it from overriding the array assignment * @see For a more detailed explanation on why the plain pointer overloads cannot * coexist with the array overloads, see http://cplusplus.bordoon.com/specializeForCharacterArrays.html */ template::value, int>::type=0> C4_ALWAYS_INLINE basic_substring& operator= (CharPtr s_) noexcept { // the SFINAE is catching const types, so that on calls like // substr(const char*) we can do a static_assert, and so // the user will see an informative error message static_assert(can_borrow_char_ptr::value, "string pointer is not mutable"); str = s_; len = s_ ? strlen(s_) : 0; return *this; } /** @} */ public: /** @name Standard accessor methods */ /** @{ */ C4_ALWAYS_INLINE C4_PURE bool has_str() const noexcept { return ! empty() && str[0] != C(0); } C4_ALWAYS_INLINE C4_PURE bool empty() const noexcept { return (len == 0 || str == nullptr); } C4_ALWAYS_INLINE C4_PURE bool not_empty() const noexcept { return (len != 0 && str != nullptr); } C4_ALWAYS_INLINE C4_PURE size_t size() const noexcept { return len; } C4_ALWAYS_INLINE C4_PURE iterator begin() noexcept { return str; } C4_ALWAYS_INLINE C4_PURE iterator end () noexcept { return str + len; } C4_ALWAYS_INLINE C4_PURE const_iterator begin() const noexcept { return str; } C4_ALWAYS_INLINE C4_PURE const_iterator end () const noexcept { return str + len; } C4_ALWAYS_INLINE C4_PURE C * data() noexcept { return str; } C4_ALWAYS_INLINE C4_PURE C const* data() const noexcept { return str; } C4_ALWAYS_INLINE C4_PURE C & operator[] (size_t i) noexcept { C4_ASSERT(i >= 0 && i < len); return str[i]; } C4_ALWAYS_INLINE C4_PURE C const& operator[] (size_t i) const noexcept { C4_ASSERT(i >= 0 && i < len); return str[i]; } C4_ALWAYS_INLINE C4_PURE C & front() noexcept { C4_ASSERT(len > 0 && str != nullptr); return *str; } C4_ALWAYS_INLINE C4_PURE C const& front() const noexcept { C4_ASSERT(len > 0 && str != nullptr); return *str; } C4_ALWAYS_INLINE C4_PURE C & back() noexcept { C4_ASSERT(len > 0 && str != nullptr); return *(str + len - 1); } C4_ALWAYS_INLINE C4_PURE C const& back() const noexcept { C4_ASSERT(len > 0 && str != nullptr); return *(str + len - 1); } /** @} */ public: /** @name Comparison methods */ /** @{ */ C4_ALWAYS_INLINE C4_PURE int compare(C const c) const noexcept { C4_XASSERT((str != nullptr) || len == 0); if C4_LIKELY(str != nullptr && len > 0) return (*str != c) ? *str - c : (static_cast(len) - 1); else return -1; } C4_PURE int compare(C const* C4_RESTRICT that, size_t sz) const noexcept { C4_SUPPRESS_WARNING_GCC_PUSH #if defined(__GNUC__) && (__GNUC__ >= 6) C4_SUPPRESS_WARNING_GCC("-Wnull-dereference") #endif C4_XASSERT(that || sz == 0); C4_XASSERT(str || len == 0); if C4_LIKELY(str && that) { { const size_t min = len < sz ? len : sz; for(size_t i = 0; i < min; ++i) if(str[i] != that[i]) return str[i] < that[i] ? -1 : 1; } if(len < sz) return -1; else if(len == sz) return 0; else return 1; } else if(len == sz) { C4_XASSERT(len == 0 && sz == 0); return 0; } return len < sz ? -1 : 1; C4_SUPPRESS_WARNING_GCC_POP } template C4_ALWAYS_INLINE C4_PURE auto compare(CharPtr c_str) const noexcept -> typename std::enable_if::value, int>::type { return compare(c_str, strlen(c_str)); } template C4_ALWAYS_INLINE C4_PURE int compare(basic_substring const that) const noexcept { return this->compare(that.str, that.len); } C4_ALWAYS_INLINE C4_PURE bool operator== (std::nullptr_t) const noexcept { return str == nullptr; } C4_ALWAYS_INLINE C4_PURE bool operator!= (std::nullptr_t) const noexcept { return str != nullptr; } C4_ALWAYS_INLINE C4_PURE bool operator== (C const c) const noexcept { return this->compare(c) == 0; } C4_ALWAYS_INLINE C4_PURE bool operator!= (C const c) const noexcept { return this->compare(c) != 0; } C4_ALWAYS_INLINE C4_PURE bool operator< (C const c) const noexcept { return this->compare(c) < 0; } C4_ALWAYS_INLINE C4_PURE bool operator> (C const c) const noexcept { return this->compare(c) > 0; } C4_ALWAYS_INLINE C4_PURE bool operator<= (C const c) const noexcept { return this->compare(c) <= 0; } C4_ALWAYS_INLINE C4_PURE bool operator>= (C const c) const noexcept { return this->compare(c) >= 0; } template C4_ALWAYS_INLINE C4_PURE bool operator== (basic_substring const that) const noexcept { return this->compare(that) == 0; } template C4_ALWAYS_INLINE C4_PURE bool operator!= (basic_substring const that) const noexcept { return this->compare(that) != 0; } template C4_ALWAYS_INLINE C4_PURE bool operator< (basic_substring const that) const noexcept { return this->compare(that) < 0; } template C4_ALWAYS_INLINE C4_PURE bool operator> (basic_substring const that) const noexcept { return this->compare(that) > 0; } template C4_ALWAYS_INLINE C4_PURE bool operator<= (basic_substring const that) const noexcept { return this->compare(that) <= 0; } template C4_ALWAYS_INLINE C4_PURE bool operator>= (basic_substring const that) const noexcept { return this->compare(that) >= 0; } template C4_ALWAYS_INLINE C4_PURE bool operator== (const char (&arr)[N]) const noexcept { return this->compare(arr, N-1) == 0; } template C4_ALWAYS_INLINE C4_PURE bool operator!= (const char (&arr)[N]) const noexcept { return this->compare(arr, N-1) != 0; } template C4_ALWAYS_INLINE C4_PURE bool operator< (const char (&arr)[N]) const noexcept { return this->compare(arr, N-1) < 0; } template C4_ALWAYS_INLINE C4_PURE bool operator> (const char (&arr)[N]) const noexcept { return this->compare(arr, N-1) > 0; } template C4_ALWAYS_INLINE C4_PURE bool operator<= (const char (&arr)[N]) const noexcept { return this->compare(arr, N-1) <= 0; } template C4_ALWAYS_INLINE C4_PURE bool operator>= (const char (&arr)[N]) const noexcept { return this->compare(arr, N-1) >= 0; } template C4_ALWAYS_INLINE C4_PURE auto operator== (CharPtr c_str) const noexcept -> typename std::enable_if::value, int>::type{ return this->compare(c_str, strlen(c_str)) == 0; } template C4_ALWAYS_INLINE C4_PURE auto operator!= (CharPtr c_str) const noexcept -> typename std::enable_if::value, int>::type{ return this->compare(c_str, strlen(c_str)) != 0; } template C4_ALWAYS_INLINE C4_PURE auto operator< (CharPtr c_str) const noexcept -> typename std::enable_if::value, int>::type{ return this->compare(c_str, strlen(c_str)) < 0; } template C4_ALWAYS_INLINE C4_PURE auto operator> (CharPtr c_str) const noexcept -> typename std::enable_if::value, int>::type{ return this->compare(c_str, strlen(c_str)) > 0; } template C4_ALWAYS_INLINE C4_PURE auto operator<= (CharPtr c_str) const noexcept -> typename std::enable_if::value, int>::type{ return this->compare(c_str, strlen(c_str)) <= 0; } template C4_ALWAYS_INLINE C4_PURE auto operator>= (CharPtr c_str) const noexcept -> typename std::enable_if::value, int>::type{ return this->compare(c_str, strlen(c_str)) >= 0; } /** @} */ public: /** @name Sub-selection methods */ /** @{ */ /** true if *this is a substring of that (ie, from the same buffer) */ C4_ALWAYS_INLINE C4_PURE bool is_sub(ro_substr const that) const noexcept { return that.is_super(*this); } /** true if that is a substring of *this (ie, from the same buffer) */ C4_ALWAYS_INLINE C4_PURE bool is_super(ro_substr const that) const noexcept { if C4_LIKELY(len > 0) return that.str >= str && that.str+that.len <= str+len; else return that.len == 0 && that.str == str && str != nullptr; } /** true if there is overlap of at least one element between that and *this */ C4_ALWAYS_INLINE C4_PURE bool overlaps(ro_substr const that) const noexcept { // thanks @timwynants return that.str+that.len > str && that.str < str+len; } public: /** return [first,len[ */ C4_ALWAYS_INLINE C4_PURE basic_substring sub(size_t first) const noexcept { C4_ASSERT(first >= 0 && first <= len); return basic_substring(str + first, len - first); } /** return [first,first+num[. If num==npos, return [first,len[ */ C4_ALWAYS_INLINE C4_PURE basic_substring sub(size_t first, size_t num) const noexcept { C4_ASSERT(first >= 0 && first <= len); C4_ASSERT((num >= 0 && num <= len) || (num == npos)); size_t rnum = num != npos ? num : len - first; C4_ASSERT((first >= 0 && first + rnum <= len) || (num == 0)); return basic_substring(str + first, rnum); } /** return [first,last[. If last==npos, return [first,len[ */ C4_ALWAYS_INLINE C4_PURE basic_substring range(size_t first, size_t last=npos) const noexcept { C4_ASSERT(first >= 0 && first <= len); last = last != npos ? last : len; C4_ASSERT(first <= last); C4_ASSERT(last >= 0 && last <= len); return basic_substring(str + first, last - first); } /** return the first @p num elements: [0,num[*/ C4_ALWAYS_INLINE C4_PURE basic_substring first(size_t num) const noexcept { C4_ASSERT(num <= len || num == npos); return basic_substring(str, num != npos ? num : len); } /** return the last @p num elements: [len-num,len[*/ C4_ALWAYS_INLINE C4_PURE basic_substring last(size_t num) const noexcept { C4_ASSERT(num <= len || num == npos); return num != npos ? basic_substring(str + len - num, num) : *this; } /** offset from the ends: return [left,len-right[ ; ie, trim a number of characters from the left and right. This is equivalent to python's negative list indices. */ C4_ALWAYS_INLINE C4_PURE basic_substring offs(size_t left, size_t right) const noexcept { C4_ASSERT(left >= 0 && left <= len); C4_ASSERT(right >= 0 && right <= len); C4_ASSERT(left <= len - right + 1); return basic_substring(str + left, len - right - left); } /** return [0, pos[ . Same as .first(pos), but provided for compatibility with .right_of() */ C4_ALWAYS_INLINE C4_PURE basic_substring left_of(size_t pos) const noexcept { C4_ASSERT(pos <= len || pos == npos); return (pos != npos) ? basic_substring(str, pos) : *this; } /** return [0, pos+include_pos[ . Same as .first(pos+1), but provided for compatibility with .right_of() */ C4_ALWAYS_INLINE C4_PURE basic_substring left_of(size_t pos, bool include_pos) const noexcept { C4_ASSERT(pos <= len || pos == npos); return (pos != npos) ? basic_substring(str, pos+include_pos) : *this; } /** return [pos+1, len[ */ C4_ALWAYS_INLINE C4_PURE basic_substring right_of(size_t pos) const noexcept { C4_ASSERT(pos <= len || pos == npos); return (pos != npos) ? basic_substring(str + (pos + 1), len - (pos + 1)) : basic_substring(str + len, size_t(0)); } /** return [pos+!include_pos, len[ */ C4_ALWAYS_INLINE C4_PURE basic_substring right_of(size_t pos, bool include_pos) const noexcept { C4_ASSERT(pos <= len || pos == npos); return (pos != npos) ? basic_substring(str + (pos + !include_pos), len - (pos + !include_pos)) : basic_substring(str + len, size_t(0)); } public: /** given @p subs a substring of the current string, get the * portion of the current string to the left of it */ C4_ALWAYS_INLINE C4_PURE basic_substring left_of(ro_substr const subs) const noexcept { C4_ASSERT(is_super(subs) || subs.empty()); auto ssb = subs.begin(); auto b = begin(); auto e = end(); if(ssb >= b && ssb <= e) return sub(0, static_cast(ssb - b)); else return sub(0, 0); } /** given @p subs a substring of the current string, get the * portion of the current string to the right of it */ C4_ALWAYS_INLINE C4_PURE basic_substring right_of(ro_substr const subs) const noexcept { C4_ASSERT(is_super(subs) || subs.empty()); auto sse = subs.end(); auto b = begin(); auto e = end(); if(sse >= b && sse <= e) return sub(static_cast(sse - b), static_cast(e - sse)); else return sub(0, 0); } /** @} */ public: /** @name Removing characters (trim()) / patterns (strip()) from the tips of the string */ /** @{ */ /** trim left */ basic_substring triml(const C c) const { if( ! empty()) { size_t pos = first_not_of(c); if(pos != npos) return sub(pos); } return sub(0, 0); } /** trim left ANY of the characters. * @see stripl() to remove a pattern from the left */ basic_substring triml(ro_substr chars) const { if( ! empty()) { size_t pos = first_not_of(chars); if(pos != npos) return sub(pos); } return sub(0, 0); } /** trim the character c from the right */ basic_substring trimr(const C c) const { if( ! empty()) { size_t pos = last_not_of(c, npos); if(pos != npos) return sub(0, pos+1); } return sub(0, 0); } /** trim right ANY of the characters * @see stripr() to remove a pattern from the right */ basic_substring trimr(ro_substr chars) const { if( ! empty()) { size_t pos = last_not_of(chars, npos); if(pos != npos) return sub(0, pos+1); } return sub(0, 0); } /** trim the character c left and right */ basic_substring trim(const C c) const { return triml(c).trimr(c); } /** trim left and right ANY of the characters * @see strip() to remove a pattern from the left and right */ basic_substring trim(ro_substr const chars) const { return triml(chars).trimr(chars); } /** remove a pattern from the left * @see triml() to remove characters*/ basic_substring stripl(ro_substr pattern) const { if( ! begins_with(pattern)) return *this; return sub(pattern.len < len ? pattern.len : len); } /** remove a pattern from the right * @see trimr() to remove characters*/ basic_substring stripr(ro_substr pattern) const { if( ! ends_with(pattern)) return *this; return left_of(len - (pattern.len < len ? pattern.len : len)); } /** @} */ public: /** @name Lookup methods */ /** @{ */ size_t find(const C c, size_t start_pos=0) const { return first_of(c, start_pos); } size_t find(ro_substr pattern, size_t start_pos=0) const { C4_ASSERT(start_pos == npos || (start_pos >= 0 && start_pos <= len)); if(len < pattern.len) return npos; for(size_t i = start_pos, e = len - pattern.len + 1; i < e; ++i) { bool gotit = true; for(size_t j = 0; j < pattern.len; ++j) { C4_ASSERT(i + j < len); if(str[i + j] != pattern.str[j]) { gotit = false; break; } } if(gotit) { return i; } } return npos; } public: /** count the number of occurrences of c */ size_t count(const C c, size_t pos=0) const { C4_ASSERT(pos >= 0 && pos <= len); size_t num = 0; pos = find(c, pos); while(pos != npos) { ++num; pos = find(c, pos + 1); } return num; } /** count the number of occurrences of s */ size_t count(ro_substr c, size_t pos=0) const { C4_ASSERT(pos >= 0 && pos <= len); size_t num = 0; pos = find(c, pos); while(pos != npos) { ++num; pos = find(c, pos + c.len); } return num; } /** get the substr consisting of the first occurrence of @p c after @p pos, or an empty substr if none occurs */ basic_substring select(const C c, size_t pos=0) const { pos = find(c, pos); return pos != npos ? sub(pos, 1) : basic_substring(); } /** get the substr consisting of the first occurrence of @p pattern after @p pos, or an empty substr if none occurs */ basic_substring select(ro_substr pattern, size_t pos=0) const { pos = find(pattern, pos); return pos != npos ? sub(pos, pattern.len) : basic_substring(); } public: struct first_of_any_result { size_t which; size_t pos; operator bool() const { return which != NONE && pos != npos; } }; first_of_any_result first_of_any(ro_substr s0, ro_substr s1) const { ro_substr s[2] = {s0, s1}; return first_of_any_iter(&s[0], &s[0] + 2); } first_of_any_result first_of_any(ro_substr s0, ro_substr s1, ro_substr s2) const { ro_substr s[3] = {s0, s1, s2}; return first_of_any_iter(&s[0], &s[0] + 3); } first_of_any_result first_of_any(ro_substr s0, ro_substr s1, ro_substr s2, ro_substr s3) const { ro_substr s[4] = {s0, s1, s2, s3}; return first_of_any_iter(&s[0], &s[0] + 4); } first_of_any_result first_of_any(ro_substr s0, ro_substr s1, ro_substr s2, ro_substr s3, ro_substr s4) const { ro_substr s[5] = {s0, s1, s2, s3, s4}; return first_of_any_iter(&s[0], &s[0] + 5); } template first_of_any_result first_of_any_iter(It first_span, It last_span) const { for(size_t i = 0; i < len; ++i) { size_t curr = 0; for(It it = first_span; it != last_span; ++curr, ++it) { auto const& chars = *it; if((i + chars.len) > len) continue; bool gotit = true; for(size_t j = 0; j < chars.len; ++j) { C4_ASSERT(i + j < len); if(str[i + j] != chars[j]) { gotit = false; break; } } if(gotit) { return {curr, i}; } } } return {NONE, npos}; } public: /** true if the first character of the string is @p c */ bool begins_with(const C c) const noexcept { C4_SUPPRESS_WARNING_GCC_PUSH #if defined(__GNUC__) && (__GNUC__ >= 6) C4_SUPPRESS_WARNING_GCC("-Wnull-dereference") #endif return len && str[0] == c; C4_SUPPRESS_WARNING_GCC_POP } /** true if the first @p num characters of the string are @p c */ bool begins_with(const C c, size_t num) const noexcept { if(len < num) return false; for(size_t i = 0; i < num; ++i) if(str[i] != c) return false; return num > 0; } /** true if the string begins with the given @p pattern */ bool begins_with(ro_substr pattern) const noexcept { if(len < pattern.len) return false; for(size_t i = 0; i < pattern.len; ++i) if(str[i] != pattern.str[i]) return false; return pattern.len > 0; } /** true if the first character of the string is any of the given @p chars */ bool begins_with_any(ro_substr chars) const noexcept { if(len) for(size_t i = 0; i < chars.len; ++i) if(str[0] == chars.str[i]) return true; return false; } /** true if the last character of the string is @p c */ bool ends_with(const C c) const noexcept { return len && str[len-1] == c; } /** true if the last @p num characters of the string are @p c */ bool ends_with(const C c, const size_t num) const noexcept { if(len < num) return false; for(size_t i = len - num; i < len; ++i) if(str[i] != c) return false; return num > 0; } /** true if the string ends with the given @p pattern */ bool ends_with(ro_substr pattern) const noexcept { if(len < pattern.len) return false; for(size_t i = 0, s = len-pattern.len; i < pattern.len; ++i) if(str[s+i] != pattern[i]) return false; return pattern.len > 0; } /** true if the last character of the string is any of the given @p chars */ bool ends_with_any(ro_substr chars) const noexcept { if(len) for(size_t i = 0; i < chars.len; ++i) if(str[len - 1] == chars[i]) return true; return false; } public: /** @return the first position where c is found in the string, or npos if none is found */ size_t first_of(const C c, size_t start=0) const { C4_ASSERT(start == npos || (start >= 0 && start <= len)); for(size_t i = start; i < len; ++i) { if(str[i] == c) return i; } return npos; } /** @return the last position where c is found in the string, or npos if none is found */ size_t last_of(const C c, size_t start=npos) const { C4_ASSERT(start == npos || (start >= 0 && start <= len)); if(start == npos) start = len; for(size_t i = start-1; i != size_t(-1); --i) { if(str[i] == c) return i; } return npos; } /** @return the first position where ANY of the chars is found in the string, or npos if none is found */ size_t first_of(ro_substr chars, size_t start=0) const { C4_ASSERT(start == npos || (start >= 0 && start <= len)); for(size_t i = start; i < len; ++i) { for(size_t j = 0; j < chars.len; ++j) { if(str[i] == chars.str[j]) return i; } } return npos; } /** @return the last position where ANY of the chars is found in the string, or npos if none is found */ size_t last_of(ro_substr chars, size_t start=npos) const { C4_ASSERT(start == npos || (start >= 0 && start <= len)); if(start == npos) start = len; for(size_t i = start-1; i != size_t(-1); --i) { for(size_t j = 0; j < chars.len; ++j) { if(str[i] == chars[j]) return i; } } return npos; } public: size_t first_not_of(const C c) const { for(size_t i = 0; i < len; ++i) { if(str[i] != c) return i; } return npos; } size_t first_not_of(const C c, size_t start) const { C4_ASSERT((start >= 0 && start <= len) || (start == len && len == 0)); for(size_t i = start; i < len; ++i) { if(str[i] != c) return i; } return npos; } size_t last_not_of(const C c) const { for(size_t i = len-1; i != size_t(-1); --i) { if(str[i] != c) return i; } return npos; } size_t last_not_of(const C c, size_t start) const { C4_ASSERT(start == npos || (start >= 0 && start <= len)); if(start == npos) start = len; for(size_t i = start-1; i != size_t(-1); --i) { if(str[i] != c) return i; } return npos; } size_t first_not_of(ro_substr chars) const { for(size_t i = 0; i < len; ++i) { bool gotit = true; for(size_t j = 0; j < chars.len; ++j) { if(str[i] == chars.str[j]) { gotit = false; break; } } if(gotit) { return i; } } return npos; } size_t first_not_of(ro_substr chars, size_t start) const { C4_ASSERT((start >= 0 && start <= len) || (start == len && len == 0)); for(size_t i = start; i < len; ++i) { bool gotit = true; for(size_t j = 0; j < chars.len; ++j) { if(str[i] == chars.str[j]) { gotit = false; break; } } if(gotit) { return i; } } return npos; } size_t last_not_of(ro_substr chars) const { for(size_t i = len-1; i != size_t(-1); --i) { bool gotit = true; for(size_t j = 0; j < chars.len; ++j) { if(str[i] == chars.str[j]) { gotit = false; break; } } if(gotit) { return i; } } return npos; } size_t last_not_of(ro_substr chars, size_t start) const { C4_ASSERT(start == npos || (start >= 0 && start <= len)); if(start == npos) start = len; for(size_t i = start-1; i != size_t(-1); --i) { bool gotit = true; for(size_t j = 0; j < chars.len; ++j) { if(str[i] == chars.str[j]) { gotit = false; break; } } if(gotit) { return i; } } return npos; } /** @} */ public: /** @name Range lookup methods */ /** @{ */ /** get the range delimited by an open-close pair of characters. * @note There must be no nested pairs. * @note No checks for escapes are performed. */ basic_substring pair_range(CC open, CC close) const { size_t b = find(open); if(b == npos) return basic_substring(); size_t e = find(close, b+1); if(e == npos) return basic_substring(); basic_substring ret = range(b, e+1); C4_ASSERT(ret.sub(1).find(open) == npos); return ret; } /** get the range delimited by a single open-close character (eg, quotes). * @note The open-close character can be escaped. */ basic_substring pair_range_esc(CC open_close, CC escape=CC('\\')) { size_t b = find(open_close); if(b == npos) return basic_substring(); for(size_t i = b+1; i < len; ++i) { CC c = str[i]; if(c == open_close) { if(str[i-1] != escape) { return range(b, i+1); } } } return basic_substring(); } /** get the range delimited by an open-close pair of characters, * with possibly nested occurrences. No checks for escapes are * performed. */ basic_substring pair_range_nested(CC open, CC close) const { size_t b = find(open); if(b == npos) return basic_substring(); size_t e, curr = b+1, count = 0; const char both[] = {open, close, '\0'}; while((e = first_of(both, curr)) != npos) { if(str[e] == open) { ++count; curr = e+1; } else if(str[e] == close) { if(count == 0) return range(b, e+1); --count; curr = e+1; } } return basic_substring(); } basic_substring unquoted() const { constexpr const C dq('"'), sq('\''); if(len >= 2 && (str[len - 2] != C('\\')) && ((begins_with(sq) && ends_with(sq)) || (begins_with(dq) && ends_with(dq)))) { return range(1, len -1); } return *this; } /** @} */ public: /** @name Number-matching query methods */ /** @{ */ /** @return true if the substring contents are a floating-point or integer number. * @note any leading or trailing whitespace will return false. */ bool is_number() const { if(empty() || (first_non_empty_span().empty())) return false; if(first_uint_span() == *this) return true; if(first_int_span() == *this) return true; if(first_real_span() == *this) return true; return false; } /** @return true if the substring contents are a real number. * @note any leading or trailing whitespace will return false. */ bool is_real() const { if(empty() || (first_non_empty_span().empty())) return false; if(first_real_span() == *this) return true; return false; } /** @return true if the substring contents are an integer number. * @note any leading or trailing whitespace will return false. */ bool is_integer() const { if(empty() || (first_non_empty_span().empty())) return false; if(first_uint_span() == *this) return true; if(first_int_span() == *this) return true; return false; } /** @return true if the substring contents are an unsigned integer number. * @note any leading or trailing whitespace will return false. */ bool is_unsigned_integer() const { if(empty() || (first_non_empty_span().empty())) return false; if(first_uint_span() == *this) return true; return false; } /** get the first span consisting exclusively of non-empty characters */ basic_substring first_non_empty_span() const { constexpr const ro_substr empty_chars(" \n\r\t"); size_t pos = first_not_of(empty_chars); if(pos == npos) return first(0); auto ret = sub(pos); pos = ret.first_of(empty_chars); return ret.first(pos); } /** get the first span which can be interpreted as an unsigned integer */ basic_substring first_uint_span() const { basic_substring ne = first_non_empty_span(); if(ne.empty()) return ne; if(ne.str[0] == '-') return first(0); size_t skip_start = size_t(ne.str[0] == '+'); return ne._first_integral_span(skip_start); } /** get the first span which can be interpreted as a signed integer */ basic_substring first_int_span() const { basic_substring ne = first_non_empty_span(); if(ne.empty()) return ne; size_t skip_start = size_t(ne.str[0] == '+' || ne.str[0] == '-'); return ne._first_integral_span(skip_start); } basic_substring _first_integral_span(size_t skip_start) const { C4_ASSERT(!empty()); if(skip_start == len) return first(0); C4_ASSERT(skip_start < len); if(len >= skip_start + 3) { if(str[skip_start] != '0') { for(size_t i = skip_start; i < len; ++i) { char c = str[i]; if(c < '0' || c > '9') return i > skip_start && _is_delim_char(c) ? first(i) : first(0); } } else { char next = str[skip_start + 1]; if(next == 'x' || next == 'X') { skip_start += 2; for(size_t i = skip_start; i < len; ++i) { const char c = str[i]; if( ! _is_hex_char(c)) return i > skip_start && _is_delim_char(c) ? first(i) : first(0); } return *this; } else if(next == 'b' || next == 'B') { skip_start += 2; for(size_t i = skip_start; i < len; ++i) { const char c = str[i]; if(c != '0' && c != '1') return i > skip_start && _is_delim_char(c) ? first(i) : first(0); } return *this; } else if(next == 'o' || next == 'O') { skip_start += 2; for(size_t i = skip_start; i < len; ++i) { const char c = str[i]; if(c < '0' || c > '7') return i > skip_start && _is_delim_char(c) ? first(i) : first(0); } return *this; } } } // must be a decimal, or it is not a an number for(size_t i = skip_start; i < len; ++i) { const char c = str[i]; if(c < '0' || c > '9') return i > skip_start && _is_delim_char(c) ? first(i) : first(0); } return *this; } /** get the first span which can be interpreted as a real (floating-point) number */ basic_substring first_real_span() const { basic_substring ne = first_non_empty_span(); if(ne.empty()) return ne; const size_t skip_start = (ne.str[0] == '+' || ne.str[0] == '-'); C4_ASSERT(skip_start == 0 || skip_start == 1); // if we have at least three digits after the leading sign, it // can be decimal, or hex, or bin or oct. Ex: // non-decimal: 0x0, 0b0, 0o0 // decimal: 1.0, 10., 1e1, 100, inf, nan, infinity if(ne.len >= skip_start+3) { // if it does not have leading 0, it must be decimal, or it is not a real if(ne.str[skip_start] != '0') { if(ne.str[skip_start] == 'i') // is it infinity or inf? { basic_substring word = ne._word_follows(skip_start + 1, "nfinity"); if(word.len) return word; return ne._word_follows(skip_start + 1, "nf"); } else if(ne.str[skip_start] == 'n') // is it nan? { return ne._word_follows(skip_start + 1, "an"); } else // must be a decimal, or it is not a real { return ne._first_real_span_dec(skip_start); } } else // starts with 0. is it 0x, 0b or 0o? { const char next = ne.str[skip_start + 1]; // hexadecimal if(next == 'x' || next == 'X') return ne._first_real_span_hex(skip_start + 2); // binary else if(next == 'b' || next == 'B') return ne._first_real_span_bin(skip_start + 2); // octal else if(next == 'o' || next == 'O') return ne._first_real_span_oct(skip_start + 2); // none of the above. may still be a decimal. else return ne._first_real_span_dec(skip_start); // do not skip the 0. } } // less than 3 chars after the leading sign. It is either a // decimal or it is not a real. (cannot be any of 0x0, etc). return ne._first_real_span_dec(skip_start); } /** true if the character is a delimiter character *at the end* */ static constexpr C4_ALWAYS_INLINE C4_CONST bool _is_delim_char(char c) noexcept { return c == ' ' || c == '\n' || c == ']' || c == ')' || c == '}' || c == ',' || c == ';' || c == '\r' || c == '\t' || c == '\0'; } /** true if the character is in [0-9a-fA-F] */ static constexpr C4_ALWAYS_INLINE C4_CONST bool _is_hex_char(char c) noexcept { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); } C4_NO_INLINE C4_PURE basic_substring _word_follows(size_t pos, csubstr word) const noexcept { size_t posend = pos + word.len; if(len >= posend && sub(pos, word.len) == word) if(len == posend || _is_delim_char(str[posend])) return first(posend); return first(0); } // this function is declared inside the class to avoid a VS error with __declspec(dllimport) C4_NO_INLINE C4_PURE basic_substring _first_real_span_dec(size_t pos) const noexcept { bool intchars = false; bool fracchars = false; bool powchars; // integral part for( ; pos < len; ++pos) { const char c = str[pos]; if(c >= '0' && c <= '9') { intchars = true; } else if(c == '.') { ++pos; goto fractional_part_dec; // NOLINT } else if(c == 'e' || c == 'E') { ++pos; goto power_part_dec; // NOLINT } else if(_is_delim_char(c)) { return intchars ? first(pos) : first(0); } else { return first(0); } } // no . or p were found; this is either an integral number // or not a number at all return intchars ? *this : first(0); fractional_part_dec: C4_ASSERT(pos > 0); C4_ASSERT(str[pos - 1] == '.'); for( ; pos < len; ++pos) { const char c = str[pos]; if(c >= '0' && c <= '9') { fracchars = true; } else if(c == 'e' || c == 'E') { ++pos; goto power_part_dec; // NOLINT } else if(_is_delim_char(c)) { return intchars || fracchars ? first(pos) : first(0); } else { return first(0); } } return intchars || fracchars ? *this : first(0); power_part_dec: C4_ASSERT(pos > 0); C4_ASSERT(str[pos - 1] == 'e' || str[pos - 1] == 'E'); // either digits, or +, or - are expected here, followed by more digits. if((len == pos) || ((!intchars) && (!fracchars))) return first(0); if(str[pos] == '-' || str[pos] == '+') ++pos; // skip the sign powchars = false; for( ; pos < len; ++pos) { const char c = str[pos]; if(c >= '0' && c <= '9') powchars = true; else if(powchars && _is_delim_char(c)) return first(pos); else return first(0); } return powchars ? *this : first(0); } // this function is declared inside the class to avoid a VS error with __declspec(dllimport) C4_NO_INLINE C4_PURE basic_substring _first_real_span_hex(size_t pos) const noexcept { bool intchars = false; bool fracchars = false; bool powchars; // integral part for( ; pos < len; ++pos) { const char c = str[pos]; if(_is_hex_char(c)) { intchars = true; } else if(c == '.') { ++pos; goto fractional_part_hex; // NOLINT } else if(c == 'p' || c == 'P') { ++pos; goto power_part_hex; // NOLINT } else if(_is_delim_char(c)) { return intchars ? first(pos) : first(0); } else { return first(0); } } // no . or p were found; this is either an integral number // or not a number at all return intchars ? *this : first(0); fractional_part_hex: C4_ASSERT(pos > 0); C4_ASSERT(str[pos - 1] == '.'); for( ; pos < len; ++pos) { const char c = str[pos]; if(_is_hex_char(c)) { fracchars = true; } else if(c == 'p' || c == 'P') { ++pos; goto power_part_hex; // NOLINT } else if(_is_delim_char(c)) { return intchars || fracchars ? first(pos) : first(0); } else { return first(0); } } return intchars || fracchars ? *this : first(0); power_part_hex: C4_ASSERT(pos > 0); C4_ASSERT(str[pos - 1] == 'p' || str[pos - 1] == 'P'); // either a + or a - is expected here, followed by more chars. // also, using (pos+1) in this check will cause an early // return when no more chars follow the sign. if(len <= (pos+1) || (str[pos] != '+' && str[pos] != '-') || ((!intchars) && (!fracchars))) return first(0); ++pos; // this was the sign. // ... so the (pos+1) ensures that we enter the loop and // hence that there exist chars in the power part powchars = false; for( ; pos < len; ++pos) { const char c = str[pos]; if(c >= '0' && c <= '9') powchars = true; else if(powchars && _is_delim_char(c)) return first(pos); else return first(0); } return *this; } // this function is declared inside the class to avoid a VS error with __declspec(dllimport) C4_NO_INLINE C4_PURE basic_substring _first_real_span_bin(size_t pos) const noexcept { bool intchars = false; bool fracchars = false; bool powchars; // integral part for( ; pos < len; ++pos) { const char c = str[pos]; if(c == '0' || c == '1') { intchars = true; } else if(c == '.') { ++pos; goto fractional_part_bin; // NOLINT } else if(c == 'p' || c == 'P') { ++pos; goto power_part_bin; // NOLINT } else if(_is_delim_char(c)) { return intchars ? first(pos) : first(0); } else { return first(0); } } // no . or p were found; this is either an integral number // or not a number at all return intchars ? *this : first(0); fractional_part_bin: C4_ASSERT(pos > 0); C4_ASSERT(str[pos - 1] == '.'); for( ; pos < len; ++pos) { const char c = str[pos]; if(c == '0' || c == '1') { fracchars = true; } else if(c == 'p' || c == 'P') { ++pos; goto power_part_bin; // NOLINT } else if(_is_delim_char(c)) { return intchars || fracchars ? first(pos) : first(0); } else { return first(0); } } return intchars || fracchars ? *this : first(0); power_part_bin: C4_ASSERT(pos > 0); C4_ASSERT(str[pos - 1] == 'p' || str[pos - 1] == 'P'); // either a + or a - is expected here, followed by more chars. // also, using (pos+1) in this check will cause an early // return when no more chars follow the sign. if(len <= (pos+1) || (str[pos] != '+' && str[pos] != '-') || ((!intchars) && (!fracchars))) return first(0); ++pos; // this was the sign. // ... so the (pos+1) ensures that we enter the loop and // hence that there exist chars in the power part powchars = false; for( ; pos < len; ++pos) { const char c = str[pos]; if(c >= '0' && c <= '9') powchars = true; else if(powchars && _is_delim_char(c)) return first(pos); else return first(0); } return *this; } // this function is declared inside the class to avoid a VS error with __declspec(dllimport) C4_NO_INLINE C4_PURE basic_substring _first_real_span_oct(size_t pos) const noexcept { bool intchars = false; bool fracchars = false; bool powchars; // integral part for( ; pos < len; ++pos) { const char c = str[pos]; if(c >= '0' && c <= '7') { intchars = true; } else if(c == '.') { ++pos; goto fractional_part_oct; // NOLINT } else if(c == 'p' || c == 'P') { ++pos; goto power_part_oct; // NOLINT } else if(_is_delim_char(c)) { return intchars ? first(pos) : first(0); } else { return first(0); } } // no . or p were found; this is either an integral number // or not a number at all return intchars ? *this : first(0); fractional_part_oct: C4_ASSERT(pos > 0); C4_ASSERT(str[pos - 1] == '.'); for( ; pos < len; ++pos) { const char c = str[pos]; if(c >= '0' && c <= '7') { fracchars = true; } else if(c == 'p' || c == 'P') { ++pos; goto power_part_oct; // NOLINT } else if(_is_delim_char(c)) { return intchars || fracchars ? first(pos) : first(0); } else { return first(0); } } return intchars || fracchars ? *this : first(0); power_part_oct: C4_ASSERT(pos > 0); C4_ASSERT(str[pos - 1] == 'p' || str[pos - 1] == 'P'); // either a + or a - is expected here, followed by more chars. // also, using (pos+1) in this check will cause an early // return when no more chars follow the sign. if(len <= (pos+1) || (str[pos] != '+' && str[pos] != '-') || ((!intchars) && (!fracchars))) return first(0); ++pos; // this was the sign. // ... so the (pos+1) ensures that we enter the loop and // hence that there exist chars in the power part powchars = false; for( ; pos < len; ++pos) { const char c = str[pos]; if(c >= '0' && c <= '9') powchars = true; else if(powchars && _is_delim_char(c)) return first(pos); else return first(0); } return *this; } /** @} */ public: /** @name Splitting methods */ /** @{ */ /** returns true if the string has not been exhausted yet, meaning * it's ok to call next_split() again. When no instance of sep * exists in the string, returns the full string. When the input * is an empty string, the output string is the empty string. */ bool next_split(C sep, size_t *C4_RESTRICT start_pos, basic_substring *C4_RESTRICT out) const { if C4_LIKELY(*start_pos < len) { for(size_t i = *start_pos; i < len; i++) { if(str[i] == sep) { out->assign(str + *start_pos, i - *start_pos); *start_pos = i+1; return true; } } out->assign(str + *start_pos, len - *start_pos); *start_pos = len + 1; return true; } else { bool valid = len > 0 && (*start_pos == len); if(valid && str && str[len-1] == sep) { out->assign(str + len, size_t(0)); // the cast is needed to prevent overload ambiguity } else { out->assign(str + len + 1, size_t(0)); // the cast is needed to prevent overload ambiguity } *start_pos = len + 1; return valid; } } private: struct split_proxy_impl { struct split_iterator_impl { split_proxy_impl const* m_proxy; basic_substring m_str; size_t m_pos; NCC_ m_sep; split_iterator_impl(split_proxy_impl const* proxy, size_t pos, C sep) : m_proxy(proxy), m_pos(pos), m_sep(sep) { _tick(); } void _tick() { m_proxy->m_str.next_split(m_sep, &m_pos, &m_str); } split_iterator_impl& operator++ () { _tick(); return *this; } split_iterator_impl operator++ (int) { split_iterator_impl it = *this; _tick(); return it; } // NOLINT basic_substring& operator* () { return m_str; } basic_substring* operator-> () { return &m_str; } bool operator!= (split_iterator_impl const& that) const { return !(this->operator==(that)); } bool operator== (split_iterator_impl const& that) const { C4_XASSERT((m_sep == that.m_sep) && "cannot compare split iterators with different separators"); if(m_str.size() != that.m_str.size()) return false; if(m_str.data() != that.m_str.data()) return false; return m_pos == that.m_pos; } }; basic_substring m_str; size_t m_start_pos; C m_sep; split_proxy_impl(basic_substring str_, size_t start_pos, C sep) : m_str(str_), m_start_pos(start_pos), m_sep(sep) { } split_iterator_impl begin() const { auto it = split_iterator_impl(this, m_start_pos, m_sep); return it; } split_iterator_impl end() const { size_t pos = m_str.size() + 1; auto it = split_iterator_impl(this, pos, m_sep); return it; } }; public: using split_proxy = split_proxy_impl; /** a view into the splits */ split_proxy split(C sep, size_t start_pos=0) const { C4_XASSERT((start_pos >= 0 && start_pos < len) || empty()); auto ss = sub(0, len); auto it = split_proxy(ss, start_pos, sep); return it; } public: /** pop right: return the first split from the right. Use * gpop_left() to get the reciprocal part. */ basic_substring pop_right(C sep=C('/'), bool skip_empty=false) const { if C4_LIKELY(len > 1) { auto pos = last_of(sep); if(pos != npos) { if(pos + 1 < len) // does not end with sep { return sub(pos + 1); // return from sep to end } else // the string ends with sep { if( ! skip_empty) { return sub(pos + 1, 0); } auto ppos = last_not_of(sep); // skip repeated seps if(ppos == npos) // the string is all made of seps { return sub(0, 0); } // find the previous sep auto pos0 = last_of(sep, ppos); if(pos0 == npos) // only the last sep exists { return sub(0); // return the full string (because skip_empty is true) } ++pos0; return sub(pos0); } } else // no sep was found, return the full string { return *this; } } else if(len == 1) { if(begins_with(sep)) { return sub(0, 0); } return *this; } else // an empty string { return basic_substring(); } } /** return the first split from the left. Use gpop_right() to get * the reciprocal part. */ basic_substring pop_left(C sep = C('/'), bool skip_empty=false) const { if C4_LIKELY(len > 1) { auto pos = first_of(sep); if(pos != npos) { if(pos > 0) // does not start with sep { return sub(0, pos); // return everything up to it } else // the string starts with sep { if( ! skip_empty) { return sub(0, 0); } auto ppos = first_not_of(sep); // skip repeated seps if(ppos == npos) // the string is all made of seps { return sub(0, 0); } // find the next sep auto pos0 = first_of(sep, ppos); if(pos0 == npos) // only the first sep exists { return sub(0); // return the full string (because skip_empty is true) } C4_XASSERT(pos0 > 0); // return everything up to the second sep return sub(0, pos0); } } else // no sep was found, return the full string { return sub(0); } } else if(len == 1) { if(begins_with(sep)) { return sub(0, 0); } return sub(0); } else // an empty string { return basic_substring(); } } public: /** greedy pop left. eg, csubstr("a/b/c").gpop_left('/')="c" */ basic_substring gpop_left(C sep = C('/'), bool skip_empty=false) const { auto ss = pop_right(sep, skip_empty); ss = left_of(ss); if(ss.find(sep) != npos) { if(ss.ends_with(sep)) { if(skip_empty) { ss = ss.trimr(sep); } else { ss = ss.sub(0, ss.len-1); // safe to subtract because ends_with(sep) is true } } } return ss; } /** greedy pop right. eg, csubstr("a/b/c").gpop_right('/')="a" */ basic_substring gpop_right(C sep = C('/'), bool skip_empty=false) const { auto ss = pop_left(sep, skip_empty); ss = right_of(ss); if(ss.find(sep) != npos) { if(ss.begins_with(sep)) { if(skip_empty) { ss = ss.triml(sep); } else { ss = ss.sub(1); } } } return ss; } /** @} */ public: /** @name Path-like manipulation methods */ /** @{ */ basic_substring basename(C sep=C('/')) const { auto ss = pop_right(sep, /*skip_empty*/true); ss = ss.trimr(sep); return ss; } basic_substring dirname(C sep=C('/')) const { auto ss = basename(sep); ss = ss.empty() ? *this : left_of(ss); return ss; } C4_ALWAYS_INLINE basic_substring name_wo_extshort() const { return gpop_left('.'); } C4_ALWAYS_INLINE basic_substring name_wo_extlong() const { return pop_left('.'); } C4_ALWAYS_INLINE basic_substring extshort() const { return pop_right('.'); } C4_ALWAYS_INLINE basic_substring extlong() const { return gpop_right('.'); } /** @} */ public: /** @name Content-modification methods (only for non-const C) */ /** @{ */ /** convert the string to upper-case * @note this method requires that the string memory is writeable and is SFINAEd out for const C */ template auto toupper() -> typename std::enable_if< ! std::is_const::value, void>::type { for(size_t i = 0; i < len; ++i) { str[i] = static_cast(::toupper(str[i])); } } /** convert the string to lower-case * @note this method requires that the string memory is writeable and is SFINAEd out for const C */ template auto tolower() -> typename std::enable_if< !std::is_const::value, void>::type { for(size_t i = 0; i < len; ++i) { str[i] = static_cast(::tolower(str[i])); } } public: /** fill the entire contents with the given @p val * @note this method requires that the string memory is writeable and is SFINAEd out for const C */ template auto fill(C val) -> typename std::enable_if< !std::is_const::value, void>::type { for(size_t i = 0; i < len; ++i) str[i] = val; } public: /** copy a string to this substr, starting at 0 * @note this method requires that the string memory is writeable and is SFINAEd out for const C */ template auto copy_from(ro_substr that) -> typename std::enable_if< !std::is_const::value, void>::type { C4_ASSERT(!overlaps(that)); size_t num = that.len <= len ? that.len : len; // calling memcpy with zero len is undefined behavior // and will wreak havoc in calling code's branches. // see https://github.com/biojppm/rapidyaml/pull/264#issuecomment-1262133637 if(num) memcpy(str, that.str, sizeof(C) * num); } /** copy a string to this substr, starting at a specified given position * @note this method requires that the string memory is writeable and is SFINAEd out for const C */ template auto copy_from(ro_substr that, size_t ifirst, size_t num=npos) -> typename std::enable_if< !std::is_const::value, void>::type { C4_ASSERT(ifirst >= 0 && ifirst <= len); num = num != npos ? num : len - ifirst; num = num < that.len ? num : that.len; C4_ASSERT(ifirst + num >= 0 && ifirst + num <= len); // calling memcpy with zero len is undefined behavior // and will wreak havoc in calling code's branches. // see https://github.com/biojppm/rapidyaml/pull/264#issuecomment-1262133637 if(num) memcpy(str + (sizeof(C) * ifirst), that.str, sizeof(C) * num); } public: /** reverse in place * @note this method requires that the string memory is writeable and is SFINAEd out for const C */ template auto reverse() -> typename std::enable_if< !std::is_const::value, void>::type { if(len == 0) return; detail::_do_reverse(str, str + len - 1); } /** revert a subpart in place * @note this method requires that the string memory is writeable and is SFINAEd out for const C */ template auto reverse_sub(size_t ifirst, size_t num) -> typename std::enable_if< !std::is_const::value, void>::type { C4_ASSERT(ifirst >= 0 && ifirst <= len); C4_ASSERT(ifirst + num >= 0 && ifirst + num <= len); if(num == 0) return; detail::_do_reverse(str + ifirst, str + ifirst + num - 1); } /** revert a range in place * @note this method requires that the string memory is writeable and is SFINAEd out for const C */ template auto reverse_range(size_t ifirst, size_t ilast) -> typename std::enable_if< !std::is_const::value, void>::type { C4_ASSERT(ifirst >= 0 && ifirst <= len); C4_ASSERT(ilast >= 0 && ilast <= len); if(ifirst == ilast) return; detail::_do_reverse(str + ifirst, str + ilast - 1); } public: /** erase part of the string. eg, with char s[] = "0123456789", * substr(s).erase(3, 2) = "01256789", and s is now "0125678989" * @note this method requires that the string memory is writeable and is SFINAEd out for const C */ template auto erase(size_t pos, size_t num) -> typename std::enable_if< !std::is_const::value, basic_substring>::type { C4_ASSERT(pos >= 0 && pos+num <= len); size_t num_to_move = len - pos - num; memmove(str + pos, str + pos + num, sizeof(C) * num_to_move); return basic_substring{str, len - num}; } /** @note this method requires that the string memory is writeable and is SFINAEd out for const C */ template auto erase_range(size_t first, size_t last) -> typename std::enable_if< !std::is_const::value, basic_substring>::type { C4_ASSERT(first <= last); return erase(first, static_cast(last-first)); // NOLINT } /** erase a part of the string. * @note @p sub must be a substring of this string * @note this method requires that the string memory is writeable and is SFINAEd out for const C */ template auto erase(ro_substr sub) -> typename std::enable_if< !std::is_const::value, basic_substring>::type { C4_ASSERT(is_super(sub)); C4_ASSERT(sub.str >= str); return erase(static_cast(sub.str - str), sub.len); } public: /** replace every occurrence of character @p value with the character @p repl * @return the number of characters that were replaced * @note this method requires that the string memory is writeable and is SFINAEd out for const C */ template auto replace(C value, C repl, size_t pos=0) -> typename std::enable_if< ! std::is_const::value, size_t>::type { C4_ASSERT((pos >= 0 && pos <= len) || pos == npos); size_t did_it = 0; while((pos = find(value, pos)) != npos) { str[pos++] = repl; ++did_it; } return did_it; } /** replace every occurrence of each character in @p value with * the character @p repl. * @return the number of characters that were replaced * @note this method requires that the string memory is writeable and is SFINAEd out for const C */ template auto replace(ro_substr chars, C repl, size_t pos=0) -> typename std::enable_if< ! std::is_const::value, size_t>::type { C4_ASSERT((pos >= 0 && pos <= len) || pos == npos); size_t did_it = 0; while((pos = first_of(chars, pos)) != npos) { str[pos++] = repl; ++did_it; } return did_it; } /** replace @p pattern with @p repl, and write the result into * @p dst. pattern and repl don't need equal sizes. * * @return the required size for dst. No overflow occurs if * dst.len is smaller than the required size; this can be used to * determine the required size for an existing container. */ size_t replace_all(rw_substr dst, ro_substr pattern, ro_substr repl, size_t pos=0) const { C4_ASSERT( ! pattern.empty()); //!< @todo relax this precondition C4_ASSERT( ! this ->overlaps(dst)); //!< @todo relax this precondition C4_ASSERT( ! pattern.overlaps(dst)); C4_ASSERT( ! repl .overlaps(dst)); C4_ASSERT((pos >= 0 && pos <= len) || pos == npos); C4_SUPPRESS_WARNING_GCC_PUSH C4_SUPPRESS_WARNING_GCC("-Warray-bounds") // gcc11 has a false positive here #if (!defined(__clang__)) && (defined(__GNUC__) && (__GNUC__ >= 7)) C4_SUPPRESS_WARNING_GCC("-Wstringop-overflow") // gcc11 has a false positive here #endif #define _c4append(first, last) \ { \ C4_ASSERT((last) >= (first)); \ size_t num = static_cast((last) - (first)); \ if(num > 0 && sz + num <= dst.len) \ { \ memcpy(dst.str + sz, first, num * sizeof(C)); \ } \ sz += num; \ } size_t sz = 0; size_t b = pos; _c4append(str, str + pos) do { size_t e = find(pattern, b); if(e == npos) { _c4append(str + b, str + len) break; } _c4append(str + b, str + e) _c4append(repl.begin(), repl.end()) b = e + pattern.size(); } while(b < len && b != npos); return sz; #undef _c4append C4_SUPPRESS_WARNING_GCC_POP } /** @} */ }; // template class basic_substring #ifdef __DOXYGEN__ using substr = basic_substring; /**< a mutable string view */ using csubstr = basic_substring; /**< an immutable string view */ #endif //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @defgroup doc_substr_adapters substr adapters * * @ref c4::to_substr() and @ref c4::to_csubstr() are used in generic * code like @ref c4::format(). They enable the user to provide an * entry point for the construction of substrings from custom types. * * @{ */ /** @defgroup doc_substr_adapters_literal create substrings from a char literal * @{ */ template C4_ALWAYS_INLINE substr to_substr(char (&s)[N]) noexcept { return substr(s, N-1); } template C4_ALWAYS_INLINE csubstr to_csubstr(const char (&s)[N]) noexcept { return csubstr(s, N-1); } /** @} */ /** @defgroup doc_substr_adapters_cstring create substrings from C strings * @{ */ /** Create a substring from a C-string (char*-like pointer) * * @note this overload uses SFINAE to prevent it from overriding the * literal/array overload. U must be is a non-const-char pointer for * this function to be considered in the overload set. * * @see For a more detailed explanation on why the plain overloads cannot * coexist, see http://cplusplus.bordoon.com/specializeForCharacterArrays.html */ template C4_ALWAYS_INLINE auto to_substr(U s) noexcept -> typename std::enable_if::value, substr>::type { return substr(s); } /** Create a substring from a const char*-like pointer * * @note this overload uses SFINAE to prevent it from overriding the * literal/array overload * * @see For a more detailed explanation on why the plain overloads cannot * coexist, see http://cplusplus.bordoon.com/specializeForCharacterArrays.html */ template C4_ALWAYS_INLINE auto to_csubstr(U s) noexcept -> typename std::enable_if::value, csubstr>::type { return csubstr(s); } /** @} */ /** @defgroup doc_substr_adapters_neutral neutral version for use in generic code * @{ */ C4_ALWAYS_INLINE substr to_substr(substr s) noexcept { return s; } C4_ALWAYS_INLINE csubstr to_csubstr(substr s) noexcept { return csubstr{s.str, s.len}; } C4_ALWAYS_INLINE csubstr to_csubstr(csubstr s) noexcept { return s; } /** @} */ /** @} */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @defgroup doc_substr_cmp substr left-comparison operators * @{ */ /** @defgroup doc_substr_cmp_singlechar left-compare a single char with a csubstr * @{ */ template inline bool operator== (const char c, basic_substring const that) noexcept { return that.compare(c) == 0; } template inline bool operator!= (const char c, basic_substring const that) noexcept { return that.compare(c) != 0; } template inline bool operator< (const char c, basic_substring const that) noexcept { return that.compare(c) > 0; } template inline bool operator> (const char c, basic_substring const that) noexcept { return that.compare(c) < 0; } template inline bool operator<= (const char c, basic_substring const that) noexcept { return that.compare(c) >= 0; } template inline bool operator>= (const char c, basic_substring const that) noexcept { return that.compare(c) <= 0; } /** @} */ /** @defgroup doc_substr_cmp_literal left-compare a string literal with a csubstr * @{ */ template inline bool operator== (const char (&arr)[N], basic_substring const that) noexcept { return that.compare(arr, N-1) == 0; } template inline bool operator!= (const char (&arr)[N], basic_substring const that) noexcept { return that.compare(arr, N-1) != 0; } template inline bool operator< (const char (&arr)[N], basic_substring const that) noexcept { return that.compare(arr, N-1) > 0; } template inline bool operator> (const char (&arr)[N], basic_substring const that) noexcept { return that.compare(arr, N-1) < 0; } template inline bool operator<= (const char (&arr)[N], basic_substring const that) noexcept { return that.compare(arr, N-1) >= 0; } template inline bool operator>= (const char (&arr)[N], basic_substring const that) noexcept { return that.compare(arr, N-1) <= 0; } /** @} */ /** @defgroup doc_substr_cmp_cstring left-compare a C-string with a csubstr * @{ */ template inline auto operator== (U c_str, basic_substring const that) noexcept -> typename std::enable_if::value, bool>::type { return that.compare(c_str, strlen(c_str)) == 0; } template inline auto operator!= (U c_str, basic_substring const that) noexcept -> typename std::enable_if::value, bool>::type { return that.compare(c_str, strlen(c_str)) != 0; } template inline auto operator< (U c_str, basic_substring const that) noexcept -> typename std::enable_if::value, bool>::type { return that.compare(c_str, strlen(c_str)) > 0; } template inline auto operator> (U c_str, basic_substring const that) noexcept -> typename std::enable_if::value, bool>::type { return that.compare(c_str, strlen(c_str)) < 0; } template inline auto operator<= (U c_str, basic_substring const that) noexcept -> typename std::enable_if::value, bool>::type { return that.compare(c_str, strlen(c_str)) >= 0; } template inline auto operator>= (U c_str, basic_substring const that) noexcept -> typename std::enable_if::value, bool>::type { return that.compare(c_str, strlen(c_str)) <= 0; } /** @} */ /** @} */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /* C4_SUBSTR_NO_OSTREAM_LSHIFT doctest does not deal well with * template operator<< * @see https://github.com/onqtam/doctest/pull/431 */ #ifndef C4_SUBSTR_NO_OSTREAM_LSHIFT /** output the string to an ostream-like type */ template inline OStream& operator<< (OStream& os, basic_substring s) { C4_SUPPRESS_WARNING_GCC_CLANG_WITH_PUSH("-Wsign-conversion") os.write(s.str, s.len); C4_SUPPRESS_WARNING_GCC_CLANG_POP return os; } #endif // !C4_SUBSTR_NO_OSTREAM_LSHIFT /** @} */ } // namespace c4 C4_SUPPRESS_WARNING_GCC_CLANG_POP #endif /* C4_SUBSTR_HPP_ */ // (end ext/c4core.src/c4/substr.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/ext/fast_float.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_EXT_FAST_FLOAT_HPP_ #define C4_EXT_FAST_FLOAT_HPP_ #if defined(_MSC_VER) && !defined(__clang__) # pragma warning(push) # pragma warning(disable: 4127) // conditional expression is constant # pragma warning(disable: 4365) // '=': conversion from 'const _Ty' to 'fast_float::limb', signed/unsigned mismatch # pragma warning(disable: 4996) // snprintf/scanf: this function or variable may be unsafe #elif defined(__clang__) || defined(__APPLE_CC__) || defined(_LIBCPP_VERSION) # pragma clang diagnostic push # if (defined(__clang_major__) && (__clang_major__ >= 9)) || defined(__APPLE_CC__) # pragma clang diagnostic ignored "-Wfortify-source" # endif # pragma clang diagnostic ignored "-Wshift-count-overflow" # pragma clang diagnostic ignored "-Wold-style-cast" # pragma clang diagnostic ignored "-Wpadded" # pragma clang diagnostic ignored "-Wdocumentation-unknown-command" # if (defined(__clang_major__) && (__clang_major__ >= 21)) # pragma clang diagnostic ignored "-Wnrvo" # endif # if (defined(__clang_major__) && (__clang_major__ >= 13)) # pragma clang diagnostic ignored "-Wreserved-identifier" # endif # if (defined(__clang_major__) && (__clang_major__ >= 8)) # pragma clang diagnostic ignored "-Wextra-semi-stmt" # endif #elif defined(__GNUC__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wnarrowing" # pragma GCC diagnostic ignored "-Wconversion" # pragma GCC diagnostic ignored "-Wsign-conversion" # pragma GCC diagnostic ignored "-Wuseless-cast" # pragma GCC diagnostic ignored "-Wold-style-cast" # pragma GCC diagnostic ignored "-Warray-bounds" # if __GNUC__ >= 5 # pragma GCC diagnostic ignored "-Wshift-count-overflow" # endif # if __GNUC__ >= 6 # pragma GCC diagnostic ignored "-Wnull-dereference" # endif #endif #ifndef C4CORE_SYS_FAST_FLOAT // fast_float by Daniel Lemire // fast_float by João Paulo Magalhaes // // // with contributions from Eugene Golushkov // with contributions from Maksim Kita // with contributions from Marcin Wojdyr // with contributions from Neal Richardson // with contributions from Tim Paine // with contributions from Fabio Pellacini // with contributions from Lénárd Szolnoki // with contributions from Jan Pharago // with contributions from Maya Warrier // with contributions from Taha Khokhar // with contributions from Anders Dalvander // // // MIT License Notice // // MIT License // // Copyright (c) 2021 The fast_float authors // // Permission is hereby granted, free of charge, to any // person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the // Software without restriction, including without // limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice // shall be included in all copies or substantial portions // of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef FASTFLOAT_CONSTEXPR_FEATURE_DETECT_H #define FASTFLOAT_CONSTEXPR_FEATURE_DETECT_H #ifdef __has_include #if __has_include() #include #endif #endif // Testing for https://wg21.link/N3652, adopted in C++14 #if defined(__cpp_constexpr) && __cpp_constexpr >= 201304 #define FASTFLOAT_CONSTEXPR14 constexpr #else #define FASTFLOAT_CONSTEXPR14 #endif #if defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L #define FASTFLOAT_HAS_BIT_CAST 1 #else #define FASTFLOAT_HAS_BIT_CAST 0 #endif #if defined(__cpp_lib_is_constant_evaluated) && \ __cpp_lib_is_constant_evaluated >= 201811L #define FASTFLOAT_HAS_IS_CONSTANT_EVALUATED 1 #else #define FASTFLOAT_HAS_IS_CONSTANT_EVALUATED 0 #endif #if defined(__cpp_if_constexpr) && __cpp_if_constexpr >= 201606L #define FASTFLOAT_IF_CONSTEXPR17(x) if constexpr (x) #else #define FASTFLOAT_IF_CONSTEXPR17(x) if (x) #endif // Testing for relevant C++20 constexpr library features #if FASTFLOAT_HAS_IS_CONSTANT_EVALUATED && FASTFLOAT_HAS_BIT_CAST && \ defined(__cpp_lib_constexpr_algorithms) && \ __cpp_lib_constexpr_algorithms >= 201806L /*For std::copy and std::fill*/ #define FASTFLOAT_CONSTEXPR20 constexpr #define FASTFLOAT_IS_CONSTEXPR 1 #else #define FASTFLOAT_CONSTEXPR20 #define FASTFLOAT_IS_CONSTEXPR 0 #endif #if __cplusplus >= 201703L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) #define FASTFLOAT_DETAIL_MUST_DEFINE_CONSTEXPR_VARIABLE 0 #else #define FASTFLOAT_DETAIL_MUST_DEFINE_CONSTEXPR_VARIABLE 1 #endif #endif // FASTFLOAT_CONSTEXPR_FEATURE_DETECT_H #ifndef FASTFLOAT_FLOAT_COMMON_H #define FASTFLOAT_FLOAT_COMMON_H #include //#include // amalgamate: included above //#include // amalgamate: included above #include //#include // amalgamate: included above #include //#include // amalgamate: included above #include #ifdef __has_include #if __has_include() && (__cplusplus > 202002L || (defined(_MSVC_LANG) && (_MSVC_LANG > 202002L))) #include #endif #endif #define FASTFLOAT_VERSION_MAJOR 8 #define FASTFLOAT_VERSION_MINOR 2 #define FASTFLOAT_VERSION_PATCH 10 #define FASTFLOAT_STRINGIZE_IMPL(x) #x #define FASTFLOAT_STRINGIZE(x) FASTFLOAT_STRINGIZE_IMPL(x) #define FASTFLOAT_VERSION_STR \ FASTFLOAT_STRINGIZE(FASTFLOAT_VERSION_MAJOR) \ "." FASTFLOAT_STRINGIZE(FASTFLOAT_VERSION_MINOR) "." FASTFLOAT_STRINGIZE( \ FASTFLOAT_VERSION_PATCH) #define FASTFLOAT_VERSION \ (FASTFLOAT_VERSION_MAJOR * 10000 + FASTFLOAT_VERSION_MINOR * 100 + \ FASTFLOAT_VERSION_PATCH) namespace fast_float { enum class chars_format : uint64_t; namespace detail { constexpr chars_format basic_json_fmt = chars_format(1 << 5); constexpr chars_format basic_fortran_fmt = chars_format(1 << 6); } // namespace detail enum class chars_format : uint64_t { scientific = 1 << 0, fixed = 1 << 2, hex = 1 << 3, no_infnan = 1 << 4, // RFC 8259: https://datatracker.ietf.org/doc/html/rfc8259#section-6 json = uint64_t(detail::basic_json_fmt) | fixed | scientific | no_infnan, // Extension of RFC 8259 where, e.g., "inf" and "nan" are allowed. json_or_infnan = uint64_t(detail::basic_json_fmt) | fixed | scientific, fortran = uint64_t(detail::basic_fortran_fmt) | fixed | scientific, general = fixed | scientific, allow_leading_plus = 1 << 7, skip_white_space = 1 << 8, }; template struct from_chars_result_t { UC const *ptr; std::errc ec; // https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/p2497r0.html constexpr explicit operator bool() const noexcept { return ec == std::errc(); } }; using from_chars_result = from_chars_result_t; template struct parse_options_t { constexpr explicit parse_options_t(chars_format fmt = chars_format::general, UC dot = UC('.'), int b = 10) : format(fmt), decimal_point(dot), base(b) {} /** Which number formats are accepted */ chars_format format; /** The character used as decimal point */ UC decimal_point; /** The base used for integers */ int base; }; using parse_options = parse_options_t; } // namespace fast_float #if FASTFLOAT_HAS_BIT_CAST #include #endif #if (defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \ defined(__amd64) || defined(__aarch64__) || defined(_M_ARM64) || \ defined(__MINGW64__) || defined(__s390x__) || \ (defined(__ppc64__) || defined(__PPC64__) || defined(__ppc64le__) || \ defined(__PPC64LE__)) || \ defined(__loongarch64) || (defined(__riscv) && __riscv_xlen == 64)) #define FASTFLOAT_64BIT 1 #elif (defined(__i386) || defined(__i386__) || defined(_M_IX86) || \ defined(__arm__) || defined(_M_ARM) || defined(__ppc__) || \ defined(__MINGW32__) || defined(__EMSCRIPTEN__) || \ (defined(__riscv) && __riscv_xlen == 32)) #define FASTFLOAT_32BIT 1 #else // Need to check incrementally, since SIZE_MAX is a size_t, avoid overflow. // We can never tell the register width, but the SIZE_MAX is a good // approximation. UINTPTR_MAX and INTPTR_MAX are optional, so avoid them for max // portability. #if SIZE_MAX == 0xffff #error Unknown platform (16-bit, unsupported) #elif SIZE_MAX == 0xffffffff #define FASTFLOAT_32BIT 1 #elif SIZE_MAX == 0xffffffffffffffff #define FASTFLOAT_64BIT 1 #else #error Unknown platform (not 32-bit, not 64-bit?) #endif #endif #if ((defined(_WIN32) || defined(_WIN64)) && !defined(__clang__)) || \ (defined(_M_ARM64) && !defined(__MINGW32__)) //#include // amalgamate: included above #endif #if defined(_MSC_VER) && !defined(__clang__) #define FASTFLOAT_VISUAL_STUDIO 1 #endif #if defined __BYTE_ORDER__ && defined __ORDER_BIG_ENDIAN__ #define FASTFLOAT_IS_BIG_ENDIAN (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) #elif defined _WIN32 #define FASTFLOAT_IS_BIG_ENDIAN 0 #else #if defined(__APPLE__) || defined(__FreeBSD__) #include #elif defined(sun) || defined(__sun) #include #elif defined(__MVS__) #include #else #ifdef __has_include #if __has_include() #include #endif //__has_include() #endif //__has_include #endif # #ifndef __BYTE_ORDER__ // safe choice #define FASTFLOAT_IS_BIG_ENDIAN 0 #endif # #ifndef __ORDER_LITTLE_ENDIAN__ // safe choice #define FASTFLOAT_IS_BIG_ENDIAN 0 #endif # #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ #define FASTFLOAT_IS_BIG_ENDIAN 0 #else #define FASTFLOAT_IS_BIG_ENDIAN 1 #endif #endif #if defined(__SSE2__) || (defined(FASTFLOAT_VISUAL_STUDIO) && \ (defined(_M_AMD64) || defined(_M_X64) || \ (defined(_M_IX86_FP) && _M_IX86_FP == 2))) #define FASTFLOAT_SSE2 1 #endif #if defined(__aarch64__) || defined(_M_ARM64) #define FASTFLOAT_NEON 1 #endif #if defined(FASTFLOAT_SSE2) || defined(FASTFLOAT_NEON) #define FASTFLOAT_HAS_SIMD 1 #endif #if defined(__GNUC__) // disable -Wcast-align=strict (GCC only) #define FASTFLOAT_SIMD_DISABLE_WARNINGS \ _Pragma("GCC diagnostic push") \ _Pragma("GCC diagnostic ignored \"-Wcast-align\"") #else #define FASTFLOAT_SIMD_DISABLE_WARNINGS #endif #if defined(__GNUC__) #define FASTFLOAT_SIMD_RESTORE_WARNINGS _Pragma("GCC diagnostic pop") #else #define FASTFLOAT_SIMD_RESTORE_WARNINGS #endif #ifdef FASTFLOAT_VISUAL_STUDIO #define fastfloat_really_inline __forceinline #else #define fastfloat_really_inline inline __attribute__((always_inline)) #endif // Branch-probability hint marking the rare slow-path branches as cold, so the // optimizer keeps the out-of-line slow-path re-parse off the hot path (and does // not duplicate the force-inlined hot scanner into the caller, which bloated // the hot frame and hurt ILP on some targets). Used at the call site as // if fastfloat_unlikely(cond) { ... } // (the macro supplies the parentheses). It expands to the standard [[unlikely]] // attribute when supported, otherwise to __builtin_expect on GCC/Clang, or // to a no-op elsewhere (e.g. pre-C++20 MSVC, which has no equivalent hint). #ifdef __has_cpp_attribute #if __has_cpp_attribute(unlikely) >= 201803L // g++-9 hits hits this branch, but then fails to compile // [[unlikely]]. This happens only with g++-9. #if !defined(__GNUC__) || (__GNUC__ != 9) #define FASTFLOAT_USE_UNLIKELY_ATTR #endif #endif #endif #ifdef FASTFLOAT_USE_UNLIKELY_ATTR #define fastfloat_unlikely(x) (x) [[unlikely]] #elif defined(__GNUC__) || defined(__clang__) #define fastfloat_unlikely(x) (__builtin_expect(!!(x), 0)) #else #define fastfloat_unlikely(x) (x) #endif #ifndef FASTFLOAT_ASSERT #define FASTFLOAT_ASSERT(x) \ { ((void)(x)); } #endif #ifndef FASTFLOAT_DEBUG_ASSERT #define FASTFLOAT_DEBUG_ASSERT(x) \ { ((void)(x)); } #endif // rust style `try!()` macro, or `?` operator #define FASTFLOAT_TRY(x) \ { \ if (!(x)) \ return false; \ } #define FASTFLOAT_ENABLE_IF(...) \ typename std::enable_if<(__VA_ARGS__), int>::type namespace fast_float { fastfloat_really_inline constexpr bool cpp20_and_in_constexpr() { #if FASTFLOAT_HAS_IS_CONSTANT_EVALUATED return std::is_constant_evaluated(); #else return false; #endif } template struct is_supported_float_type : std::integral_constant< bool, std::is_same::value || std::is_same::value #ifdef __STDCPP_FLOAT64_T__ || std::is_same::value #endif #ifdef __STDCPP_FLOAT32_T__ || std::is_same::value #endif #ifdef __STDCPP_FLOAT16_T__ || std::is_same::value #endif #ifdef __STDCPP_BFLOAT16_T__ || std::is_same::value #endif > { }; template using equiv_uint_t = typename std::conditional< sizeof(T) == 1, uint8_t, typename std::conditional< sizeof(T) == 2, uint16_t, typename std::conditional::type>::type>::type; template struct is_supported_integer_type : std::is_integral {}; template struct is_supported_char_type : std::integral_constant::value || std::is_same::value || std::is_same::value || std::is_same::value #ifdef __cpp_char8_t || std::is_same::value #endif > { }; template inline FASTFLOAT_CONSTEXPR14 bool fastfloat_strncasecmp3(UC const *actual_mixedcase, UC const *expected_lowercase) { uint64_t mask{0}; FASTFLOAT_IF_CONSTEXPR17(sizeof(UC) == 1) { mask = 0x2020202020202020; } else FASTFLOAT_IF_CONSTEXPR17(sizeof(UC) == 2) { mask = 0x0020002000200020; } else FASTFLOAT_IF_CONSTEXPR17(sizeof(UC) == 4) { mask = 0x0000002000000020; } else { return false; } uint64_t val1{0}, val2{0}; if (cpp20_and_in_constexpr()) { for (size_t i = 0; i < 3; i++) { if ((actual_mixedcase[i] | 32) != expected_lowercase[i]) { return false; } } return true; } else { FASTFLOAT_IF_CONSTEXPR17(sizeof(UC) == 1 || sizeof(UC) == 2) { ::memcpy(&val1, actual_mixedcase, 3 * sizeof(UC)); ::memcpy(&val2, expected_lowercase, 3 * sizeof(UC)); val1 |= mask; val2 |= mask; return val1 == val2; } else FASTFLOAT_IF_CONSTEXPR17(sizeof(UC) == 4) { ::memcpy(&val1, actual_mixedcase, 2 * sizeof(UC)); ::memcpy(&val2, expected_lowercase, 2 * sizeof(UC)); val1 |= mask; if (val1 != val2) { return false; } return (actual_mixedcase[2] | 32) == (expected_lowercase[2]); } else { return false; } } } template inline FASTFLOAT_CONSTEXPR14 bool fastfloat_strncasecmp5(UC const *actual_mixedcase, UC const *expected_lowercase) { uint64_t mask{0}; uint64_t val1{0}, val2{0}; if (cpp20_and_in_constexpr()) { for (size_t i = 0; i < 5; i++) { if ((actual_mixedcase[i] | 32) != expected_lowercase[i]) { return false; } } return true; } else { FASTFLOAT_IF_CONSTEXPR17(sizeof(UC) == 1) { mask = 0x2020202020202020; ::memcpy(&val1, actual_mixedcase, 5 * sizeof(UC)); ::memcpy(&val2, expected_lowercase, 5 * sizeof(UC)); val1 |= mask; val2 |= mask; return val1 == val2; } else FASTFLOAT_IF_CONSTEXPR17(sizeof(UC) == 2) { mask = 0x0020002000200020; ::memcpy(&val1, actual_mixedcase, 4 * sizeof(UC)); ::memcpy(&val2, expected_lowercase, 4 * sizeof(UC)); val1 |= mask; if (val1 != val2) { return false; } return (actual_mixedcase[4] | 32) == (expected_lowercase[4]); } else FASTFLOAT_IF_CONSTEXPR17(sizeof(UC) == 4) { mask = 0x0000002000000020; ::memcpy(&val1, actual_mixedcase, 2 * sizeof(UC)); ::memcpy(&val2, expected_lowercase, 2 * sizeof(UC)); val1 |= mask; if (val1 != val2) { return false; } ::memcpy(&val1, actual_mixedcase + 2, 2 * sizeof(UC)); ::memcpy(&val2, expected_lowercase + 2, 2 * sizeof(UC)); val1 |= mask; if (val1 != val2) { return false; } return (actual_mixedcase[4] | 32) == (expected_lowercase[4]); } else { return false; } } } // Compares two ASCII strings in a case insensitive manner. template inline FASTFLOAT_CONSTEXPR14 bool fastfloat_strncasecmp(UC const *actual_mixedcase, UC const *expected_lowercase, size_t length) { uint64_t mask{0}; FASTFLOAT_IF_CONSTEXPR17(sizeof(UC) == 1) { mask = 0x2020202020202020; } else FASTFLOAT_IF_CONSTEXPR17(sizeof(UC) == 2) { mask = 0x0020002000200020; } else FASTFLOAT_IF_CONSTEXPR17(sizeof(UC) == 4) { mask = 0x0000002000000020; } else { return false; } if (cpp20_and_in_constexpr()) { for (size_t i = 0; i < length; i++) { if ((actual_mixedcase[i] | 32) != expected_lowercase[i]) { return false; } } return true; } else { uint64_t val1{0}, val2{0}; size_t sz{8 / (sizeof(UC))}; for (size_t i = 0; i < length; i += sz) { val1 = val2 = 0; sz = sz < (length - i) ? sz : length - i; ::memcpy(&val1, actual_mixedcase + i, sz * sizeof(UC)); ::memcpy(&val2, expected_lowercase + i, sz * sizeof(UC)); val1 |= mask; val2 |= mask; if (val1 != val2) { return false; } } return true; } } #ifndef FLT_EVAL_METHOD #error "FLT_EVAL_METHOD should be defined, please include cfloat." #endif // a pointer and a length to a contiguous block of memory template struct span { T const *ptr; size_t length; constexpr span(T const *_ptr, size_t _length) : ptr(_ptr), length(_length) {} constexpr span() : ptr(nullptr), length(0) {} constexpr size_t len() const noexcept { return length; } FASTFLOAT_CONSTEXPR14 const T &operator[](size_t index) const noexcept { FASTFLOAT_DEBUG_ASSERT(index < length); return ptr[index]; } }; struct value128 { uint64_t low; uint64_t high; constexpr value128(uint64_t _low, uint64_t _high) : low(_low), high(_high) {} constexpr value128() : low(0), high(0) {} }; /* Helper C++14 constexpr generic implementation of leading_zeroes */ fastfloat_really_inline FASTFLOAT_CONSTEXPR14 int leading_zeroes_generic(uint64_t input_num, int last_bit = 0) { if (input_num & uint64_t(0xffffffff00000000)) { input_num >>= 32; last_bit |= 32; } if (input_num & uint64_t(0xffff0000)) { input_num >>= 16; last_bit |= 16; } if (input_num & uint64_t(0xff00)) { input_num >>= 8; last_bit |= 8; } if (input_num & uint64_t(0xf0)) { input_num >>= 4; last_bit |= 4; } if (input_num & uint64_t(0xc)) { input_num >>= 2; last_bit |= 2; } if (input_num & uint64_t(0x2)) { /* input_num >>= 1; */ last_bit |= 1; } return 63 - last_bit; } /* result might be undefined when input_num is zero */ fastfloat_really_inline FASTFLOAT_CONSTEXPR20 int leading_zeroes(uint64_t input_num) { assert(input_num > 0); if (cpp20_and_in_constexpr()) { return leading_zeroes_generic(input_num); } #ifdef FASTFLOAT_VISUAL_STUDIO #if defined(_M_X64) || defined(_M_ARM64) unsigned long leading_zero = 0; // Search the mask data from most significant bit (MSB) // to least significant bit (LSB) for a set bit (1). _BitScanReverse64(&leading_zero, input_num); return (int)(63 - leading_zero); #else return leading_zeroes_generic(input_num); #endif #else return __builtin_clzll(input_num); #endif } /* Helper C++14 constexpr generic implementation of countr_zero for 32-bit */ fastfloat_really_inline FASTFLOAT_CONSTEXPR14 int countr_zero_generic_32(uint32_t input_num) { if (input_num == 0) { return 32; } int last_bit = 0; if (!(input_num & 0x0000FFFF)) { input_num >>= 16; last_bit |= 16; } if (!(input_num & 0x00FF)) { input_num >>= 8; last_bit |= 8; } if (!(input_num & 0x0F)) { input_num >>= 4; last_bit |= 4; } if (!(input_num & 0x3)) { input_num >>= 2; last_bit |= 2; } if (!(input_num & 0x1)) { last_bit |= 1; } return last_bit; } /* count trailing zeroes for 32-bit integers */ fastfloat_really_inline FASTFLOAT_CONSTEXPR20 int countr_zero_32(uint32_t input_num) { if (cpp20_and_in_constexpr()) { return countr_zero_generic_32(input_num); } #ifdef FASTFLOAT_VISUAL_STUDIO unsigned long trailing_zero = 0; if (_BitScanForward(&trailing_zero, input_num)) { return (int)trailing_zero; } return 32; #else return input_num == 0 ? 32 : __builtin_ctz(input_num); #endif } // slow emulation routine for 32-bit fastfloat_really_inline constexpr uint64_t emulu(uint32_t x, uint32_t y) { return x * (uint64_t)y; } fastfloat_really_inline FASTFLOAT_CONSTEXPR14 uint64_t umul128_generic(uint64_t ab, uint64_t cd, uint64_t *hi) { uint64_t ad = emulu((uint32_t)(ab >> 32), (uint32_t)cd); uint64_t bd = emulu((uint32_t)ab, (uint32_t)cd); uint64_t adbc = ad + emulu((uint32_t)ab, (uint32_t)(cd >> 32)); uint64_t adbc_carry = (uint64_t)(adbc < ad); uint64_t lo = bd + (adbc << 32); *hi = emulu((uint32_t)(ab >> 32), (uint32_t)(cd >> 32)) + (adbc >> 32) + (adbc_carry << 32) + (uint64_t)(lo < bd); return lo; } #ifdef FASTFLOAT_32BIT // slow emulation routine for 32-bit #if !defined(__MINGW64__) fastfloat_really_inline FASTFLOAT_CONSTEXPR14 uint64_t _umul128(uint64_t ab, uint64_t cd, uint64_t *hi) { return umul128_generic(ab, cd, hi); } #endif // !__MINGW64__ #endif // FASTFLOAT_32BIT // compute 64-bit a*b fastfloat_really_inline FASTFLOAT_CONSTEXPR20 value128 full_multiplication(uint64_t a, uint64_t b) { if (cpp20_and_in_constexpr()) { value128 answer; answer.low = umul128_generic(a, b, &answer.high); return answer; } value128 answer; #if defined(_M_ARM64) && !defined(__MINGW32__) // ARM64 has native support for 64-bit multiplications, no need to emulate // But MinGW on ARM64 doesn't have native support for 64-bit multiplications answer.high = __umulh(a, b); answer.low = a * b; #elif defined(FASTFLOAT_32BIT) || (defined(_WIN64) && !defined(__clang__) && \ !defined(_M_ARM64) && !defined(__GNUC__)) answer.low = _umul128(a, b, &answer.high); // _umul128 not available on ARM64 #elif defined(FASTFLOAT_64BIT) && defined(__SIZEOF_INT128__) __uint128_t r = ((__uint128_t)a) * b; answer.low = uint64_t(r); answer.high = uint64_t(r >> 64); #else answer.low = umul128_generic(a, b, &answer.high); #endif return answer; } struct adjusted_mantissa { uint64_t mantissa{0}; int32_t power2{0}; // a negative value indicates an invalid result adjusted_mantissa() = default; constexpr bool operator==(adjusted_mantissa const &o) const { return mantissa == o.mantissa && power2 == o.power2; } constexpr bool operator!=(adjusted_mantissa const &o) const { return mantissa != o.mantissa || power2 != o.power2; } }; // Bias so we can get the real exponent with an invalid adjusted_mantissa. constexpr static int32_t invalid_am_bias = -0x8000; // used for binary_format_lookup_tables::max_mantissa constexpr uint64_t constant_55555 = 5 * 5 * 5 * 5 * 5; template struct binary_format_lookup_tables; template struct binary_format : binary_format_lookup_tables { using equiv_uint = equiv_uint_t; static constexpr int mantissa_explicit_bits(); static constexpr int minimum_exponent(); static constexpr int infinite_power(); static constexpr int sign_index(); static constexpr int min_exponent_fast_path(); // used when fegetround() == FE_TONEAREST static constexpr int max_exponent_fast_path(); static constexpr int max_exponent_round_to_even(); static constexpr int min_exponent_round_to_even(); static constexpr uint64_t max_mantissa_fast_path(int64_t power); static constexpr uint64_t max_mantissa_fast_path(); // used when fegetround() == FE_TONEAREST static constexpr int largest_power_of_ten(); static constexpr int smallest_power_of_ten(); static constexpr T exact_power_of_ten(int64_t power); static constexpr size_t max_digits(); static constexpr equiv_uint exponent_mask(); static constexpr equiv_uint mantissa_mask(); static constexpr equiv_uint hidden_bit_mask(); }; template struct binary_format_lookup_tables { static constexpr double powers_of_ten[] = { 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22}; // Largest integer value v so that (5**index * v) <= 1<<53. // 0x20000000000000 == 1 << 53 static constexpr uint64_t max_mantissa[] = { 0x20000000000000, 0x20000000000000 / 5, 0x20000000000000 / (5 * 5), 0x20000000000000 / (5 * 5 * 5), 0x20000000000000 / (5 * 5 * 5 * 5), 0x20000000000000 / (constant_55555), 0x20000000000000 / (constant_55555 * 5), 0x20000000000000 / (constant_55555 * 5 * 5), 0x20000000000000 / (constant_55555 * 5 * 5 * 5), 0x20000000000000 / (constant_55555 * 5 * 5 * 5 * 5), 0x20000000000000 / (constant_55555 * constant_55555), 0x20000000000000 / (constant_55555 * constant_55555 * 5), 0x20000000000000 / (constant_55555 * constant_55555 * 5 * 5), 0x20000000000000 / (constant_55555 * constant_55555 * 5 * 5 * 5), 0x20000000000000 / (constant_55555 * constant_55555 * constant_55555), 0x20000000000000 / (constant_55555 * constant_55555 * constant_55555 * 5), 0x20000000000000 / (constant_55555 * constant_55555 * constant_55555 * 5 * 5), 0x20000000000000 / (constant_55555 * constant_55555 * constant_55555 * 5 * 5 * 5), 0x20000000000000 / (constant_55555 * constant_55555 * constant_55555 * 5 * 5 * 5 * 5), 0x20000000000000 / (constant_55555 * constant_55555 * constant_55555 * constant_55555), 0x20000000000000 / (constant_55555 * constant_55555 * constant_55555 * constant_55555 * 5), 0x20000000000000 / (constant_55555 * constant_55555 * constant_55555 * constant_55555 * 5 * 5), 0x20000000000000 / (constant_55555 * constant_55555 * constant_55555 * constant_55555 * 5 * 5 * 5), 0x20000000000000 / (constant_55555 * constant_55555 * constant_55555 * constant_55555 * 5 * 5 * 5 * 5)}; }; #if FASTFLOAT_DETAIL_MUST_DEFINE_CONSTEXPR_VARIABLE template constexpr double binary_format_lookup_tables::powers_of_ten[]; template constexpr uint64_t binary_format_lookup_tables::max_mantissa[]; #endif template struct binary_format_lookup_tables { static constexpr float powers_of_ten[] = {1e0f, 1e1f, 1e2f, 1e3f, 1e4f, 1e5f, 1e6f, 1e7f, 1e8f, 1e9f, 1e10f}; // Largest integer value v so that (5**index * v) <= 1<<24. // 0x1000000 == 1<<24 static constexpr uint64_t max_mantissa[] = { 0x1000000, 0x1000000 / 5, 0x1000000 / (5 * 5), 0x1000000 / (5 * 5 * 5), 0x1000000 / (5 * 5 * 5 * 5), 0x1000000 / (constant_55555), 0x1000000 / (constant_55555 * 5), 0x1000000 / (constant_55555 * 5 * 5), 0x1000000 / (constant_55555 * 5 * 5 * 5), 0x1000000 / (constant_55555 * 5 * 5 * 5 * 5), 0x1000000 / (constant_55555 * constant_55555), 0x1000000 / (constant_55555 * constant_55555 * 5)}; }; #if FASTFLOAT_DETAIL_MUST_DEFINE_CONSTEXPR_VARIABLE template constexpr float binary_format_lookup_tables::powers_of_ten[]; template constexpr uint64_t binary_format_lookup_tables::max_mantissa[]; #endif template <> inline constexpr int binary_format::min_exponent_fast_path() { #if (FLT_EVAL_METHOD != 1) && (FLT_EVAL_METHOD != 0) return 0; #else return -22; #endif } template <> inline constexpr int binary_format::min_exponent_fast_path() { #if (FLT_EVAL_METHOD != 1) && (FLT_EVAL_METHOD != 0) return 0; #else return -10; #endif } template <> inline constexpr int binary_format::mantissa_explicit_bits() { return 52; } template <> inline constexpr int binary_format::mantissa_explicit_bits() { return 23; } template <> inline constexpr int binary_format::max_exponent_round_to_even() { return 23; } template <> inline constexpr int binary_format::max_exponent_round_to_even() { return 10; } template <> inline constexpr int binary_format::min_exponent_round_to_even() { return -4; } template <> inline constexpr int binary_format::min_exponent_round_to_even() { return -17; } template <> inline constexpr int binary_format::minimum_exponent() { return -1023; } template <> inline constexpr int binary_format::minimum_exponent() { return -127; } template <> inline constexpr int binary_format::infinite_power() { return 0x7FF; } template <> inline constexpr int binary_format::infinite_power() { return 0xFF; } template <> inline constexpr int binary_format::sign_index() { return 63; } template <> inline constexpr int binary_format::sign_index() { return 31; } template <> inline constexpr int binary_format::max_exponent_fast_path() { return 22; } template <> inline constexpr int binary_format::max_exponent_fast_path() { return 10; } template <> inline constexpr uint64_t binary_format::max_mantissa_fast_path() { return uint64_t(2) << mantissa_explicit_bits(); } template <> inline constexpr uint64_t binary_format::max_mantissa_fast_path() { return uint64_t(2) << mantissa_explicit_bits(); } // credit: Jakub Jelínek #ifdef __STDCPP_FLOAT16_T__ template struct binary_format_lookup_tables { static constexpr std::float16_t powers_of_ten[] = {1e0f16, 1e1f16, 1e2f16, 1e3f16, 1e4f16}; // Largest integer value v so that (5**index * v) <= 1<<11. // 0x800 == 1<<11 static constexpr uint64_t max_mantissa[] = {0x800, 0x800 / 5, 0x800 / (5 * 5), 0x800 / (5 * 5 * 5), 0x800 / (5 * 5 * 5 * 5), 0x800 / (constant_55555)}; }; #if FASTFLOAT_DETAIL_MUST_DEFINE_CONSTEXPR_VARIABLE template constexpr std::float16_t binary_format_lookup_tables::powers_of_ten[]; template constexpr uint64_t binary_format_lookup_tables::max_mantissa[]; #endif template <> inline constexpr std::float16_t binary_format::exact_power_of_ten(int64_t power) { // Work around clang bug https://godbolt.org/z/zedh7rrhc return (void)powers_of_ten[0], powers_of_ten[power]; } template <> inline constexpr binary_format::equiv_uint binary_format::exponent_mask() { return 0x7C00; } template <> inline constexpr binary_format::equiv_uint binary_format::mantissa_mask() { return 0x03FF; } template <> inline constexpr binary_format::equiv_uint binary_format::hidden_bit_mask() { return 0x0400; } template <> inline constexpr int binary_format::max_exponent_fast_path() { return 4; } template <> inline constexpr int binary_format::mantissa_explicit_bits() { return 10; } template <> inline constexpr uint64_t binary_format::max_mantissa_fast_path() { return uint64_t(2) << mantissa_explicit_bits(); } template <> inline constexpr uint64_t binary_format::max_mantissa_fast_path(int64_t power) { // caller is responsible to ensure that // power >= 0 && power <= 4 // // Work around clang bug https://godbolt.org/z/zedh7rrhc return (void)max_mantissa[0], max_mantissa[power]; } template <> inline constexpr int binary_format::min_exponent_fast_path() { return 0; } template <> inline constexpr int binary_format::max_exponent_round_to_even() { return 5; } template <> inline constexpr int binary_format::min_exponent_round_to_even() { return -22; } template <> inline constexpr int binary_format::minimum_exponent() { return -15; } template <> inline constexpr int binary_format::infinite_power() { return 0x1F; } template <> inline constexpr int binary_format::sign_index() { return 15; } template <> inline constexpr int binary_format::largest_power_of_ten() { return 4; } template <> inline constexpr int binary_format::smallest_power_of_ten() { return -27; } template <> inline constexpr size_t binary_format::max_digits() { return 22; } #endif // __STDCPP_FLOAT16_T__ // credit: Jakub Jelínek #ifdef __STDCPP_BFLOAT16_T__ template struct binary_format_lookup_tables { static constexpr std::bfloat16_t powers_of_ten[] = {1e0bf16, 1e1bf16, 1e2bf16, 1e3bf16}; // Largest integer value v so that (5**index * v) <= 1<<8. // 0x100 == 1<<8 static constexpr uint64_t max_mantissa[] = {0x100, 0x100 / 5, 0x100 / (5 * 5), 0x100 / (5 * 5 * 5), 0x100 / (5 * 5 * 5 * 5)}; }; #if FASTFLOAT_DETAIL_MUST_DEFINE_CONSTEXPR_VARIABLE template constexpr std::bfloat16_t binary_format_lookup_tables::powers_of_ten[]; template constexpr uint64_t binary_format_lookup_tables::max_mantissa[]; #endif template <> inline constexpr std::bfloat16_t binary_format::exact_power_of_ten(int64_t power) { // Work around clang bug https://godbolt.org/z/zedh7rrhc return (void)powers_of_ten[0], powers_of_ten[power]; } template <> inline constexpr int binary_format::max_exponent_fast_path() { return 3; } template <> inline constexpr binary_format::equiv_uint binary_format::exponent_mask() { return 0x7F80; } template <> inline constexpr binary_format::equiv_uint binary_format::mantissa_mask() { return 0x007F; } template <> inline constexpr binary_format::equiv_uint binary_format::hidden_bit_mask() { return 0x0080; } template <> inline constexpr int binary_format::mantissa_explicit_bits() { return 7; } template <> inline constexpr uint64_t binary_format::max_mantissa_fast_path() { return uint64_t(2) << mantissa_explicit_bits(); } template <> inline constexpr uint64_t binary_format::max_mantissa_fast_path(int64_t power) { // caller is responsible to ensure that // power >= 0 && power <= 3 // // Work around clang bug https://godbolt.org/z/zedh7rrhc return (void)max_mantissa[0], max_mantissa[power]; } template <> inline constexpr int binary_format::min_exponent_fast_path() { return 0; } template <> inline constexpr int binary_format::max_exponent_round_to_even() { return 3; } template <> inline constexpr int binary_format::min_exponent_round_to_even() { return -24; } template <> inline constexpr int binary_format::minimum_exponent() { return -127; } template <> inline constexpr int binary_format::infinite_power() { return 0xFF; } template <> inline constexpr int binary_format::sign_index() { return 15; } template <> inline constexpr int binary_format::largest_power_of_ten() { return 38; } template <> inline constexpr int binary_format::smallest_power_of_ten() { return -60; } template <> inline constexpr size_t binary_format::max_digits() { return 98; } #endif // __STDCPP_BFLOAT16_T__ template <> inline constexpr uint64_t binary_format::max_mantissa_fast_path(int64_t power) { // caller is responsible to ensure that // power >= 0 && power <= 22 // // Work around clang bug https://godbolt.org/z/zedh7rrhc return (void)max_mantissa[0], max_mantissa[power]; } template <> inline constexpr uint64_t binary_format::max_mantissa_fast_path(int64_t power) { // caller is responsible to ensure that // power >= 0 && power <= 10 // // Work around clang bug https://godbolt.org/z/zedh7rrhc return (void)max_mantissa[0], max_mantissa[power]; } template <> inline constexpr double binary_format::exact_power_of_ten(int64_t power) { // Work around clang bug https://godbolt.org/z/zedh7rrhc return (void)powers_of_ten[0], powers_of_ten[power]; } template <> inline constexpr float binary_format::exact_power_of_ten(int64_t power) { // Work around clang bug https://godbolt.org/z/zedh7rrhc return (void)powers_of_ten[0], powers_of_ten[power]; } template <> inline constexpr int binary_format::largest_power_of_ten() { return 308; } template <> inline constexpr int binary_format::largest_power_of_ten() { return 38; } template <> inline constexpr int binary_format::smallest_power_of_ten() { return -342; } template <> inline constexpr int binary_format::smallest_power_of_ten() { return -64; } template <> inline constexpr size_t binary_format::max_digits() { return 769; } template <> inline constexpr size_t binary_format::max_digits() { return 114; } template <> inline constexpr binary_format::equiv_uint binary_format::exponent_mask() { return 0x7F800000; } template <> inline constexpr binary_format::equiv_uint binary_format::exponent_mask() { return 0x7FF0000000000000; } template <> inline constexpr binary_format::equiv_uint binary_format::mantissa_mask() { return 0x007FFFFF; } template <> inline constexpr binary_format::equiv_uint binary_format::mantissa_mask() { return 0x000FFFFFFFFFFFFF; } template <> inline constexpr binary_format::equiv_uint binary_format::hidden_bit_mask() { return 0x00800000; } template <> inline constexpr binary_format::equiv_uint binary_format::hidden_bit_mask() { return 0x0010000000000000; } template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 void to_float(bool negative, adjusted_mantissa am, T &value) { using equiv_uint = equiv_uint_t; equiv_uint word = equiv_uint(am.mantissa); word = equiv_uint(word | equiv_uint(am.power2) << binary_format::mantissa_explicit_bits()); word = equiv_uint(word | equiv_uint(negative) << binary_format::sign_index()); #if FASTFLOAT_HAS_BIT_CAST value = std::bit_cast(word); #else ::memcpy(&value, &word, sizeof(T)); #endif } template struct space_lut { static constexpr bool value[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; }; #if FASTFLOAT_DETAIL_MUST_DEFINE_CONSTEXPR_VARIABLE template constexpr bool space_lut::value[]; #endif template constexpr bool is_space(UC c) { return c < 256 && space_lut<>::value[uint8_t(c)]; } template static constexpr uint64_t int_cmp_zeros() { static_assert((sizeof(UC) == 1) || (sizeof(UC) == 2) || (sizeof(UC) == 4), "Unsupported character size"); return (sizeof(UC) == 1) ? 0x3030303030303030 : (sizeof(UC) == 2) ? (uint64_t(UC('0')) << 48 | uint64_t(UC('0')) << 32 | uint64_t(UC('0')) << 16 | UC('0')) : (uint64_t(UC('0')) << 32 | UC('0')); } template static constexpr int int_cmp_len() { return sizeof(uint64_t) / sizeof(UC); } template constexpr UC const *str_const_nan(); template <> constexpr char const *str_const_nan() { return "nan"; } template <> constexpr wchar_t const *str_const_nan() { return L"nan"; } template <> constexpr char16_t const *str_const_nan() { return u"nan"; } template <> constexpr char32_t const *str_const_nan() { return U"nan"; } #ifdef __cpp_char8_t template <> constexpr char8_t const *str_const_nan() { return u8"nan"; } #endif template constexpr UC const *str_const_inf(); template <> constexpr char const *str_const_inf() { return "infinity"; } template <> constexpr wchar_t const *str_const_inf() { return L"infinity"; } template <> constexpr char16_t const *str_const_inf() { return u"infinity"; } template <> constexpr char32_t const *str_const_inf() { return U"infinity"; } #ifdef __cpp_char8_t template <> constexpr char8_t const *str_const_inf() { return u8"infinity"; } #endif template struct int_luts { static constexpr uint8_t chdigit[] = { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}; static constexpr size_t maxdigits_u64[] = { 64, 41, 32, 28, 25, 23, 22, 21, 20, 19, 18, 18, 17, 17, 16, 16, 16, 16, 15, 15, 15, 15, 14, 14, 14, 14, 14, 14, 14, 13, 13, 13, 13, 13, 13}; static constexpr uint64_t min_safe_u64[] = { 9223372036854775808ull, 12157665459056928801ull, 4611686018427387904, 7450580596923828125, 4738381338321616896, 3909821048582988049, 9223372036854775808ull, 12157665459056928801ull, 10000000000000000000ull, 5559917313492231481, 2218611106740436992, 8650415919381337933, 2177953337809371136, 6568408355712890625, 1152921504606846976, 2862423051509815793, 6746640616477458432, 15181127029874798299ull, 1638400000000000000, 3243919932521508681, 6221821273427820544, 11592836324538749809ull, 876488338465357824, 1490116119384765625, 2481152873203736576, 4052555153018976267, 6502111422497947648, 10260628712958602189ull, 15943230000000000000ull, 787662783788549761, 1152921504606846976, 1667889514952984961, 2386420683693101056, 3379220508056640625, 4738381338321616896}; }; #if FASTFLOAT_DETAIL_MUST_DEFINE_CONSTEXPR_VARIABLE template constexpr uint8_t int_luts::chdigit[]; template constexpr size_t int_luts::maxdigits_u64[]; template constexpr uint64_t int_luts::min_safe_u64[]; #endif template fastfloat_really_inline constexpr uint8_t ch_to_digit(UC c) { // wchar_t and char can be signed, so we need to be careful. using UnsignedUC = typename std::make_unsigned::type; return int_luts<>::chdigit[static_cast( static_cast(c) & static_cast( -((static_cast(c) & ~0xFFull) == 0)))]; } fastfloat_really_inline constexpr size_t max_digits_u64(int base) { return int_luts<>::maxdigits_u64[base - 2]; } // If a u64 is exactly max_digits_u64() in length, this is // the value below which it has definitely overflowed. fastfloat_really_inline constexpr uint64_t min_safe_u64(int base) { return int_luts<>::min_safe_u64[base - 2]; } static_assert(std::is_same, uint64_t>::value, "equiv_uint should be uint64_t for double"); static_assert(std::numeric_limits::is_iec559, "double must fulfill the requirements of IEC 559 (IEEE 754)"); static_assert(std::is_same, uint32_t>::value, "equiv_uint should be uint32_t for float"); static_assert(std::numeric_limits::is_iec559, "float must fulfill the requirements of IEC 559 (IEEE 754)"); #ifdef __STDCPP_FLOAT64_T__ static_assert(std::is_same, uint64_t>::value, "equiv_uint should be uint64_t for std::float64_t"); static_assert( std::numeric_limits::is_iec559, "std::float64_t must fulfill the requirements of IEC 559 (IEEE 754)"); template <> struct binary_format : public binary_format {}; #endif // __STDCPP_FLOAT64_T__ #ifdef __STDCPP_FLOAT32_T__ static_assert(std::is_same, uint32_t>::value, "equiv_uint should be uint32_t for std::float32_t"); static_assert( std::numeric_limits::is_iec559, "std::float32_t must fulfill the requirements of IEC 559 (IEEE 754)"); template <> struct binary_format : public binary_format {}; #endif // __STDCPP_FLOAT32_T__ #ifdef __STDCPP_FLOAT16_T__ static_assert( std::is_same::equiv_uint, uint16_t>::value, "equiv_uint should be uint16_t for std::float16_t"); static_assert( std::numeric_limits::is_iec559, "std::float16_t must fulfill the requirements of IEC 559 (IEEE 754)"); #endif // __STDCPP_FLOAT16_T__ #ifdef __STDCPP_BFLOAT16_T__ static_assert( std::is_same::equiv_uint, uint16_t>::value, "equiv_uint should be uint16_t for std::bfloat16_t"); static_assert( std::numeric_limits::is_iec559, "std::bfloat16_t must fulfill the requirements of IEC 559 (IEEE 754)"); #endif // __STDCPP_BFLOAT16_T__ constexpr chars_format operator~(chars_format rhs) noexcept { using int_type = std::underlying_type::type; return static_cast(~static_cast(rhs)); } constexpr chars_format operator&(chars_format lhs, chars_format rhs) noexcept { using int_type = std::underlying_type::type; return static_cast(static_cast(lhs) & static_cast(rhs)); } constexpr chars_format operator|(chars_format lhs, chars_format rhs) noexcept { using int_type = std::underlying_type::type; return static_cast(static_cast(lhs) | static_cast(rhs)); } constexpr chars_format operator^(chars_format lhs, chars_format rhs) noexcept { using int_type = std::underlying_type::type; return static_cast(static_cast(lhs) ^ static_cast(rhs)); } fastfloat_really_inline FASTFLOAT_CONSTEXPR14 chars_format & operator&=(chars_format &lhs, chars_format rhs) noexcept { return lhs = (lhs & rhs); } fastfloat_really_inline FASTFLOAT_CONSTEXPR14 chars_format & operator|=(chars_format &lhs, chars_format rhs) noexcept { return lhs = (lhs | rhs); } fastfloat_really_inline FASTFLOAT_CONSTEXPR14 chars_format & operator^=(chars_format &lhs, chars_format rhs) noexcept { return lhs = (lhs ^ rhs); } namespace detail { // adjust for deprecated feature macros constexpr chars_format adjust_for_feature_macros(chars_format fmt) { return fmt #ifdef FASTFLOAT_ALLOWS_LEADING_PLUS | chars_format::allow_leading_plus #endif #ifdef FASTFLOAT_SKIP_WHITE_SPACE | chars_format::skip_white_space #endif ; } } // namespace detail } // namespace fast_float #endif #ifndef FASTFLOAT_FAST_FLOAT_H #define FASTFLOAT_FAST_FLOAT_H namespace fast_float { /** * This function parses the character sequence [first,last) for a number. It * parses floating-point numbers expecting a locale-independent format * equivalent to what is used by std::strtod in the default ("C") locale. The * resulting floating-point value is the closest floating-point values (using * either float or double), using the "round to even" convention for values that * would otherwise fall right in-between two values. That is, we provide exact * parsing according to the IEEE standard. * * Given a successful parse, the pointer (`ptr`) in the returned value is set to * point right after the parsed number, and the `value` referenced is set to the * parsed value. In case of error, the returned `ec` contains a representative * error, otherwise the default (`std::errc()`) value is stored. * * The implementation does not throw and does not allocate memory (e.g., with * `new` or `malloc`). * * Like the C++17 standard, the `fast_float::from_chars` functions take an * optional last argument of the type `fast_float::chars_format`. It is a bitset * value: we check whether `fmt & fast_float::chars_format::fixed` and `fmt & * fast_float::chars_format::scientific` are set to determine whether we allow * the fixed point and scientific notation respectively. The default is * `fast_float::chars_format::general` which allows both `fixed` and * `scientific`. */ template ::value)> FASTFLOAT_CONSTEXPR20 from_chars_result_t from_chars(UC const *first, UC const *last, T &value, chars_format fmt = chars_format::general) noexcept; /** * Like from_chars, but accepts an `options` argument to govern number parsing. * Both for floating-point types and integer types. */ template FASTFLOAT_CONSTEXPR20 from_chars_result_t from_chars_advanced(UC const *first, UC const *last, T &value, parse_options_t options) noexcept; /** * This function multiplies an integer number by a power of 10 and returns * the result as a double precision floating-point value that is correctly * rounded. The resulting floating-point value is the closest floating-point * value, using the "round to nearest, tie to even" convention for values that * would otherwise fall right in-between two values. That is, we provide exact * conversion according to the IEEE standard. * * On overflow infinity is returned, on underflow 0 is returned. * * The implementation does not throw and does not allocate memory (e.g., with * `new` or `malloc`). */ FASTFLOAT_CONSTEXPR20 inline double integer_times_pow10(uint64_t mantissa, int decimal_exponent) noexcept; FASTFLOAT_CONSTEXPR20 inline double integer_times_pow10(int64_t mantissa, int decimal_exponent) noexcept; /** * This function is a template overload of `integer_times_pow10()` * that returns a floating-point value of type `T` that is one of * supported floating-point types (e.g. `double`, `float`). */ template FASTFLOAT_CONSTEXPR20 typename std::enable_if::value, T>::type integer_times_pow10(uint64_t mantissa, int decimal_exponent) noexcept; template FASTFLOAT_CONSTEXPR20 typename std::enable_if::value, T>::type integer_times_pow10(int64_t mantissa, int decimal_exponent) noexcept; /** * from_chars for integer types. */ template ::value)> FASTFLOAT_CONSTEXPR20 from_chars_result_t from_chars(UC const *first, UC const *last, T &value, int base = 10) noexcept; } // namespace fast_float #endif // FASTFLOAT_FAST_FLOAT_H #ifndef FASTFLOAT_ASCII_NUMBER_H #define FASTFLOAT_ASCII_NUMBER_H //#include // amalgamate: included above //#include // amalgamate: included above //#include // amalgamate: included above #include //#include // amalgamate: included above //#include // amalgamate: included above #ifdef FASTFLOAT_SSE2 #include #endif #ifdef FASTFLOAT_NEON #include #endif namespace fast_float { template fastfloat_really_inline constexpr bool has_simd_opt() { #ifdef FASTFLOAT_HAS_SIMD return std::is_same::value; #else return false; #endif } // Next function can be micro-optimized, but compilers are entirely // able to optimize it well. template fastfloat_really_inline constexpr bool is_integer(UC c) noexcept { return (unsigned)(c - UC('0')) <= 9u; } fastfloat_really_inline constexpr uint64_t byteswap(uint64_t val) { return (val & 0xFF00000000000000) >> 56 | (val & 0x00FF000000000000) >> 40 | (val & 0x0000FF0000000000) >> 24 | (val & 0x000000FF00000000) >> 8 | (val & 0x00000000FF000000) << 8 | (val & 0x0000000000FF0000) << 24 | (val & 0x000000000000FF00) << 40 | (val & 0x00000000000000FF) << 56; } fastfloat_really_inline constexpr uint32_t byteswap_32(uint32_t val) { return (val >> 24) | ((val >> 8) & 0x0000FF00u) | ((val << 8) & 0x00FF0000u) | (val << 24); } // Read 8 UC into a u64. Truncates UC if not char. template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 uint64_t read8_to_u64(UC const *chars) { if (cpp20_and_in_constexpr() || !std::is_same::value) { uint64_t val = 0; for (int i = 0; i < 8; ++i) { val |= uint64_t(uint8_t(*chars)) << (i * 8); ++chars; } return val; } uint64_t val; ::memcpy(&val, chars, sizeof(uint64_t)); #if FASTFLOAT_IS_BIG_ENDIAN == 1 // Need to read as-if the number was in little-endian order. val = byteswap(val); #endif return val; } // Read 4 UC into a u32. Truncates UC if not char. template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 uint32_t read4_to_u32(UC const *chars) { if (cpp20_and_in_constexpr() || !std::is_same::value) { uint32_t val = 0; for (int i = 0; i < 4; ++i) { val |= uint32_t(uint8_t(*chars)) << (i * 8); ++chars; } return val; } uint32_t val; ::memcpy(&val, chars, sizeof(uint32_t)); #if FASTFLOAT_IS_BIG_ENDIAN == 1 val = byteswap_32(val); #endif return val; } #ifdef FASTFLOAT_SSE2 fastfloat_really_inline uint64_t simd_read8_to_u64(__m128i const data) { FASTFLOAT_SIMD_DISABLE_WARNINGS __m128i const packed = _mm_packus_epi16(data, data); #ifdef FASTFLOAT_64BIT return uint64_t(_mm_cvtsi128_si64(packed)); #else uint64_t value; // Visual Studio + older versions of GCC don't support _mm_storeu_si64 _mm_storel_epi64(reinterpret_cast<__m128i *>(&value), packed); return value; #endif FASTFLOAT_SIMD_RESTORE_WARNINGS } fastfloat_really_inline uint64_t simd_read8_to_u64(char16_t const *chars) { FASTFLOAT_SIMD_DISABLE_WARNINGS return simd_read8_to_u64( _mm_loadu_si128(reinterpret_cast<__m128i const *>(chars))); FASTFLOAT_SIMD_RESTORE_WARNINGS } #elif defined(FASTFLOAT_NEON) fastfloat_really_inline uint64_t simd_read8_to_u64(uint16x8_t const data) { FASTFLOAT_SIMD_DISABLE_WARNINGS uint8x8_t utf8_packed = vmovn_u16(data); return vget_lane_u64(vreinterpret_u64_u8(utf8_packed), 0); FASTFLOAT_SIMD_RESTORE_WARNINGS } fastfloat_really_inline uint64_t simd_read8_to_u64(char16_t const *chars) { FASTFLOAT_SIMD_DISABLE_WARNINGS return simd_read8_to_u64( vld1q_u16(reinterpret_cast(chars))); FASTFLOAT_SIMD_RESTORE_WARNINGS } #endif // FASTFLOAT_SSE2 // MSVC SFINAE is broken pre-VS2017 #if defined(_MSC_VER) && _MSC_VER <= 1900 template #else template ()) = 0> #endif // dummy for compile uint64_t simd_read8_to_u64(UC const *) { return 0; } // credit @aqrit fastfloat_really_inline FASTFLOAT_CONSTEXPR14 uint32_t parse_eight_digits_unrolled(uint64_t val) { uint64_t const mask = 0x000000FF000000FF; uint64_t const mul1 = 0x000F424000000064; // 100 + (1000000ULL << 32) uint64_t const mul2 = 0x0000271000000001; // 1 + (10000ULL << 32) val -= 0x3030303030303030; val = (val * 10) + (val >> 8); // val = (val * 2561) >> 8; val = (((val & mask) * mul1) + (((val >> 16) & mask) * mul2)) >> 32; return uint32_t(val); } // Call this if chars are definitely 8 digits. template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 uint32_t parse_eight_digits_unrolled(UC const *chars) noexcept { if (cpp20_and_in_constexpr() || !has_simd_opt()) { return parse_eight_digits_unrolled(read8_to_u64(chars)); // truncation okay } return parse_eight_digits_unrolled(simd_read8_to_u64(chars)); } // credit @aqrit fastfloat_really_inline constexpr bool is_made_of_eight_digits_fast(uint64_t val) noexcept { return !((((val + 0x4646464646464646) | (val - 0x3030303030303030)) & 0x8080808080808080)); } fastfloat_really_inline constexpr bool is_made_of_four_digits_fast(uint32_t val) noexcept { return !((((val + 0x46464646) | (val - 0x30303030)) & 0x80808080)); } fastfloat_really_inline FASTFLOAT_CONSTEXPR14 uint32_t parse_four_digits_unrolled(uint32_t val) noexcept { val -= 0x30303030; val = (val * 10) + (val >> 8); return (((val & 0x00FF00FF) * 0x00640001) >> 16) & 0xFFFF; } #ifdef FASTFLOAT_HAS_SIMD // Call this if chars might not be 8 digits. // Using this style (instead of is_made_of_eight_digits_fast() then // parse_eight_digits_unrolled()) ensures we don't load SIMD registers twice. fastfloat_really_inline FASTFLOAT_CONSTEXPR20 bool simd_parse_if_eight_digits_unrolled(char16_t const *chars, uint64_t &i) noexcept { if (cpp20_and_in_constexpr()) { return false; } #ifdef FASTFLOAT_SSE2 FASTFLOAT_SIMD_DISABLE_WARNINGS __m128i const data = _mm_loadu_si128(reinterpret_cast<__m128i const *>(chars)); // (x - '0') <= 9 // http://0x80.pl/articles/simd-parsing-int-sequences.html __m128i const t0 = _mm_add_epi16(data, _mm_set1_epi16(32720)); __m128i const t1 = _mm_cmpgt_epi16(t0, _mm_set1_epi16(-32759)); if (_mm_movemask_epi8(t1) == 0) { i = i * 100000000 + parse_eight_digits_unrolled(simd_read8_to_u64(data)); return true; } else return false; FASTFLOAT_SIMD_RESTORE_WARNINGS #elif defined(FASTFLOAT_NEON) FASTFLOAT_SIMD_DISABLE_WARNINGS uint16x8_t const data = vld1q_u16(reinterpret_cast(chars)); // (x - '0') <= 9 // http://0x80.pl/articles/simd-parsing-int-sequences.html uint16x8_t const t0 = vsubq_u16(data, vmovq_n_u16('0')); uint16x8_t const mask = vcltq_u16(t0, vmovq_n_u16('9' - '0' + 1)); if (vminvq_u16(mask) == 0xFFFF) { i = i * 100000000 + parse_eight_digits_unrolled(simd_read8_to_u64(data)); return true; } else return false; FASTFLOAT_SIMD_RESTORE_WARNINGS #else (void)chars; (void)i; return false; #endif // FASTFLOAT_SSE2 } #endif // FASTFLOAT_HAS_SIMD // MSVC SFINAE is broken pre-VS2017 #if defined(_MSC_VER) && _MSC_VER <= 1900 template #else template ()) = 0> #endif // dummy for compile bool simd_parse_if_eight_digits_unrolled(UC const *, uint64_t &) { return 0; } template ::value) = 0> fastfloat_really_inline FASTFLOAT_CONSTEXPR20 void loop_parse_if_eight_digits(UC const *&p, UC const *const pend, uint64_t &i) { if (!has_simd_opt()) { return; } while ((std::distance(p, pend) >= 8) && simd_parse_if_eight_digits_unrolled( p, i)) { // in rare cases, this will overflow, but that's ok p += 8; } } fastfloat_really_inline FASTFLOAT_CONSTEXPR20 void loop_parse_if_eight_digits(char const *&p, char const *const pend, uint64_t &i) { // optimizes better than parse_if_eight_digits_unrolled() for UC = char. while ((std::distance(p, pend) >= 8) && is_made_of_eight_digits_fast(read8_to_u64(p))) { i = i * 100000000 + parse_eight_digits_unrolled(read8_to_u64( p)); // in rare cases, this will overflow, but that's ok p += 8; } // Consume a remaining 4-7 digit run in a single SWAR step instead of // byte-by-byte (reuses the existing 4-digit helpers). The parsed result is // identical either way. Gated to clang: on gcc the extra 4-digit check // regresses inputs whose remainder is shorter than 4 digits (it becomes pure // overhead there); clang does not show that. #if defined(__clang__) if ((pend - p) >= 4) { uint32_t const val4 = read4_to_u32(p); if (is_made_of_four_digits_fast(val4)) { i = i * 10000 + parse_four_digits_unrolled(val4); // may overflow, that's ok p += 4; } } #endif } enum class parse_error { no_error, // [JSON-only] The minus sign must be followed by an integer. missing_integer_after_sign, // A sign must be followed by an integer or dot. missing_integer_or_dot_after_sign, // [JSON-only] The integer part must not have leading zeros. leading_zeros_in_integer_part, // [JSON-only] The integer part must have at least one digit. no_digits_in_integer_part, // [JSON-only] If there is a decimal point, there must be digits in the // fractional part. no_digits_in_fractional_part, // The mantissa must have at least one digit. no_digits_in_mantissa, // Scientific notation requires an exponential part. missing_exponential_part, }; template struct parsed_number_string_t { int64_t exponent{0}; uint64_t mantissa{0}; UC const *lastmatch{nullptr}; bool negative{false}; bool valid{false}; bool too_many_digits{false}; // contains the range of the significant digits span integer{}; // non-nullable span fraction{}; // nullable parse_error error{parse_error::no_error}; }; using byte_span = span; using parsed_number_string = parsed_number_string_t; template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 parsed_number_string_t report_parse_error(UC const *p, parse_error error) { parsed_number_string_t answer; answer.valid = false; answer.lastmatch = p; answer.error = error; return answer; } // Assuming that you use no more than 19 digits, this will // parse an ASCII string. // // store_spans is a *runtime* flag (not a template parameter, deliberately: a // template would create a second instantiation of this whole function and the // extra icache pressure wipes out the gain). When false, the integer/fraction // spans (read only by the rare digit_comp slow path) are not materialized, // which keeps the fat parsed_number_string_t off the hot path. The caller // re-parses with store_spans=true if the slow path is actually reached. template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 parsed_number_string_t parse_number_string(UC const *p, UC const *pend, parse_options_t options, bool store_spans = true) noexcept { chars_format const fmt = detail::adjust_for_feature_macros(options.format); UC const decimal_point = options.decimal_point; parsed_number_string_t answer; answer.valid = false; answer.too_many_digits = false; // assume p < pend, so dereference without checks; answer.negative = (*p == UC('-')); // C++17 20.19.3.(7.1) explicitly forbids '+' sign here if ((*p == UC('-')) || (uint64_t(fmt & chars_format::allow_leading_plus) && !basic_json_fmt && *p == UC('+'))) { ++p; if (p == pend) { return report_parse_error( p, parse_error::missing_integer_or_dot_after_sign); } FASTFLOAT_IF_CONSTEXPR17(basic_json_fmt) { if (!is_integer(*p)) { // a sign must be followed by an integer return report_parse_error(p, parse_error::missing_integer_after_sign); } } else { if (!is_integer(*p) && (*p != decimal_point)) { // a sign must be followed by an integer or the dot return report_parse_error( p, parse_error::missing_integer_or_dot_after_sign); } } } UC const *const start_digits = p; uint64_t i = 0; // an unsigned int avoids signed overflows (which are bad) // Straight-line unroll of the integer-part scan: most integer parts are // 1-5 digits, so peeling the first iterations eliminates the loop back-edge // for the common case. Semantics are identical to the original `while` loop: // i = 10*i + digit, advancing p. if ((p != pend) && is_integer(*p)) { i = uint64_t(*p - UC('0')); ++p; if ((p != pend) && is_integer(*p)) { i = 10 * i + uint64_t(*p - UC('0')); ++p; if ((p != pend) && is_integer(*p)) { i = 10 * i + uint64_t(*p - UC('0')); ++p; if ((p != pend) && is_integer(*p)) { i = 10 * i + uint64_t(*p - UC('0')); ++p; if ((p != pend) && is_integer(*p)) { i = 10 * i + uint64_t(*p - UC('0')); ++p; while ((p != pend) && is_integer(*p)) { // a multiplication by 10 is cheaper than an arbitrary integer // multiplication i = 10 * i + uint64_t(*p - UC('0')); // might overflow, handled later ++p; } } } } } } UC const *const end_of_integer_part = p; int64_t digit_count = int64_t(end_of_integer_part - start_digits); if (store_spans) { answer.integer = span(start_digits, size_t(digit_count)); } FASTFLOAT_IF_CONSTEXPR17(basic_json_fmt) { // at least 1 digit in integer part, without leading zeros if (digit_count == 0) { return report_parse_error(p, parse_error::no_digits_in_integer_part); } if ((start_digits[0] == UC('0') && digit_count > 1)) { return report_parse_error(start_digits, parse_error::leading_zeros_in_integer_part); } } int64_t exponent = 0; bool const has_decimal_point = (p != pend) && (*p == decimal_point); if (has_decimal_point) { ++p; UC const *before = p; // can occur at most twice without overflowing, but let it occur more, since // for integers with many digits, digit parsing is the primary bottleneck. loop_parse_if_eight_digits(p, pend, i); while ((p != pend) && is_integer(*p)) { uint8_t digit = uint8_t(*p - UC('0')); ++p; i = i * 10 + digit; // in rare cases, this will overflow, but that's ok } exponent = before - p; if (store_spans) { answer.fraction = span(before, size_t(p - before)); } digit_count -= exponent; } FASTFLOAT_IF_CONSTEXPR17(basic_json_fmt) { // at least 1 digit in fractional part if (has_decimal_point && exponent == 0) { return report_parse_error(p, parse_error::no_digits_in_fractional_part); } } else if (digit_count == 0) { // we must have encountered at least one integer! return report_parse_error(p, parse_error::no_digits_in_mantissa); } int64_t exp_number = 0; // explicit exponential part if ((uint64_t(fmt & chars_format::scientific) && (p != pend) && ((UC('e') == *p) || (UC('E') == *p))) || (uint64_t(fmt & detail::basic_fortran_fmt) && (p != pend) && ((UC('+') == *p) || (UC('-') == *p) || (UC('d') == *p) || (UC('D') == *p)))) { UC const *location_of_e = p; if ((UC('e') == *p) || (UC('E') == *p) || (UC('d') == *p) || (UC('D') == *p)) { ++p; } bool neg_exp = false; if ((p != pend) && (UC('-') == *p)) { neg_exp = true; ++p; } else if ((p != pend) && (UC('+') == *p)) { // '+' on exponent is allowed by C++17 20.19.3.(7.1) ++p; } if ((p == pend) || !is_integer(*p)) { if (!uint64_t(fmt & chars_format::fixed)) { // The exponential part is invalid for scientific notation, so it must // be a trailing token for fixed notation. However, fixed notation is // disabled, so report a scientific notation error. return report_parse_error(p, parse_error::missing_exponential_part); } // Otherwise, we will be ignoring the 'e'. p = location_of_e; } else { while ((p != pend) && is_integer(*p)) { uint8_t digit = uint8_t(*p - UC('0')); if (exp_number < 0x10000000) { exp_number = 10 * exp_number + digit; } ++p; } if (neg_exp) { exp_number = -exp_number; } exponent += exp_number; } } else { // If it scientific and not fixed, we have to bail out. if (uint64_t(fmt & chars_format::scientific) && !uint64_t(fmt & chars_format::fixed)) { return report_parse_error(p, parse_error::missing_exponential_part); } } answer.lastmatch = p; answer.valid = true; // If we frequently had to deal with long strings of digits, // we could extend our code by using a 128-bit integer instead // of a 64-bit integer. However, this is uncommon. // // We can deal with up to 19 digits. if (digit_count > 19) { // this is uncommon // It is possible that the integer had an overflow. // We have to handle the case where we have 0.0000somenumber. // We need to be mindful of the case where we only have zeroes... // E.g., 0.000000000...000. UC const *start = start_digits; while ((start != pend) && (*start == UC('0') || *start == decimal_point)) { if (*start == UC('0')) { digit_count--; } start++; } if (digit_count > 19) { answer.too_many_digits = true; // The truncation recompute below reads the integer/fraction spans. When // store_spans is false we didn't materialize them, so just flag // too_many_digits; the caller re-parses with store_spans=true to obtain // the corrected mantissa/exponent before taking the slow path. if (store_spans) { // Let us start again, this time, avoiding overflows. // We don't need to call if is_integer, since we use the // pre-tokenized spans from above. i = 0; p = answer.integer.ptr; UC const *int_end = p + answer.integer.len(); uint64_t const minimal_nineteen_digit_integer{1000000000000000000}; while ((i < minimal_nineteen_digit_integer) && (p != int_end)) { i = i * 10 + uint64_t(*p - UC('0')); ++p; } if (i >= minimal_nineteen_digit_integer) { // We have a big integer exponent = end_of_integer_part - p + exp_number; } else { // We have a value with a fractional component. p = answer.fraction.ptr; UC const *frac_end = p + answer.fraction.len(); while ((i < minimal_nineteen_digit_integer) && (p != frac_end)) { i = i * 10 + uint64_t(*p - UC('0')); ++p; } exponent = answer.fraction.ptr - p + exp_number; } // We have now corrected both exponent and i, to a truncated value } } } answer.exponent = exponent; answer.mantissa = i; return answer; } template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 from_chars_result_t parse_int_string(UC const *p, UC const *pend, T &value, parse_options_t options) { chars_format const fmt = detail::adjust_for_feature_macros(options.format); int const base = options.base; from_chars_result_t answer; UC const *const first = p; bool const negative = (*p == UC('-')); #ifdef FASTFLOAT_VISUAL_STUDIO #pragma warning(push) #pragma warning(disable : 4127) #endif if (!std::is_signed::value && negative) { #ifdef FASTFLOAT_VISUAL_STUDIO #pragma warning(pop) #endif answer.ec = std::errc::invalid_argument; answer.ptr = first; return answer; } if ((*p == UC('-')) || (uint64_t(fmt & chars_format::allow_leading_plus) && (*p == UC('+')))) { ++p; } UC const *const start_num = p; while (p != pend && *p == UC('0')) { ++p; } bool const has_leading_zeros = p > start_num; UC const *const start_digits = p; FASTFLOAT_IF_CONSTEXPR17( (std::is_same::value && sizeof(UC) == 1)) { if (base == 10) { const size_t len = (size_t)(pend - p); if (len == 0) { if (has_leading_zeros) { value = 0; answer.ec = std::errc(); answer.ptr = p; } else { answer.ec = std::errc::invalid_argument; answer.ptr = first; } return answer; } uint32_t digits; #if FASTFLOAT_HAS_IS_CONSTANT_EVALUATED && FASTFLOAT_HAS_BIT_CAST if (std::is_constant_evaluated()) { uint8_t str[4]{}; for (size_t j = 0; j < 4 && j < len; ++j) { str[j] = static_cast(p[j]); } digits = std::bit_cast(str); #if FASTFLOAT_IS_BIG_ENDIAN digits = byteswap_32(digits); #endif } #else if (false) { } #endif else if (len >= 4) { ::memcpy(&digits, p, 4); #if FASTFLOAT_IS_BIG_ENDIAN digits = byteswap_32(digits); #endif } else { uint32_t b0 = static_cast(p[0]); uint32_t b1 = (len > 1) ? static_cast(p[1]) : 0xFFu; uint32_t b2 = (len > 2) ? static_cast(p[2]) : 0xFFu; uint32_t b3 = 0xFFu; digits = b0 | (b1 << 8) | (b2 << 16) | (b3 << 24); } uint32_t magic = ((digits + 0x46464646u) | (digits - 0x30303030u)) & 0x80808080u; uint32_t tz = (uint32_t)countr_zero_32(magic); // 7, 15, 23, 31, or 32 uint32_t nd = (tz == 32) ? 4 : (tz >> 3); nd = (uint32_t)(nd < len ? nd : len); if (nd == 0) { if (has_leading_zeros) { value = 0; answer.ec = std::errc(); answer.ptr = p; return answer; } answer.ec = std::errc::invalid_argument; answer.ptr = first; return answer; } if (nd > 3) { const UC *q = p + nd; size_t rem = len - nd; while (rem) { if (*q < UC('0') || *q > UC('9')) break; ++q; --rem; } answer.ec = std::errc::result_out_of_range; answer.ptr = q; return answer; } digits ^= 0x30303030u; digits <<= ((4 - nd) * 8); uint32_t check = ((digits >> 24) & 0xff) | ((digits >> 8) & 0xff00) | ((digits << 8) & 0xff0000); if (check > 0x00020505) { answer.ec = std::errc::result_out_of_range; answer.ptr = p + nd; return answer; } value = (uint8_t)((0x640a01 * digits) >> 24); answer.ec = std::errc(); answer.ptr = p + nd; return answer; } } FASTFLOAT_IF_CONSTEXPR17( (std::is_same::value && sizeof(UC) == 1)) { if (base == 10) { const size_t len = size_t(pend - p); if (len == 0) { if (has_leading_zeros) { value = 0; answer.ec = std::errc(); answer.ptr = p; } else { answer.ec = std::errc::invalid_argument; answer.ptr = first; } return answer; } if (len >= 4) { uint32_t digits = read4_to_u32(p); if (is_made_of_four_digits_fast(digits)) { uint32_t v = parse_four_digits_unrolled(digits); if (len >= 5 && is_integer(p[4])) { v = v * 10 + uint32_t(p[4] - '0'); if (len >= 6 && is_integer(p[5])) { answer.ec = std::errc::result_out_of_range; const UC *q = p + 5; while (q != pend && is_integer(*q)) { q++; } answer.ptr = q; return answer; } if (v > 65535) { answer.ec = std::errc::result_out_of_range; answer.ptr = p + 5; return answer; } value = uint16_t(v); answer.ec = std::errc(); answer.ptr = p + 5; return answer; } // 4 digits value = uint16_t(v); answer.ec = std::errc(); answer.ptr = p + 4; return answer; } } } } uint64_t i = 0; if (base == 10) { loop_parse_if_eight_digits(p, pend, i); // use SIMD if possible } while (p != pend) { uint8_t digit = ch_to_digit(*p); if (digit >= base) { break; } i = uint64_t(base) * i + digit; // might overflow, check this later p++; } size_t digit_count = size_t(p - start_digits); if (digit_count == 0) { if (has_leading_zeros) { value = 0; answer.ec = std::errc(); answer.ptr = p; } else { answer.ec = std::errc::invalid_argument; answer.ptr = first; } return answer; } answer.ptr = p; // check u64 overflow size_t max_digits = max_digits_u64(base); if (digit_count > max_digits) { answer.ec = std::errc::result_out_of_range; return answer; } // this check can be eliminated for all other types, but they will all require // a max_digits(base) equivalent if (digit_count == max_digits) { // At the max_digits boundary the accumulator `i` may have wrapped around // 2^64. A plain `i < min_safe_u64(base)` test is not sufficient: for any // base whose max_digits-length range exceeds 2^64 (base 10 reaches // ~5.4 * 2^64 at 20 digits) the value can wrap a whole multiple of 2^64 and // land back above min_safe, slipping through. Decide exactly in O(1) using // the leading digit, following the approach used in simdjson: // ms == min_safe_u64(base) == base^(max_digits-1), the smallest // max_digits-length value. // dmax == the largest leading digit whose number can still fit in u64. // The leading-digit band [d*ms, (d+1)*ms) has width ms < 2^64, so within // the single band where d == dmax the value straddles 2^64 at most once, // and a single threshold separates wrapped from non-wrapped values. A // leading digit above dmax always overflows; below dmax always fits. uint64_t const ms = min_safe_u64(base); uint64_t const dmax = (std::numeric_limits::max)() / ms; uint64_t const lead = ch_to_digit(*start_digits); if (lead > dmax || (lead == dmax && i < dmax * ms)) { answer.ec = std::errc::result_out_of_range; return answer; } } // check other types overflow if (!std::is_same::value) { if (i > uint64_t(std::numeric_limits::max()) + uint64_t(negative)) { answer.ec = std::errc::result_out_of_range; return answer; } } if (negative) { #ifdef FASTFLOAT_VISUAL_STUDIO #pragma warning(push) #pragma warning(disable : 4146) #endif // this weird workaround is required because: // - converting unsigned to signed when its value is greater than signed max // is UB pre-C++23. // - reinterpret_casting (~i + 1) would work, but it is not constexpr // this is always optimized into a neg instruction (note: T is an integer // type) value = T(-std::numeric_limits::max() - T(i - uint64_t(std::numeric_limits::max()))); #ifdef FASTFLOAT_VISUAL_STUDIO #pragma warning(pop) #endif } else { value = T(i); } answer.ec = std::errc(); return answer; } } // namespace fast_float #endif #ifndef FASTFLOAT_FAST_TABLE_H #define FASTFLOAT_FAST_TABLE_H //#include // amalgamate: included above namespace fast_float { /** * When mapping numbers from decimal to binary, * we go from w * 10^q to m * 2^p but we have * 10^q = 5^q * 2^q, so effectively * we are trying to match * w * 2^q * 5^q to m * 2^p. Thus the powers of two * are not a concern since they can be represented * exactly using the binary notation, only the powers of five * affect the binary significand. */ /** * The smallest non-zero float (binary64) is 2^-1074. * We take as input numbers of the form w x 10^q where w < 2^64. * We have that w * 10^-343 < 2^(64-344) 5^-343 < 2^-1076. * However, we have that * (2^64-1) * 10^-342 = (2^64-1) * 2^-342 * 5^-342 > 2^-1074. * Thus it is possible for a number of the form w * 10^-342 where * w is a 64-bit value to be a non-zero floating-point number. ********* * Any number of form w * 10^309 where w>= 1 is going to be * infinite in binary64 so we never need to worry about powers * of 5 greater than 308. */ template struct powers_template { constexpr static int smallest_power_of_five = binary_format::smallest_power_of_ten(); constexpr static int largest_power_of_five = binary_format::largest_power_of_ten(); constexpr static int number_of_entries = 2 * (largest_power_of_five - smallest_power_of_five + 1); // Powers of five from 5^-342 all the way to 5^308 rounded toward one. constexpr static uint64_t power_of_five_128[number_of_entries] = { 0xeef453d6923bd65a, 0x113faa2906a13b3f, 0x9558b4661b6565f8, 0x4ac7ca59a424c507, 0xbaaee17fa23ebf76, 0x5d79bcf00d2df649, 0xe95a99df8ace6f53, 0xf4d82c2c107973dc, 0x91d8a02bb6c10594, 0x79071b9b8a4be869, 0xb64ec836a47146f9, 0x9748e2826cdee284, 0xe3e27a444d8d98b7, 0xfd1b1b2308169b25, 0x8e6d8c6ab0787f72, 0xfe30f0f5e50e20f7, 0xb208ef855c969f4f, 0xbdbd2d335e51a935, 0xde8b2b66b3bc4723, 0xad2c788035e61382, 0x8b16fb203055ac76, 0x4c3bcb5021afcc31, 0xaddcb9e83c6b1793, 0xdf4abe242a1bbf3d, 0xd953e8624b85dd78, 0xd71d6dad34a2af0d, 0x87d4713d6f33aa6b, 0x8672648c40e5ad68, 0xa9c98d8ccb009506, 0x680efdaf511f18c2, 0xd43bf0effdc0ba48, 0x212bd1b2566def2, 0x84a57695fe98746d, 0x14bb630f7604b57, 0xa5ced43b7e3e9188, 0x419ea3bd35385e2d, 0xcf42894a5dce35ea, 0x52064cac828675b9, 0x818995ce7aa0e1b2, 0x7343efebd1940993, 0xa1ebfb4219491a1f, 0x1014ebe6c5f90bf8, 0xca66fa129f9b60a6, 0xd41a26e077774ef6, 0xfd00b897478238d0, 0x8920b098955522b4, 0x9e20735e8cb16382, 0x55b46e5f5d5535b0, 0xc5a890362fddbc62, 0xeb2189f734aa831d, 0xf712b443bbd52b7b, 0xa5e9ec7501d523e4, 0x9a6bb0aa55653b2d, 0x47b233c92125366e, 0xc1069cd4eabe89f8, 0x999ec0bb696e840a, 0xf148440a256e2c76, 0xc00670ea43ca250d, 0x96cd2a865764dbca, 0x380406926a5e5728, 0xbc807527ed3e12bc, 0xc605083704f5ecf2, 0xeba09271e88d976b, 0xf7864a44c633682e, 0x93445b8731587ea3, 0x7ab3ee6afbe0211d, 0xb8157268fdae9e4c, 0x5960ea05bad82964, 0xe61acf033d1a45df, 0x6fb92487298e33bd, 0x8fd0c16206306bab, 0xa5d3b6d479f8e056, 0xb3c4f1ba87bc8696, 0x8f48a4899877186c, 0xe0b62e2929aba83c, 0x331acdabfe94de87, 0x8c71dcd9ba0b4925, 0x9ff0c08b7f1d0b14, 0xaf8e5410288e1b6f, 0x7ecf0ae5ee44dd9, 0xdb71e91432b1a24a, 0xc9e82cd9f69d6150, 0x892731ac9faf056e, 0xbe311c083a225cd2, 0xab70fe17c79ac6ca, 0x6dbd630a48aaf406, 0xd64d3d9db981787d, 0x92cbbccdad5b108, 0x85f0468293f0eb4e, 0x25bbf56008c58ea5, 0xa76c582338ed2621, 0xaf2af2b80af6f24e, 0xd1476e2c07286faa, 0x1af5af660db4aee1, 0x82cca4db847945ca, 0x50d98d9fc890ed4d, 0xa37fce126597973c, 0xe50ff107bab528a0, 0xcc5fc196fefd7d0c, 0x1e53ed49a96272c8, 0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7a, 0x9faacf3df73609b1, 0x77b191618c54e9ac, 0xc795830d75038c1d, 0xd59df5b9ef6a2417, 0xf97ae3d0d2446f25, 0x4b0573286b44ad1d, 0x9becce62836ac577, 0x4ee367f9430aec32, 0xc2e801fb244576d5, 0x229c41f793cda73f, 0xf3a20279ed56d48a, 0x6b43527578c1110f, 0x9845418c345644d6, 0x830a13896b78aaa9, 0xbe5691ef416bd60c, 0x23cc986bc656d553, 0xedec366b11c6cb8f, 0x2cbfbe86b7ec8aa8, 0x94b3a202eb1c3f39, 0x7bf7d71432f3d6a9, 0xb9e08a83a5e34f07, 0xdaf5ccd93fb0cc53, 0xe858ad248f5c22c9, 0xd1b3400f8f9cff68, 0x91376c36d99995be, 0x23100809b9c21fa1, 0xb58547448ffffb2d, 0xabd40a0c2832a78a, 0xe2e69915b3fff9f9, 0x16c90c8f323f516c, 0x8dd01fad907ffc3b, 0xae3da7d97f6792e3, 0xb1442798f49ffb4a, 0x99cd11cfdf41779c, 0xdd95317f31c7fa1d, 0x40405643d711d583, 0x8a7d3eef7f1cfc52, 0x482835ea666b2572, 0xad1c8eab5ee43b66, 0xda3243650005eecf, 0xd863b256369d4a40, 0x90bed43e40076a82, 0x873e4f75e2224e68, 0x5a7744a6e804a291, 0xa90de3535aaae202, 0x711515d0a205cb36, 0xd3515c2831559a83, 0xd5a5b44ca873e03, 0x8412d9991ed58091, 0xe858790afe9486c2, 0xa5178fff668ae0b6, 0x626e974dbe39a872, 0xce5d73ff402d98e3, 0xfb0a3d212dc8128f, 0x80fa687f881c7f8e, 0x7ce66634bc9d0b99, 0xa139029f6a239f72, 0x1c1fffc1ebc44e80, 0xc987434744ac874e, 0xa327ffb266b56220, 0xfbe9141915d7a922, 0x4bf1ff9f0062baa8, 0x9d71ac8fada6c9b5, 0x6f773fc3603db4a9, 0xc4ce17b399107c22, 0xcb550fb4384d21d3, 0xf6019da07f549b2b, 0x7e2a53a146606a48, 0x99c102844f94e0fb, 0x2eda7444cbfc426d, 0xc0314325637a1939, 0xfa911155fefb5308, 0xf03d93eebc589f88, 0x793555ab7eba27ca, 0x96267c7535b763b5, 0x4bc1558b2f3458de, 0xbbb01b9283253ca2, 0x9eb1aaedfb016f16, 0xea9c227723ee8bcb, 0x465e15a979c1cadc, 0x92a1958a7675175f, 0xbfacd89ec191ec9, 0xb749faed14125d36, 0xcef980ec671f667b, 0xe51c79a85916f484, 0x82b7e12780e7401a, 0x8f31cc0937ae58d2, 0xd1b2ecb8b0908810, 0xb2fe3f0b8599ef07, 0x861fa7e6dcb4aa15, 0xdfbdcece67006ac9, 0x67a791e093e1d49a, 0x8bd6a141006042bd, 0xe0c8bb2c5c6d24e0, 0xaecc49914078536d, 0x58fae9f773886e18, 0xda7f5bf590966848, 0xaf39a475506a899e, 0x888f99797a5e012d, 0x6d8406c952429603, 0xaab37fd7d8f58178, 0xc8e5087ba6d33b83, 0xd5605fcdcf32e1d6, 0xfb1e4a9a90880a64, 0x855c3be0a17fcd26, 0x5cf2eea09a55067f, 0xa6b34ad8c9dfc06f, 0xf42faa48c0ea481e, 0xd0601d8efc57b08b, 0xf13b94daf124da26, 0x823c12795db6ce57, 0x76c53d08d6b70858, 0xa2cb1717b52481ed, 0x54768c4b0c64ca6e, 0xcb7ddcdda26da268, 0xa9942f5dcf7dfd09, 0xfe5d54150b090b02, 0xd3f93b35435d7c4c, 0x9efa548d26e5a6e1, 0xc47bc5014a1a6daf, 0xc6b8e9b0709f109a, 0x359ab6419ca1091b, 0xf867241c8cc6d4c0, 0xc30163d203c94b62, 0x9b407691d7fc44f8, 0x79e0de63425dcf1d, 0xc21094364dfb5636, 0x985915fc12f542e4, 0xf294b943e17a2bc4, 0x3e6f5b7b17b2939d, 0x979cf3ca6cec5b5a, 0xa705992ceecf9c42, 0xbd8430bd08277231, 0x50c6ff782a838353, 0xece53cec4a314ebd, 0xa4f8bf5635246428, 0x940f4613ae5ed136, 0x871b7795e136be99, 0xb913179899f68584, 0x28e2557b59846e3f, 0xe757dd7ec07426e5, 0x331aeada2fe589cf, 0x9096ea6f3848984f, 0x3ff0d2c85def7621, 0xb4bca50b065abe63, 0xfed077a756b53a9, 0xe1ebce4dc7f16dfb, 0xd3e8495912c62894, 0x8d3360f09cf6e4bd, 0x64712dd7abbbd95c, 0xb080392cc4349dec, 0xbd8d794d96aacfb3, 0xdca04777f541c567, 0xecf0d7a0fc5583a0, 0x89e42caaf9491b60, 0xf41686c49db57244, 0xac5d37d5b79b6239, 0x311c2875c522ced5, 0xd77485cb25823ac7, 0x7d633293366b828b, 0x86a8d39ef77164bc, 0xae5dff9c02033197, 0xa8530886b54dbdeb, 0xd9f57f830283fdfc, 0xd267caa862a12d66, 0xd072df63c324fd7b, 0x8380dea93da4bc60, 0x4247cb9e59f71e6d, 0xa46116538d0deb78, 0x52d9be85f074e608, 0xcd795be870516656, 0x67902e276c921f8b, 0x806bd9714632dff6, 0xba1cd8a3db53b6, 0xa086cfcd97bf97f3, 0x80e8a40eccd228a4, 0xc8a883c0fdaf7df0, 0x6122cd128006b2cd, 0xfad2a4b13d1b5d6c, 0x796b805720085f81, 0x9cc3a6eec6311a63, 0xcbe3303674053bb0, 0xc3f490aa77bd60fc, 0xbedbfc4411068a9c, 0xf4f1b4d515acb93b, 0xee92fb5515482d44, 0x991711052d8bf3c5, 0x751bdd152d4d1c4a, 0xbf5cd54678eef0b6, 0xd262d45a78a0635d, 0xef340a98172aace4, 0x86fb897116c87c34, 0x9580869f0e7aac0e, 0xd45d35e6ae3d4da0, 0xbae0a846d2195712, 0x8974836059cca109, 0xe998d258869facd7, 0x2bd1a438703fc94b, 0x91ff83775423cc06, 0x7b6306a34627ddcf, 0xb67f6455292cbf08, 0x1a3bc84c17b1d542, 0xe41f3d6a7377eeca, 0x20caba5f1d9e4a93, 0x8e938662882af53e, 0x547eb47b7282ee9c, 0xb23867fb2a35b28d, 0xe99e619a4f23aa43, 0xdec681f9f4c31f31, 0x6405fa00e2ec94d4, 0x8b3c113c38f9f37e, 0xde83bc408dd3dd04, 0xae0b158b4738705e, 0x9624ab50b148d445, 0xd98ddaee19068c76, 0x3badd624dd9b0957, 0x87f8a8d4cfa417c9, 0xe54ca5d70a80e5d6, 0xa9f6d30a038d1dbc, 0x5e9fcf4ccd211f4c, 0xd47487cc8470652b, 0x7647c3200069671f, 0x84c8d4dfd2c63f3b, 0x29ecd9f40041e073, 0xa5fb0a17c777cf09, 0xf468107100525890, 0xcf79cc9db955c2cc, 0x7182148d4066eeb4, 0x81ac1fe293d599bf, 0xc6f14cd848405530, 0xa21727db38cb002f, 0xb8ada00e5a506a7c, 0xca9cf1d206fdc03b, 0xa6d90811f0e4851c, 0xfd442e4688bd304a, 0x908f4a166d1da663, 0x9e4a9cec15763e2e, 0x9a598e4e043287fe, 0xc5dd44271ad3cdba, 0x40eff1e1853f29fd, 0xf7549530e188c128, 0xd12bee59e68ef47c, 0x9a94dd3e8cf578b9, 0x82bb74f8301958ce, 0xc13a148e3032d6e7, 0xe36a52363c1faf01, 0xf18899b1bc3f8ca1, 0xdc44e6c3cb279ac1, 0x96f5600f15a7b7e5, 0x29ab103a5ef8c0b9, 0xbcb2b812db11a5de, 0x7415d448f6b6f0e7, 0xebdf661791d60f56, 0x111b495b3464ad21, 0x936b9fcebb25c995, 0xcab10dd900beec34, 0xb84687c269ef3bfb, 0x3d5d514f40eea742, 0xe65829b3046b0afa, 0xcb4a5a3112a5112, 0x8ff71a0fe2c2e6dc, 0x47f0e785eaba72ab, 0xb3f4e093db73a093, 0x59ed216765690f56, 0xe0f218b8d25088b8, 0x306869c13ec3532c, 0x8c974f7383725573, 0x1e414218c73a13fb, 0xafbd2350644eeacf, 0xe5d1929ef90898fa, 0xdbac6c247d62a583, 0xdf45f746b74abf39, 0x894bc396ce5da772, 0x6b8bba8c328eb783, 0xab9eb47c81f5114f, 0x66ea92f3f326564, 0xd686619ba27255a2, 0xc80a537b0efefebd, 0x8613fd0145877585, 0xbd06742ce95f5f36, 0xa798fc4196e952e7, 0x2c48113823b73704, 0xd17f3b51fca3a7a0, 0xf75a15862ca504c5, 0x82ef85133de648c4, 0x9a984d73dbe722fb, 0xa3ab66580d5fdaf5, 0xc13e60d0d2e0ebba, 0xcc963fee10b7d1b3, 0x318df905079926a8, 0xffbbcfe994e5c61f, 0xfdf17746497f7052, 0x9fd561f1fd0f9bd3, 0xfeb6ea8bedefa633, 0xc7caba6e7c5382c8, 0xfe64a52ee96b8fc0, 0xf9bd690a1b68637b, 0x3dfdce7aa3c673b0, 0x9c1661a651213e2d, 0x6bea10ca65c084e, 0xc31bfa0fe5698db8, 0x486e494fcff30a62, 0xf3e2f893dec3f126, 0x5a89dba3c3efccfa, 0x986ddb5c6b3a76b7, 0xf89629465a75e01c, 0xbe89523386091465, 0xf6bbb397f1135823, 0xee2ba6c0678b597f, 0x746aa07ded582e2c, 0x94db483840b717ef, 0xa8c2a44eb4571cdc, 0xba121a4650e4ddeb, 0x92f34d62616ce413, 0xe896a0d7e51e1566, 0x77b020baf9c81d17, 0x915e2486ef32cd60, 0xace1474dc1d122e, 0xb5b5ada8aaff80b8, 0xd819992132456ba, 0xe3231912d5bf60e6, 0x10e1fff697ed6c69, 0x8df5efabc5979c8f, 0xca8d3ffa1ef463c1, 0xb1736b96b6fd83b3, 0xbd308ff8a6b17cb2, 0xddd0467c64bce4a0, 0xac7cb3f6d05ddbde, 0x8aa22c0dbef60ee4, 0x6bcdf07a423aa96b, 0xad4ab7112eb3929d, 0x86c16c98d2c953c6, 0xd89d64d57a607744, 0xe871c7bf077ba8b7, 0x87625f056c7c4a8b, 0x11471cd764ad4972, 0xa93af6c6c79b5d2d, 0xd598e40d3dd89bcf, 0xd389b47879823479, 0x4aff1d108d4ec2c3, 0x843610cb4bf160cb, 0xcedf722a585139ba, 0xa54394fe1eedb8fe, 0xc2974eb4ee658828, 0xce947a3da6a9273e, 0x733d226229feea32, 0x811ccc668829b887, 0x806357d5a3f525f, 0xa163ff802a3426a8, 0xca07c2dcb0cf26f7, 0xc9bcff6034c13052, 0xfc89b393dd02f0b5, 0xfc2c3f3841f17c67, 0xbbac2078d443ace2, 0x9d9ba7832936edc0, 0xd54b944b84aa4c0d, 0xc5029163f384a931, 0xa9e795e65d4df11, 0xf64335bcf065d37d, 0x4d4617b5ff4a16d5, 0x99ea0196163fa42e, 0x504bced1bf8e4e45, 0xc06481fb9bcf8d39, 0xe45ec2862f71e1d6, 0xf07da27a82c37088, 0x5d767327bb4e5a4c, 0x964e858c91ba2655, 0x3a6a07f8d510f86f, 0xbbe226efb628afea, 0x890489f70a55368b, 0xeadab0aba3b2dbe5, 0x2b45ac74ccea842e, 0x92c8ae6b464fc96f, 0x3b0b8bc90012929d, 0xb77ada0617e3bbcb, 0x9ce6ebb40173744, 0xe55990879ddcaabd, 0xcc420a6a101d0515, 0x8f57fa54c2a9eab6, 0x9fa946824a12232d, 0xb32df8e9f3546564, 0x47939822dc96abf9, 0xdff9772470297ebd, 0x59787e2b93bc56f7, 0x8bfbea76c619ef36, 0x57eb4edb3c55b65a, 0xaefae51477a06b03, 0xede622920b6b23f1, 0xdab99e59958885c4, 0xe95fab368e45eced, 0x88b402f7fd75539b, 0x11dbcb0218ebb414, 0xaae103b5fcd2a881, 0xd652bdc29f26a119, 0xd59944a37c0752a2, 0x4be76d3346f0495f, 0x857fcae62d8493a5, 0x6f70a4400c562ddb, 0xa6dfbd9fb8e5b88e, 0xcb4ccd500f6bb952, 0xd097ad07a71f26b2, 0x7e2000a41346a7a7, 0x825ecc24c873782f, 0x8ed400668c0c28c8, 0xa2f67f2dfa90563b, 0x728900802f0f32fa, 0xcbb41ef979346bca, 0x4f2b40a03ad2ffb9, 0xfea126b7d78186bc, 0xe2f610c84987bfa8, 0x9f24b832e6b0f436, 0xdd9ca7d2df4d7c9, 0xc6ede63fa05d3143, 0x91503d1c79720dbb, 0xf8a95fcf88747d94, 0x75a44c6397ce912a, 0x9b69dbe1b548ce7c, 0xc986afbe3ee11aba, 0xc24452da229b021b, 0xfbe85badce996168, 0xf2d56790ab41c2a2, 0xfae27299423fb9c3, 0x97c560ba6b0919a5, 0xdccd879fc967d41a, 0xbdb6b8e905cb600f, 0x5400e987bbc1c920, 0xed246723473e3813, 0x290123e9aab23b68, 0x9436c0760c86e30b, 0xf9a0b6720aaf6521, 0xb94470938fa89bce, 0xf808e40e8d5b3e69, 0xe7958cb87392c2c2, 0xb60b1d1230b20e04, 0x90bd77f3483bb9b9, 0xb1c6f22b5e6f48c2, 0xb4ecd5f01a4aa828, 0x1e38aeb6360b1af3, 0xe2280b6c20dd5232, 0x25c6da63c38de1b0, 0x8d590723948a535f, 0x579c487e5a38ad0e, 0xb0af48ec79ace837, 0x2d835a9df0c6d851, 0xdcdb1b2798182244, 0xf8e431456cf88e65, 0x8a08f0f8bf0f156b, 0x1b8e9ecb641b58ff, 0xac8b2d36eed2dac5, 0xe272467e3d222f3f, 0xd7adf884aa879177, 0x5b0ed81dcc6abb0f, 0x86ccbb52ea94baea, 0x98e947129fc2b4e9, 0xa87fea27a539e9a5, 0x3f2398d747b36224, 0xd29fe4b18e88640e, 0x8eec7f0d19a03aad, 0x83a3eeeef9153e89, 0x1953cf68300424ac, 0xa48ceaaab75a8e2b, 0x5fa8c3423c052dd7, 0xcdb02555653131b6, 0x3792f412cb06794d, 0x808e17555f3ebf11, 0xe2bbd88bbee40bd0, 0xa0b19d2ab70e6ed6, 0x5b6aceaeae9d0ec4, 0xc8de047564d20a8b, 0xf245825a5a445275, 0xfb158592be068d2e, 0xeed6e2f0f0d56712, 0x9ced737bb6c4183d, 0x55464dd69685606b, 0xc428d05aa4751e4c, 0xaa97e14c3c26b886, 0xf53304714d9265df, 0xd53dd99f4b3066a8, 0x993fe2c6d07b7fab, 0xe546a8038efe4029, 0xbf8fdb78849a5f96, 0xde98520472bdd033, 0xef73d256a5c0f77c, 0x963e66858f6d4440, 0x95a8637627989aad, 0xdde7001379a44aa8, 0xbb127c53b17ec159, 0x5560c018580d5d52, 0xe9d71b689dde71af, 0xaab8f01e6e10b4a6, 0x9226712162ab070d, 0xcab3961304ca70e8, 0xb6b00d69bb55c8d1, 0x3d607b97c5fd0d22, 0xe45c10c42a2b3b05, 0x8cb89a7db77c506a, 0x8eb98a7a9a5b04e3, 0x77f3608e92adb242, 0xb267ed1940f1c61c, 0x55f038b237591ed3, 0xdf01e85f912e37a3, 0x6b6c46dec52f6688, 0x8b61313bbabce2c6, 0x2323ac4b3b3da015, 0xae397d8aa96c1b77, 0xabec975e0a0d081a, 0xd9c7dced53c72255, 0x96e7bd358c904a21, 0x881cea14545c7575, 0x7e50d64177da2e54, 0xaa242499697392d2, 0xdde50bd1d5d0b9e9, 0xd4ad2dbfc3d07787, 0x955e4ec64b44e864, 0x84ec3c97da624ab4, 0xbd5af13bef0b113e, 0xa6274bbdd0fadd61, 0xecb1ad8aeacdd58e, 0xcfb11ead453994ba, 0x67de18eda5814af2, 0x81ceb32c4b43fcf4, 0x80eacf948770ced7, 0xa2425ff75e14fc31, 0xa1258379a94d028d, 0xcad2f7f5359a3b3e, 0x96ee45813a04330, 0xfd87b5f28300ca0d, 0x8bca9d6e188853fc, 0x9e74d1b791e07e48, 0x775ea264cf55347e, 0xc612062576589dda, 0x95364afe032a819e, 0xf79687aed3eec551, 0x3a83ddbd83f52205, 0x9abe14cd44753b52, 0xc4926a9672793543, 0xc16d9a0095928a27, 0x75b7053c0f178294, 0xf1c90080baf72cb1, 0x5324c68b12dd6339, 0x971da05074da7bee, 0xd3f6fc16ebca5e04, 0xbce5086492111aea, 0x88f4bb1ca6bcf585, 0xec1e4a7db69561a5, 0x2b31e9e3d06c32e6, 0x9392ee8e921d5d07, 0x3aff322e62439fd0, 0xb877aa3236a4b449, 0x9befeb9fad487c3, 0xe69594bec44de15b, 0x4c2ebe687989a9b4, 0x901d7cf73ab0acd9, 0xf9d37014bf60a11, 0xb424dc35095cd80f, 0x538484c19ef38c95, 0xe12e13424bb40e13, 0x2865a5f206b06fba, 0x8cbccc096f5088cb, 0xf93f87b7442e45d4, 0xafebff0bcb24aafe, 0xf78f69a51539d749, 0xdbe6fecebdedd5be, 0xb573440e5a884d1c, 0x89705f4136b4a597, 0x31680a88f8953031, 0xabcc77118461cefc, 0xfdc20d2b36ba7c3e, 0xd6bf94d5e57a42bc, 0x3d32907604691b4d, 0x8637bd05af6c69b5, 0xa63f9a49c2c1b110, 0xa7c5ac471b478423, 0xfcf80dc33721d54, 0xd1b71758e219652b, 0xd3c36113404ea4a9, 0x83126e978d4fdf3b, 0x645a1cac083126ea, 0xa3d70a3d70a3d70a, 0x3d70a3d70a3d70a4, 0xcccccccccccccccc, 0xcccccccccccccccd, 0x8000000000000000, 0x0, 0xa000000000000000, 0x0, 0xc800000000000000, 0x0, 0xfa00000000000000, 0x0, 0x9c40000000000000, 0x0, 0xc350000000000000, 0x0, 0xf424000000000000, 0x0, 0x9896800000000000, 0x0, 0xbebc200000000000, 0x0, 0xee6b280000000000, 0x0, 0x9502f90000000000, 0x0, 0xba43b74000000000, 0x0, 0xe8d4a51000000000, 0x0, 0x9184e72a00000000, 0x0, 0xb5e620f480000000, 0x0, 0xe35fa931a0000000, 0x0, 0x8e1bc9bf04000000, 0x0, 0xb1a2bc2ec5000000, 0x0, 0xde0b6b3a76400000, 0x0, 0x8ac7230489e80000, 0x0, 0xad78ebc5ac620000, 0x0, 0xd8d726b7177a8000, 0x0, 0x878678326eac9000, 0x0, 0xa968163f0a57b400, 0x0, 0xd3c21bcecceda100, 0x0, 0x84595161401484a0, 0x0, 0xa56fa5b99019a5c8, 0x0, 0xcecb8f27f4200f3a, 0x0, 0x813f3978f8940984, 0x4000000000000000, 0xa18f07d736b90be5, 0x5000000000000000, 0xc9f2c9cd04674ede, 0xa400000000000000, 0xfc6f7c4045812296, 0x4d00000000000000, 0x9dc5ada82b70b59d, 0xf020000000000000, 0xc5371912364ce305, 0x6c28000000000000, 0xf684df56c3e01bc6, 0xc732000000000000, 0x9a130b963a6c115c, 0x3c7f400000000000, 0xc097ce7bc90715b3, 0x4b9f100000000000, 0xf0bdc21abb48db20, 0x1e86d40000000000, 0x96769950b50d88f4, 0x1314448000000000, 0xbc143fa4e250eb31, 0x17d955a000000000, 0xeb194f8e1ae525fd, 0x5dcfab0800000000, 0x92efd1b8d0cf37be, 0x5aa1cae500000000, 0xb7abc627050305ad, 0xf14a3d9e40000000, 0xe596b7b0c643c719, 0x6d9ccd05d0000000, 0x8f7e32ce7bea5c6f, 0xe4820023a2000000, 0xb35dbf821ae4f38b, 0xdda2802c8a800000, 0xe0352f62a19e306e, 0xd50b2037ad200000, 0x8c213d9da502de45, 0x4526f422cc340000, 0xaf298d050e4395d6, 0x9670b12b7f410000, 0xdaf3f04651d47b4c, 0x3c0cdd765f114000, 0x88d8762bf324cd0f, 0xa5880a69fb6ac800, 0xab0e93b6efee0053, 0x8eea0d047a457a00, 0xd5d238a4abe98068, 0x72a4904598d6d880, 0x85a36366eb71f041, 0x47a6da2b7f864750, 0xa70c3c40a64e6c51, 0x999090b65f67d924, 0xd0cf4b50cfe20765, 0xfff4b4e3f741cf6d, 0x82818f1281ed449f, 0xbff8f10e7a8921a4, 0xa321f2d7226895c7, 0xaff72d52192b6a0d, 0xcbea6f8ceb02bb39, 0x9bf4f8a69f764490, 0xfee50b7025c36a08, 0x2f236d04753d5b4, 0x9f4f2726179a2245, 0x1d762422c946590, 0xc722f0ef9d80aad6, 0x424d3ad2b7b97ef5, 0xf8ebad2b84e0d58b, 0xd2e0898765a7deb2, 0x9b934c3b330c8577, 0x63cc55f49f88eb2f, 0xc2781f49ffcfa6d5, 0x3cbf6b71c76b25fb, 0xf316271c7fc3908a, 0x8bef464e3945ef7a, 0x97edd871cfda3a56, 0x97758bf0e3cbb5ac, 0xbde94e8e43d0c8ec, 0x3d52eeed1cbea317, 0xed63a231d4c4fb27, 0x4ca7aaa863ee4bdd, 0x945e455f24fb1cf8, 0x8fe8caa93e74ef6a, 0xb975d6b6ee39e436, 0xb3e2fd538e122b44, 0xe7d34c64a9c85d44, 0x60dbbca87196b616, 0x90e40fbeea1d3a4a, 0xbc8955e946fe31cd, 0xb51d13aea4a488dd, 0x6babab6398bdbe41, 0xe264589a4dcdab14, 0xc696963c7eed2dd1, 0x8d7eb76070a08aec, 0xfc1e1de5cf543ca2, 0xb0de65388cc8ada8, 0x3b25a55f43294bcb, 0xdd15fe86affad912, 0x49ef0eb713f39ebe, 0x8a2dbf142dfcc7ab, 0x6e3569326c784337, 0xacb92ed9397bf996, 0x49c2c37f07965404, 0xd7e77a8f87daf7fb, 0xdc33745ec97be906, 0x86f0ac99b4e8dafd, 0x69a028bb3ded71a3, 0xa8acd7c0222311bc, 0xc40832ea0d68ce0c, 0xd2d80db02aabd62b, 0xf50a3fa490c30190, 0x83c7088e1aab65db, 0x792667c6da79e0fa, 0xa4b8cab1a1563f52, 0x577001b891185938, 0xcde6fd5e09abcf26, 0xed4c0226b55e6f86, 0x80b05e5ac60b6178, 0x544f8158315b05b4, 0xa0dc75f1778e39d6, 0x696361ae3db1c721, 0xc913936dd571c84c, 0x3bc3a19cd1e38e9, 0xfb5878494ace3a5f, 0x4ab48a04065c723, 0x9d174b2dcec0e47b, 0x62eb0d64283f9c76, 0xc45d1df942711d9a, 0x3ba5d0bd324f8394, 0xf5746577930d6500, 0xca8f44ec7ee36479, 0x9968bf6abbe85f20, 0x7e998b13cf4e1ecb, 0xbfc2ef456ae276e8, 0x9e3fedd8c321a67e, 0xefb3ab16c59b14a2, 0xc5cfe94ef3ea101e, 0x95d04aee3b80ece5, 0xbba1f1d158724a12, 0xbb445da9ca61281f, 0x2a8a6e45ae8edc97, 0xea1575143cf97226, 0xf52d09d71a3293bd, 0x924d692ca61be758, 0x593c2626705f9c56, 0xb6e0c377cfa2e12e, 0x6f8b2fb00c77836c, 0xe498f455c38b997a, 0xb6dfb9c0f956447, 0x8edf98b59a373fec, 0x4724bd4189bd5eac, 0xb2977ee300c50fe7, 0x58edec91ec2cb657, 0xdf3d5e9bc0f653e1, 0x2f2967b66737e3ed, 0x8b865b215899f46c, 0xbd79e0d20082ee74, 0xae67f1e9aec07187, 0xecd8590680a3aa11, 0xda01ee641a708de9, 0xe80e6f4820cc9495, 0x884134fe908658b2, 0x3109058d147fdcdd, 0xaa51823e34a7eede, 0xbd4b46f0599fd415, 0xd4e5e2cdc1d1ea96, 0x6c9e18ac7007c91a, 0x850fadc09923329e, 0x3e2cf6bc604ddb0, 0xa6539930bf6bff45, 0x84db8346b786151c, 0xcfe87f7cef46ff16, 0xe612641865679a63, 0x81f14fae158c5f6e, 0x4fcb7e8f3f60c07e, 0xa26da3999aef7749, 0xe3be5e330f38f09d, 0xcb090c8001ab551c, 0x5cadf5bfd3072cc5, 0xfdcb4fa002162a63, 0x73d9732fc7c8f7f6, 0x9e9f11c4014dda7e, 0x2867e7fddcdd9afa, 0xc646d63501a1511d, 0xb281e1fd541501b8, 0xf7d88bc24209a565, 0x1f225a7ca91a4226, 0x9ae757596946075f, 0x3375788de9b06958, 0xc1a12d2fc3978937, 0x52d6b1641c83ae, 0xf209787bb47d6b84, 0xc0678c5dbd23a49a, 0x9745eb4d50ce6332, 0xf840b7ba963646e0, 0xbd176620a501fbff, 0xb650e5a93bc3d898, 0xec5d3fa8ce427aff, 0xa3e51f138ab4cebe, 0x93ba47c980e98cdf, 0xc66f336c36b10137, 0xb8a8d9bbe123f017, 0xb80b0047445d4184, 0xe6d3102ad96cec1d, 0xa60dc059157491e5, 0x9043ea1ac7e41392, 0x87c89837ad68db2f, 0xb454e4a179dd1877, 0x29babe4598c311fb, 0xe16a1dc9d8545e94, 0xf4296dd6fef3d67a, 0x8ce2529e2734bb1d, 0x1899e4a65f58660c, 0xb01ae745b101e9e4, 0x5ec05dcff72e7f8f, 0xdc21a1171d42645d, 0x76707543f4fa1f73, 0x899504ae72497eba, 0x6a06494a791c53a8, 0xabfa45da0edbde69, 0x487db9d17636892, 0xd6f8d7509292d603, 0x45a9d2845d3c42b6, 0x865b86925b9bc5c2, 0xb8a2392ba45a9b2, 0xa7f26836f282b732, 0x8e6cac7768d7141e, 0xd1ef0244af2364ff, 0x3207d795430cd926, 0x8335616aed761f1f, 0x7f44e6bd49e807b8, 0xa402b9c5a8d3a6e7, 0x5f16206c9c6209a6, 0xcd036837130890a1, 0x36dba887c37a8c0f, 0x802221226be55a64, 0xc2494954da2c9789, 0xa02aa96b06deb0fd, 0xf2db9baa10b7bd6c, 0xc83553c5c8965d3d, 0x6f92829494e5acc7, 0xfa42a8b73abbf48c, 0xcb772339ba1f17f9, 0x9c69a97284b578d7, 0xff2a760414536efb, 0xc38413cf25e2d70d, 0xfef5138519684aba, 0xf46518c2ef5b8cd1, 0x7eb258665fc25d69, 0x98bf2f79d5993802, 0xef2f773ffbd97a61, 0xbeeefb584aff8603, 0xaafb550ffacfd8fa, 0xeeaaba2e5dbf6784, 0x95ba2a53f983cf38, 0x952ab45cfa97a0b2, 0xdd945a747bf26183, 0xba756174393d88df, 0x94f971119aeef9e4, 0xe912b9d1478ceb17, 0x7a37cd5601aab85d, 0x91abb422ccb812ee, 0xac62e055c10ab33a, 0xb616a12b7fe617aa, 0x577b986b314d6009, 0xe39c49765fdf9d94, 0xed5a7e85fda0b80b, 0x8e41ade9fbebc27d, 0x14588f13be847307, 0xb1d219647ae6b31c, 0x596eb2d8ae258fc8, 0xde469fbd99a05fe3, 0x6fca5f8ed9aef3bb, 0x8aec23d680043bee, 0x25de7bb9480d5854, 0xada72ccc20054ae9, 0xaf561aa79a10ae6a, 0xd910f7ff28069da4, 0x1b2ba1518094da04, 0x87aa9aff79042286, 0x90fb44d2f05d0842, 0xa99541bf57452b28, 0x353a1607ac744a53, 0xd3fa922f2d1675f2, 0x42889b8997915ce8, 0x847c9b5d7c2e09b7, 0x69956135febada11, 0xa59bc234db398c25, 0x43fab9837e699095, 0xcf02b2c21207ef2e, 0x94f967e45e03f4bb, 0x8161afb94b44f57d, 0x1d1be0eebac278f5, 0xa1ba1ba79e1632dc, 0x6462d92a69731732, 0xca28a291859bbf93, 0x7d7b8f7503cfdcfe, 0xfcb2cb35e702af78, 0x5cda735244c3d43e, 0x9defbf01b061adab, 0x3a0888136afa64a7, 0xc56baec21c7a1916, 0x88aaa1845b8fdd0, 0xf6c69a72a3989f5b, 0x8aad549e57273d45, 0x9a3c2087a63f6399, 0x36ac54e2f678864b, 0xc0cb28a98fcf3c7f, 0x84576a1bb416a7dd, 0xf0fdf2d3f3c30b9f, 0x656d44a2a11c51d5, 0x969eb7c47859e743, 0x9f644ae5a4b1b325, 0xbc4665b596706114, 0x873d5d9f0dde1fee, 0xeb57ff22fc0c7959, 0xa90cb506d155a7ea, 0x9316ff75dd87cbd8, 0x9a7f12442d588f2, 0xb7dcbf5354e9bece, 0xc11ed6d538aeb2f, 0xe5d3ef282a242e81, 0x8f1668c8a86da5fa, 0x8fa475791a569d10, 0xf96e017d694487bc, 0xb38d92d760ec4455, 0x37c981dcc395a9ac, 0xe070f78d3927556a, 0x85bbe253f47b1417, 0x8c469ab843b89562, 0x93956d7478ccec8e, 0xaf58416654a6babb, 0x387ac8d1970027b2, 0xdb2e51bfe9d0696a, 0x6997b05fcc0319e, 0x88fcf317f22241e2, 0x441fece3bdf81f03, 0xab3c2fddeeaad25a, 0xd527e81cad7626c3, 0xd60b3bd56a5586f1, 0x8a71e223d8d3b074, 0x85c7056562757456, 0xf6872d5667844e49, 0xa738c6bebb12d16c, 0xb428f8ac016561db, 0xd106f86e69d785c7, 0xe13336d701beba52, 0x82a45b450226b39c, 0xecc0024661173473, 0xa34d721642b06084, 0x27f002d7f95d0190, 0xcc20ce9bd35c78a5, 0x31ec038df7b441f4, 0xff290242c83396ce, 0x7e67047175a15271, 0x9f79a169bd203e41, 0xf0062c6e984d386, 0xc75809c42c684dd1, 0x52c07b78a3e60868, 0xf92e0c3537826145, 0xa7709a56ccdf8a82, 0x9bbcc7a142b17ccb, 0x88a66076400bb691, 0xc2abf989935ddbfe, 0x6acff893d00ea435, 0xf356f7ebf83552fe, 0x583f6b8c4124d43, 0x98165af37b2153de, 0xc3727a337a8b704a, 0xbe1bf1b059e9a8d6, 0x744f18c0592e4c5c, 0xeda2ee1c7064130c, 0x1162def06f79df73, 0x9485d4d1c63e8be7, 0x8addcb5645ac2ba8, 0xb9a74a0637ce2ee1, 0x6d953e2bd7173692, 0xe8111c87c5c1ba99, 0xc8fa8db6ccdd0437, 0x910ab1d4db9914a0, 0x1d9c9892400a22a2, 0xb54d5e4a127f59c8, 0x2503beb6d00cab4b, 0xe2a0b5dc971f303a, 0x2e44ae64840fd61d, 0x8da471a9de737e24, 0x5ceaecfed289e5d2, 0xb10d8e1456105dad, 0x7425a83e872c5f47, 0xdd50f1996b947518, 0xd12f124e28f77719, 0x8a5296ffe33cc92f, 0x82bd6b70d99aaa6f, 0xace73cbfdc0bfb7b, 0x636cc64d1001550b, 0xd8210befd30efa5a, 0x3c47f7e05401aa4e, 0x8714a775e3e95c78, 0x65acfaec34810a71, 0xa8d9d1535ce3b396, 0x7f1839a741a14d0d, 0xd31045a8341ca07c, 0x1ede48111209a050, 0x83ea2b892091e44d, 0x934aed0aab460432, 0xa4e4b66b68b65d60, 0xf81da84d5617853f, 0xce1de40642e3f4b9, 0x36251260ab9d668e, 0x80d2ae83e9ce78f3, 0xc1d72b7c6b426019, 0xa1075a24e4421730, 0xb24cf65b8612f81f, 0xc94930ae1d529cfc, 0xdee033f26797b627, 0xfb9b7cd9a4a7443c, 0x169840ef017da3b1, 0x9d412e0806e88aa5, 0x8e1f289560ee864e, 0xc491798a08a2ad4e, 0xf1a6f2bab92a27e2, 0xf5b5d7ec8acb58a2, 0xae10af696774b1db, 0x9991a6f3d6bf1765, 0xacca6da1e0a8ef29, 0xbff610b0cc6edd3f, 0x17fd090a58d32af3, 0xeff394dcff8a948e, 0xddfc4b4cef07f5b0, 0x95f83d0a1fb69cd9, 0x4abdaf101564f98e, 0xbb764c4ca7a4440f, 0x9d6d1ad41abe37f1, 0xea53df5fd18d5513, 0x84c86189216dc5ed, 0x92746b9be2f8552c, 0x32fd3cf5b4e49bb4, 0xb7118682dbb66a77, 0x3fbc8c33221dc2a1, 0xe4d5e82392a40515, 0xfabaf3feaa5334a, 0x8f05b1163ba6832d, 0x29cb4d87f2a7400e, 0xb2c71d5bca9023f8, 0x743e20e9ef511012, 0xdf78e4b2bd342cf6, 0x914da9246b255416, 0x8bab8eefb6409c1a, 0x1ad089b6c2f7548e, 0xae9672aba3d0c320, 0xa184ac2473b529b1, 0xda3c0f568cc4f3e8, 0xc9e5d72d90a2741e, 0x8865899617fb1871, 0x7e2fa67c7a658892, 0xaa7eebfb9df9de8d, 0xddbb901b98feeab7, 0xd51ea6fa85785631, 0x552a74227f3ea565, 0x8533285c936b35de, 0xd53a88958f87275f, 0xa67ff273b8460356, 0x8a892abaf368f137, 0xd01fef10a657842c, 0x2d2b7569b0432d85, 0x8213f56a67f6b29b, 0x9c3b29620e29fc73, 0xa298f2c501f45f42, 0x8349f3ba91b47b8f, 0xcb3f2f7642717713, 0x241c70a936219a73, 0xfe0efb53d30dd4d7, 0xed238cd383aa0110, 0x9ec95d1463e8a506, 0xf4363804324a40aa, 0xc67bb4597ce2ce48, 0xb143c6053edcd0d5, 0xf81aa16fdc1b81da, 0xdd94b7868e94050a, 0x9b10a4e5e9913128, 0xca7cf2b4191c8326, 0xc1d4ce1f63f57d72, 0xfd1c2f611f63a3f0, 0xf24a01a73cf2dccf, 0xbc633b39673c8cec, 0x976e41088617ca01, 0xd5be0503e085d813, 0xbd49d14aa79dbc82, 0x4b2d8644d8a74e18, 0xec9c459d51852ba2, 0xddf8e7d60ed1219e, 0x93e1ab8252f33b45, 0xcabb90e5c942b503, 0xb8da1662e7b00a17, 0x3d6a751f3b936243, 0xe7109bfba19c0c9d, 0xcc512670a783ad4, 0x906a617d450187e2, 0x27fb2b80668b24c5, 0xb484f9dc9641e9da, 0xb1f9f660802dedf6, 0xe1a63853bbd26451, 0x5e7873f8a0396973, 0x8d07e33455637eb2, 0xdb0b487b6423e1e8, 0xb049dc016abc5e5f, 0x91ce1a9a3d2cda62, 0xdc5c5301c56b75f7, 0x7641a140cc7810fb, 0x89b9b3e11b6329ba, 0xa9e904c87fcb0a9d, 0xac2820d9623bf429, 0x546345fa9fbdcd44, 0xd732290fbacaf133, 0xa97c177947ad4095, 0x867f59a9d4bed6c0, 0x49ed8eabcccc485d, 0xa81f301449ee8c70, 0x5c68f256bfff5a74, 0xd226fc195c6a2f8c, 0x73832eec6fff3111, 0x83585d8fd9c25db7, 0xc831fd53c5ff7eab, 0xa42e74f3d032f525, 0xba3e7ca8b77f5e55, 0xcd3a1230c43fb26f, 0x28ce1bd2e55f35eb, 0x80444b5e7aa7cf85, 0x7980d163cf5b81b3, 0xa0555e361951c366, 0xd7e105bcc332621f, 0xc86ab5c39fa63440, 0x8dd9472bf3fefaa7, 0xfa856334878fc150, 0xb14f98f6f0feb951, 0x9c935e00d4b9d8d2, 0x6ed1bf9a569f33d3, 0xc3b8358109e84f07, 0xa862f80ec4700c8, 0xf4a642e14c6262c8, 0xcd27bb612758c0fa, 0x98e7e9cccfbd7dbd, 0x8038d51cb897789c, 0xbf21e44003acdd2c, 0xe0470a63e6bd56c3, 0xeeea5d5004981478, 0x1858ccfce06cac74, 0x95527a5202df0ccb, 0xf37801e0c43ebc8, 0xbaa718e68396cffd, 0xd30560258f54e6ba, 0xe950df20247c83fd, 0x47c6b82ef32a2069, 0x91d28b7416cdd27e, 0x4cdc331d57fa5441, 0xb6472e511c81471d, 0xe0133fe4adf8e952, 0xe3d8f9e563a198e5, 0x58180fddd97723a6, 0x8e679c2f5e44ff8f, 0x570f09eaa7ea7648, }; }; #if FASTFLOAT_DETAIL_MUST_DEFINE_CONSTEXPR_VARIABLE template constexpr uint64_t powers_template::power_of_five_128[number_of_entries]; #endif using powers = powers_template<>; } // namespace fast_float #endif #ifndef FASTFLOAT_DECIMAL_TO_BINARY_H #define FASTFLOAT_DECIMAL_TO_BINARY_H //#include // amalgamate: included above #include #include //#include // amalgamate: included above #include //#include // amalgamate: included above namespace fast_float { // This will compute or rather approximate w * 5**q and return a pair of 64-bit // words approximating the result, with the "high" part corresponding to the // most significant bits and the low part corresponding to the least significant // bits. // template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 value128 compute_product_approximation(int64_t q, uint64_t w) { int const index = 2 * int(q - powers::smallest_power_of_five); // For small values of q, e.g., q in [0,27], the answer is always exact // because The line value128 firstproduct = full_multiplication(w, // power_of_five_128[index]); gives the exact answer. value128 firstproduct = full_multiplication(w, powers::power_of_five_128[index]); static_assert((bit_precision >= 0) && (bit_precision <= 64), " precision should be in (0,64]"); constexpr uint64_t precision_mask = (bit_precision < 64) ? (uint64_t(0xFFFFFFFFFFFFFFFF) >> bit_precision) : uint64_t(0xFFFFFFFFFFFFFFFF); if ((firstproduct.high & precision_mask) == precision_mask) { // could further guard with (lower + w < lower) // regarding the second product, we only need secondproduct.high, but our // expectation is that the compiler will optimize this extra work away if // needed. value128 secondproduct = full_multiplication(w, powers::power_of_five_128[index + 1]); firstproduct.low += secondproduct.high; if (secondproduct.high > firstproduct.low) { firstproduct.high++; } } return firstproduct; } namespace detail { /** * For q in (0,350), we have that * f = (((152170 + 65536) * q ) >> 16); * is equal to * floor(p) + q * where * p = log(5**q)/log(2) = q * log(5)/log(2) * * For negative values of q in (-400,0), we have that * f = (((152170 + 65536) * q ) >> 16); * is equal to * -ceil(p) + q * where * p = log(5**-q)/log(2) = -q * log(5)/log(2) */ constexpr fastfloat_really_inline int32_t power(int32_t q) noexcept { return (((152170 + 65536) * q) >> 16) + 63; } } // namespace detail // create an adjusted mantissa, biased by the invalid power2 // for significant digits already multiplied by 10 ** q. template fastfloat_really_inline FASTFLOAT_CONSTEXPR14 adjusted_mantissa compute_error_scaled(int64_t q, uint64_t w, int lz) noexcept { int hilz = int(w >> 63) ^ 1; adjusted_mantissa answer; answer.mantissa = w << hilz; int bias = binary::mantissa_explicit_bits() - binary::minimum_exponent(); answer.power2 = int32_t(detail::power(int32_t(q)) + bias - hilz - lz - 62 + invalid_am_bias); return answer; } // w * 10 ** q, without rounding the representation up. // the power2 in the exponent will be adjusted by invalid_am_bias. template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 adjusted_mantissa compute_error(int64_t q, uint64_t w) noexcept { int lz = leading_zeroes(w); w <<= lz; value128 product = compute_product_approximation(q, w); return compute_error_scaled(q, product.high, lz); } // Computers w * 10 ** q. // The returned value should be a valid number that simply needs to be // packed. However, in some very rare cases, the computation will fail. In such // cases, we return an adjusted_mantissa with a negative power of 2: the caller // should recompute in such cases. template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 adjusted_mantissa compute_float(int64_t q, uint64_t w) noexcept { adjusted_mantissa answer; if ((w == 0) || (q < binary::smallest_power_of_ten())) { answer.power2 = 0; answer.mantissa = 0; // result should be zero return answer; } if (q > binary::largest_power_of_ten()) { // we want to get infinity: answer.power2 = binary::infinite_power(); answer.mantissa = 0; return answer; } // At this point in time q is in [powers::smallest_power_of_five, // powers::largest_power_of_five]. // We want the most significant bit of i to be 1. Shift if needed. int lz = leading_zeroes(w); w <<= lz; // The required precision is binary::mantissa_explicit_bits() + 3 because // 1. We need the implicit bit // 2. We need an extra bit for rounding purposes // 3. We might lose a bit due to the "upperbit" routine (result too small, // requiring a shift) value128 product = compute_product_approximation(q, w); // The computed 'product' is always sufficient. // Mathematical proof: // Noble Mushtak and Daniel Lemire, Fast Number Parsing Without Fallback (to // appear) See script/mushtak_lemire.py // The "compute_product_approximation" function can be slightly slower than a // branchless approach: value128 product = compute_product(q, w); but in // practice, we can win big with the compute_product_approximation if its // additional branch is easily predicted. Which is best is data specific. int upperbit = int(product.high >> 63); int shift = upperbit + 64 - binary::mantissa_explicit_bits() - 3; answer.mantissa = product.high >> shift; answer.power2 = int32_t(detail::power(int32_t(q)) + upperbit - lz - binary::minimum_exponent()); if (answer.power2 <= 0) { // we have a subnormal? // Here have that answer.power2 <= 0 so -answer.power2 >= 0 if (-answer.power2 + 1 >= 64) { // if we have more than 64 bits below the minimum exponent, you // have a zero for sure. answer.power2 = 0; answer.mantissa = 0; // result should be zero return answer; } // next line is safe because -answer.power2 + 1 < 64 answer.mantissa >>= -answer.power2 + 1; // Thankfully, we can't have both "round-to-even" and subnormals because // "round-to-even" only occurs for powers close to 0 in the 32-bit and // and 64-bit case (with no more than 19 digits). answer.mantissa += (answer.mantissa & 1); // round up answer.mantissa >>= 1; // There is a weird scenario where we don't have a subnormal but just. // Suppose we start with 2.2250738585072013e-308, we end up // with 0x3fffffffffffff x 2^-1023-53 which is technically subnormal // whereas 0x40000000000000 x 2^-1023-53 is normal. Now, we need to round // up 0x3fffffffffffff x 2^-1023-53 and once we do, we are no longer // subnormal, but we can only know this after rounding. // So we only declare a subnormal if we are smaller than the threshold. answer.power2 = (answer.mantissa < (uint64_t(1) << binary::mantissa_explicit_bits())) ? 0 : 1; return answer; } // usually, we round *up*, but if we fall right in between and and we have an // even basis, we need to round down // We are only concerned with the cases where 5**q fits in single 64-bit word. if ((product.low <= 1) && (q >= binary::min_exponent_round_to_even()) && (q <= binary::max_exponent_round_to_even()) && ((answer.mantissa & 3) == 1)) { // we may fall between two floats! // To be in-between two floats we need that in doing // answer.mantissa = product.high >> (upperbit + 64 - // binary::mantissa_explicit_bits() - 3); // ... we dropped out only zeroes. But if this happened, then we can go // back!!! if ((answer.mantissa << shift) == product.high) { answer.mantissa &= ~uint64_t(1); // flip it so that we do not round up } } answer.mantissa += (answer.mantissa & 1); // round up answer.mantissa >>= 1; if (answer.mantissa >= (uint64_t(2) << binary::mantissa_explicit_bits())) { answer.mantissa = (uint64_t(1) << binary::mantissa_explicit_bits()); answer.power2++; // undo previous addition } answer.mantissa &= ~(uint64_t(1) << binary::mantissa_explicit_bits()); if (answer.power2 >= binary::infinite_power()) { // infinity answer.power2 = binary::infinite_power(); answer.mantissa = 0; } return answer; } } // namespace fast_float #endif #ifndef FASTFLOAT_BIGINT_H #define FASTFLOAT_BIGINT_H #include //#include // amalgamate: included above #include //#include // amalgamate: included above namespace fast_float { // the limb width: we want efficient multiplication of double the bits in // limb, or for 64-bit limbs, at least 64-bit multiplication where we can // extract the high and low parts efficiently. this is every 64-bit // architecture except for sparc, which emulates 128-bit multiplication. // we might have platforms where `CHAR_BIT` is not 8, so let's avoid // doing `8 * sizeof(limb)`. #if defined(FASTFLOAT_64BIT) && !defined(__sparc) #define FASTFLOAT_64BIT_LIMB 1 typedef uint64_t limb; constexpr size_t limb_bits = 64; #else #define FASTFLOAT_32BIT_LIMB typedef uint32_t limb; constexpr size_t limb_bits = 32; #endif typedef span limb_span; // number of bits in a bigint. this needs to be at least the number // of bits required to store the largest bigint, which is // `log2(10**(digits + max_exp))`, or `log2(10**(767 + 342))`, or // ~3600 bits, so we round to 4000. constexpr size_t bigint_bits = 4000; constexpr size_t bigint_limbs = bigint_bits / limb_bits; // vector-like type that is allocated on the stack. the entire // buffer is pre-allocated, and only the length changes. template struct stackvec { limb data[size]; // we never need more than 150 limbs uint16_t length{0}; stackvec() = default; stackvec(stackvec const &) = delete; stackvec &operator=(stackvec const &) = delete; stackvec(stackvec &&) = delete; stackvec &operator=(stackvec &&other) = delete; // create stack vector from existing limb span. FASTFLOAT_CONSTEXPR20 stackvec(limb_span s) { FASTFLOAT_ASSERT(try_extend(s)); } FASTFLOAT_CONSTEXPR14 limb &operator[](size_t index) noexcept { FASTFLOAT_DEBUG_ASSERT(index < length); return data[index]; } FASTFLOAT_CONSTEXPR14 const limb &operator[](size_t index) const noexcept { FASTFLOAT_DEBUG_ASSERT(index < length); return data[index]; } // index from the end of the container FASTFLOAT_CONSTEXPR14 const limb &rindex(size_t index) const noexcept { FASTFLOAT_DEBUG_ASSERT(index < length); size_t rindex = length - index - 1; return data[rindex]; } // set the length, without bounds checking. FASTFLOAT_CONSTEXPR14 void set_len(size_t len) noexcept { length = uint16_t(len); } constexpr size_t len() const noexcept { return length; } constexpr bool is_empty() const noexcept { return length == 0; } constexpr size_t capacity() const noexcept { return size; } // append item to vector, without bounds checking FASTFLOAT_CONSTEXPR14 void push_unchecked(limb value) noexcept { data[length] = value; length++; } // append item to vector, returning if item was added FASTFLOAT_CONSTEXPR14 bool try_push(limb value) noexcept { if (len() < capacity()) { push_unchecked(value); return true; } else { return false; } } // add items to the vector, from a span, without bounds checking FASTFLOAT_CONSTEXPR20 void extend_unchecked(limb_span s) noexcept { limb *ptr = data + length; std::copy_n(s.ptr, s.len(), ptr); set_len(len() + s.len()); } // try to add items to the vector, returning if items were added FASTFLOAT_CONSTEXPR20 bool try_extend(limb_span s) noexcept { if (len() + s.len() <= capacity()) { extend_unchecked(s); return true; } else { return false; } } // resize the vector, without bounds checking // if the new size is longer than the vector, assign value to each // appended item. FASTFLOAT_CONSTEXPR20 void resize_unchecked(size_t new_len, limb value) noexcept { if (new_len > len()) { size_t count = new_len - len(); limb *first = data + len(); limb *last = first + count; ::std::fill(first, last, value); set_len(new_len); } else { set_len(new_len); } } // try to resize the vector, returning if the vector was resized. FASTFLOAT_CONSTEXPR20 bool try_resize(size_t new_len, limb value) noexcept { if (new_len > capacity()) { return false; } else { resize_unchecked(new_len, value); return true; } } // check if any limbs are non-zero after the given index. // this needs to be done in reverse order, since the index // is relative to the most significant limbs. FASTFLOAT_CONSTEXPR14 bool nonzero(size_t index) const noexcept { while (index < len()) { if (rindex(index) != 0) { return true; } index++; } return false; } // normalize the big integer, so most-significant zero limbs are removed. FASTFLOAT_CONSTEXPR14 void normalize() noexcept { while (len() > 0 && rindex(0) == 0) { length--; } } }; fastfloat_really_inline FASTFLOAT_CONSTEXPR14 uint64_t empty_hi64(bool &truncated) noexcept { truncated = false; return 0; } fastfloat_really_inline FASTFLOAT_CONSTEXPR20 uint64_t uint64_hi64(uint64_t r0, bool &truncated) noexcept { truncated = false; int shl = leading_zeroes(r0); return r0 << shl; } fastfloat_really_inline FASTFLOAT_CONSTEXPR20 uint64_t uint64_hi64(uint64_t r0, uint64_t r1, bool &truncated) noexcept { int shl = leading_zeroes(r0); if (shl == 0) { truncated = r1 != 0; return r0; } else { int shr = 64 - shl; truncated = (r1 << shl) != 0; return (r0 << shl) | (r1 >> shr); } } fastfloat_really_inline FASTFLOAT_CONSTEXPR20 uint64_t uint32_hi64(uint32_t r0, bool &truncated) noexcept { return uint64_hi64(r0, truncated); } fastfloat_really_inline FASTFLOAT_CONSTEXPR20 uint64_t uint32_hi64(uint32_t r0, uint32_t r1, bool &truncated) noexcept { uint64_t x0 = r0; uint64_t x1 = r1; return uint64_hi64((x0 << 32) | x1, truncated); } fastfloat_really_inline FASTFLOAT_CONSTEXPR20 uint64_t uint32_hi64(uint32_t r0, uint32_t r1, uint32_t r2, bool &truncated) noexcept { uint64_t x0 = r0; uint64_t x1 = r1; uint64_t x2 = r2; return uint64_hi64(x0, (x1 << 32) | x2, truncated); } // add two small integers, checking for overflow. // we want an efficient operation. for msvc, where // we don't have built-in intrinsics, this is still // pretty fast. fastfloat_really_inline FASTFLOAT_CONSTEXPR20 limb scalar_add(limb x, limb y, bool &overflow) noexcept { limb z; // gcc and clang #if defined(__has_builtin) #if __has_builtin(__builtin_add_overflow) if (!cpp20_and_in_constexpr()) { overflow = __builtin_add_overflow(x, y, &z); return z; } #endif #endif // generic, this still optimizes correctly on MSVC. z = x + y; overflow = z < x; return z; } // multiply two small integers, getting both the high and low bits. fastfloat_really_inline FASTFLOAT_CONSTEXPR20 limb scalar_mul(limb x, limb y, limb &carry) noexcept { #ifdef FASTFLOAT_64BIT_LIMB #if defined(__SIZEOF_INT128__) // GCC and clang both define it as an extension. __uint128_t z = __uint128_t(x) * __uint128_t(y) + __uint128_t(carry); carry = limb(z >> limb_bits); return limb(z); #else // fallback, no native 128-bit integer multiplication with carry. // on msvc, this optimizes identically, somehow. value128 z = full_multiplication(x, y); bool overflow; z.low = scalar_add(z.low, carry, overflow); z.high += uint64_t(overflow); // cannot overflow carry = z.high; return z.low; #endif #else uint64_t z = uint64_t(x) * uint64_t(y) + uint64_t(carry); carry = limb(z >> limb_bits); return limb(z); #endif } // add scalar value to bigint starting from offset. // used in grade school multiplication template inline FASTFLOAT_CONSTEXPR20 bool small_add_from(stackvec &vec, limb y, size_t start) noexcept { size_t index = start; limb carry = y; bool overflow; while (carry != 0 && index < vec.len()) { vec[index] = scalar_add(vec[index], carry, overflow); carry = limb(overflow); index += 1; } if (carry != 0) { FASTFLOAT_TRY(vec.try_push(carry)); } return true; } // add scalar value to bigint. template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 bool small_add(stackvec &vec, limb y) noexcept { return small_add_from(vec, y, 0); } // multiply bigint by scalar value. template inline FASTFLOAT_CONSTEXPR20 bool small_mul(stackvec &vec, limb y) noexcept { limb carry = 0; for (size_t index = 0; index < vec.len(); index++) { vec[index] = scalar_mul(vec[index], y, carry); } if (carry != 0) { FASTFLOAT_TRY(vec.try_push(carry)); } return true; } // add bigint to bigint starting from index. // used in grade school multiplication template FASTFLOAT_CONSTEXPR20 bool large_add_from(stackvec &x, limb_span y, size_t start) noexcept { // the effective x buffer is from `xstart..x.len()`, so exit early // if we can't get that current range. if (x.len() < start || y.len() > x.len() - start) { FASTFLOAT_TRY(x.try_resize(y.len() + start, 0)); } bool carry = false; for (size_t index = 0; index < y.len(); index++) { limb xi = x[index + start]; limb yi = y[index]; bool c1 = false; bool c2 = false; xi = scalar_add(xi, yi, c1); if (carry) { xi = scalar_add(xi, 1, c2); } x[index + start] = xi; carry = c1 | c2; } // handle overflow if (carry) { FASTFLOAT_TRY(small_add_from(x, 1, y.len() + start)); } return true; } // add bigint to bigint. template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 bool large_add_from(stackvec &x, limb_span y) noexcept { return large_add_from(x, y, 0); } // grade-school multiplication algorithm template FASTFLOAT_CONSTEXPR20 bool long_mul(stackvec &x, limb_span y) noexcept { limb_span xs = limb_span(x.data, x.len()); stackvec z(xs); limb_span zs = limb_span(z.data, z.len()); if (y.len() != 0) { limb y0 = y[0]; FASTFLOAT_TRY(small_mul(x, y0)); for (size_t index = 1; index < y.len(); index++) { limb yi = y[index]; stackvec zi; if (yi != 0) { // re-use the same buffer throughout zi.set_len(0); FASTFLOAT_TRY(zi.try_extend(zs)); FASTFLOAT_TRY(small_mul(zi, yi)); limb_span zis = limb_span(zi.data, zi.len()); FASTFLOAT_TRY(large_add_from(x, zis, index)); } } } x.normalize(); return true; } // grade-school multiplication algorithm template FASTFLOAT_CONSTEXPR20 bool large_mul(stackvec &x, limb_span y) noexcept { if (y.len() == 1) { FASTFLOAT_TRY(small_mul(x, y[0])); } else { FASTFLOAT_TRY(long_mul(x, y)); } return true; } template struct pow5_tables { static constexpr uint32_t large_step = 135; static constexpr uint64_t small_power_of_5[] = { 1UL, 5UL, 25UL, 125UL, 625UL, 3125UL, 15625UL, 78125UL, 390625UL, 1953125UL, 9765625UL, 48828125UL, 244140625UL, 1220703125UL, 6103515625UL, 30517578125UL, 152587890625UL, 762939453125UL, 3814697265625UL, 19073486328125UL, 95367431640625UL, 476837158203125UL, 2384185791015625UL, 11920928955078125UL, 59604644775390625UL, 298023223876953125UL, 1490116119384765625UL, 7450580596923828125UL, }; #ifdef FASTFLOAT_64BIT_LIMB constexpr static limb large_power_of_5[] = { 1414648277510068013UL, 9180637584431281687UL, 4539964771860779200UL, 10482974169319127550UL, 198276706040285095UL}; #else constexpr static limb large_power_of_5[] = { 4279965485U, 329373468U, 4020270615U, 2137533757U, 4287402176U, 1057042919U, 1071430142U, 2440757623U, 381945767U, 46164893U}; #endif }; #if FASTFLOAT_DETAIL_MUST_DEFINE_CONSTEXPR_VARIABLE template constexpr uint32_t pow5_tables::large_step; template constexpr uint64_t pow5_tables::small_power_of_5[]; template constexpr limb pow5_tables::large_power_of_5[]; #endif // big integer type. implements a small subset of big integer // arithmetic, using simple algorithms since asymptotically // faster algorithms are slower for a small number of limbs. // all operations assume the big-integer is normalized. struct bigint : pow5_tables<> { // storage of the limbs, in little-endian order. stackvec vec; FASTFLOAT_CONSTEXPR20 bigint() : vec() {} bigint(bigint const &) = delete; bigint &operator=(bigint const &) = delete; bigint(bigint &&) = delete; bigint &operator=(bigint &&other) = delete; FASTFLOAT_CONSTEXPR20 bigint(uint64_t value) : vec() { #ifdef FASTFLOAT_64BIT_LIMB vec.push_unchecked(value); #else vec.push_unchecked(uint32_t(value)); vec.push_unchecked(uint32_t(value >> 32)); #endif vec.normalize(); } // get the high 64 bits from the vector, and if bits were truncated. // this is to get the significant digits for the float. FASTFLOAT_CONSTEXPR20 uint64_t hi64(bool &truncated) const noexcept { #ifdef FASTFLOAT_64BIT_LIMB if (vec.len() == 0) { return empty_hi64(truncated); } else if (vec.len() == 1) { return uint64_hi64(vec.rindex(0), truncated); } else { uint64_t result = uint64_hi64(vec.rindex(0), vec.rindex(1), truncated); truncated |= vec.nonzero(2); return result; } #else if (vec.len() == 0) { return empty_hi64(truncated); } else if (vec.len() == 1) { return uint32_hi64(vec.rindex(0), truncated); } else if (vec.len() == 2) { return uint32_hi64(vec.rindex(0), vec.rindex(1), truncated); } else { uint64_t result = uint32_hi64(vec.rindex(0), vec.rindex(1), vec.rindex(2), truncated); truncated |= vec.nonzero(3); return result; } #endif } // compare two big integers, returning the large value. // assumes both are normalized. if the return value is // negative, other is larger, if the return value is // positive, this is larger, otherwise they are equal. // the limbs are stored in little-endian order, so we // must compare the limbs in ever order. FASTFLOAT_CONSTEXPR20 int compare(bigint const &other) const noexcept { if (vec.len() > other.vec.len()) { return 1; } else if (vec.len() < other.vec.len()) { return -1; } else { for (size_t index = vec.len(); index > 0; index--) { limb xi = vec[index - 1]; limb yi = other.vec[index - 1]; if (xi > yi) { return 1; } else if (xi < yi) { return -1; } } return 0; } } // shift left each limb n bits, carrying over to the new limb // returns true if we were able to shift all the digits. FASTFLOAT_CONSTEXPR20 bool shl_bits(size_t n) noexcept { // Internally, for each item, we shift left by n, and add the previous // right shifted limb-bits. // For example, we transform (for u8) shifted left 2, to: // b10100100 b01000010 // b10 b10010001 b00001000 FASTFLOAT_DEBUG_ASSERT(n != 0); FASTFLOAT_DEBUG_ASSERT(n < sizeof(limb) * 8); size_t shl = n; size_t shr = limb_bits - shl; limb prev = 0; for (size_t index = 0; index < vec.len(); index++) { limb xi = vec[index]; vec[index] = (xi << shl) | (prev >> shr); prev = xi; } limb carry = prev >> shr; if (carry != 0) { return vec.try_push(carry); } return true; } // move the limbs left by `n` limbs. FASTFLOAT_CONSTEXPR20 bool shl_limbs(size_t n) noexcept { FASTFLOAT_DEBUG_ASSERT(n != 0); if (n + vec.len() > vec.capacity()) { return false; } else if (!vec.is_empty()) { // move limbs limb *dst = vec.data + n; limb const *src = vec.data; std::copy_backward(src, src + vec.len(), dst + vec.len()); // fill in empty limbs limb *first = vec.data; limb *last = first + n; ::std::fill(first, last, 0); vec.set_len(n + vec.len()); return true; } else { return true; } } // move the limbs left by `n` bits. FASTFLOAT_CONSTEXPR20 bool shl(size_t n) noexcept { size_t rem = n % limb_bits; size_t div = n / limb_bits; if (rem != 0) { FASTFLOAT_TRY(shl_bits(rem)); } if (div != 0) { FASTFLOAT_TRY(shl_limbs(div)); } return true; } // get the number of leading zeros in the bigint. FASTFLOAT_CONSTEXPR20 int ctlz() const noexcept { if (vec.is_empty()) { return 0; } else { #ifdef FASTFLOAT_64BIT_LIMB return leading_zeroes(vec.rindex(0)); #else // no use defining a specialized leading_zeroes for a 32-bit type. uint64_t r0 = vec.rindex(0); return leading_zeroes(r0 << 32); #endif } } // get the number of bits in the bigint. FASTFLOAT_CONSTEXPR20 int bit_length() const noexcept { int lz = ctlz(); return int(limb_bits * vec.len()) - lz; } FASTFLOAT_CONSTEXPR20 bool mul(limb y) noexcept { return small_mul(vec, y); } FASTFLOAT_CONSTEXPR20 bool add(limb y) noexcept { return small_add(vec, y); } // multiply as if by 2 raised to a power. FASTFLOAT_CONSTEXPR20 bool pow2(uint32_t exp) noexcept { return shl(exp); } // multiply as if by 5 raised to a power. FASTFLOAT_CONSTEXPR20 bool pow5(uint32_t exp) noexcept { // multiply by a power of 5 size_t large_length = sizeof(large_power_of_5) / sizeof(limb); limb_span large = limb_span(large_power_of_5, large_length); while (exp >= large_step) { FASTFLOAT_TRY(large_mul(vec, large)); exp -= large_step; } #ifdef FASTFLOAT_64BIT_LIMB uint32_t small_step = 27; limb max_native = 7450580596923828125UL; #else uint32_t small_step = 13; limb max_native = 1220703125U; #endif while (exp >= small_step) { FASTFLOAT_TRY(small_mul(vec, max_native)); exp -= small_step; } if (exp != 0) { // Work around clang bug https://godbolt.org/z/zedh7rrhc // This is similar to https://github.com/llvm/llvm-project/issues/47746, // except the workaround described there don't work here FASTFLOAT_TRY(small_mul( vec, limb(((void)small_power_of_5[0], small_power_of_5[exp])))); } return true; } // multiply as if by 10 raised to a power. FASTFLOAT_CONSTEXPR20 bool pow10(uint32_t exp) noexcept { FASTFLOAT_TRY(pow5(exp)); return pow2(exp); } }; } // namespace fast_float #endif #ifndef FASTFLOAT_DIGIT_COMPARISON_H #define FASTFLOAT_DIGIT_COMPARISON_H //#include // amalgamate: included above //#include // amalgamate: included above //#include // amalgamate: included above namespace fast_float { // 1e0 to 1e19 constexpr static uint64_t powers_of_ten_uint64[] = {1UL, 10UL, 100UL, 1000UL, 10000UL, 100000UL, 1000000UL, 10000000UL, 100000000UL, 1000000000UL, 10000000000UL, 100000000000UL, 1000000000000UL, 10000000000000UL, 100000000000000UL, 1000000000000000UL, 10000000000000000UL, 100000000000000000UL, 1000000000000000000UL, 10000000000000000000UL}; // calculate the exponent, in scientific notation, of the number. // this algorithm is not even close to optimized, but it has no practical // effect on performance: in order to have a faster algorithm, we'd need // to slow down performance for faster algorithms, and this is still fast. fastfloat_really_inline FASTFLOAT_CONSTEXPR14 int32_t scientific_exponent(uint64_t mantissa, int32_t exponent) noexcept { while (mantissa >= 10000) { mantissa /= 10000; exponent += 4; } while (mantissa >= 100) { mantissa /= 100; exponent += 2; } while (mantissa >= 10) { mantissa /= 10; exponent += 1; } return exponent; } // this converts a native floating-point number to an extended-precision float. template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 adjusted_mantissa to_extended(T value) noexcept { using equiv_uint = equiv_uint_t; constexpr equiv_uint exponent_mask = binary_format::exponent_mask(); constexpr equiv_uint mantissa_mask = binary_format::mantissa_mask(); constexpr equiv_uint hidden_bit_mask = binary_format::hidden_bit_mask(); adjusted_mantissa am; int32_t bias = binary_format::mantissa_explicit_bits() - binary_format::minimum_exponent(); equiv_uint bits; #if FASTFLOAT_HAS_BIT_CAST bits = std::bit_cast(value); #else ::memcpy(&bits, &value, sizeof(T)); #endif if ((bits & exponent_mask) == 0) { // denormal am.power2 = 1 - bias; am.mantissa = bits & mantissa_mask; } else { // normal am.power2 = int32_t((bits & exponent_mask) >> binary_format::mantissa_explicit_bits()); am.power2 -= bias; am.mantissa = (bits & mantissa_mask) | hidden_bit_mask; } return am; } // get the extended precision value of the halfway point between b and b+u. // we are given a native float that represents b, so we need to adjust it // halfway between b and b+u. template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 adjusted_mantissa to_extended_halfway(T value) noexcept { adjusted_mantissa am = to_extended(value); am.mantissa <<= 1; am.mantissa += 1; am.power2 -= 1; return am; } // round an extended-precision float to the nearest machine float. template fastfloat_really_inline FASTFLOAT_CONSTEXPR14 void round(adjusted_mantissa &am, callback cb) noexcept { int32_t mantissa_shift = 64 - binary_format::mantissa_explicit_bits() - 1; if (-am.power2 >= mantissa_shift) { // have a denormal float int32_t shift = -am.power2 + 1; cb(am, (shift < 64 ? shift : 64)); // check for round-up: if rounding-nearest carried us to the hidden bit. am.power2 = (am.mantissa < (uint64_t(1) << binary_format::mantissa_explicit_bits())) ? 0 : 1; return; } // have a normal float, use the default shift. cb(am, mantissa_shift); // check for carry if (am.mantissa >= (uint64_t(2) << binary_format::mantissa_explicit_bits())) { am.mantissa = (uint64_t(1) << binary_format::mantissa_explicit_bits()); am.power2++; } // check for infinite: we could have carried to an infinite power am.mantissa &= ~(uint64_t(1) << binary_format::mantissa_explicit_bits()); if (am.power2 >= binary_format::infinite_power()) { am.power2 = binary_format::infinite_power(); am.mantissa = 0; } } template fastfloat_really_inline FASTFLOAT_CONSTEXPR14 void round_nearest_tie_even(adjusted_mantissa &am, int32_t shift, callback cb) noexcept { uint64_t const mask = (shift == 64) ? UINT64_MAX : (uint64_t(1) << shift) - 1; uint64_t const halfway = (shift == 0) ? 0 : uint64_t(1) << (shift - 1); uint64_t truncated_bits = am.mantissa & mask; bool is_above = truncated_bits > halfway; bool is_halfway = truncated_bits == halfway; // shift digits into position if (shift == 64) { am.mantissa = 0; } else { am.mantissa >>= shift; } am.power2 += shift; bool is_odd = (am.mantissa & 1) == 1; am.mantissa += uint64_t(cb(is_odd, is_halfway, is_above)); } fastfloat_really_inline FASTFLOAT_CONSTEXPR14 void round_down(adjusted_mantissa &am, int32_t shift) noexcept { if (shift == 64) { am.mantissa = 0; } else { am.mantissa >>= shift; } am.power2 += shift; } template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 void skip_zeros(UC const *&first, UC const *last) noexcept { uint64_t val; while (!cpp20_and_in_constexpr() && std::distance(first, last) >= int_cmp_len()) { ::memcpy(&val, first, sizeof(uint64_t)); if (val != int_cmp_zeros()) { break; } first += int_cmp_len(); } while (first != last) { if (*first != UC('0')) { break; } first++; } } // determine if any non-zero digits were truncated. // all characters must be valid digits. template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 bool is_truncated(UC const *first, UC const *last) noexcept { // do 8-bit optimizations, can just compare to 8 literal 0s. uint64_t val; while (!cpp20_and_in_constexpr() && std::distance(first, last) >= int_cmp_len()) { ::memcpy(&val, first, sizeof(uint64_t)); if (val != int_cmp_zeros()) { return true; } first += int_cmp_len(); } while (first != last) { if (*first != UC('0')) { return true; } ++first; } return false; } template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 bool is_truncated(span s) noexcept { return is_truncated(s.ptr, s.ptr + s.len()); } template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 void parse_eight_digits(UC const *&p, limb &value, size_t &counter, size_t &count) noexcept { value = value * 100000000 + parse_eight_digits_unrolled(p); p += 8; counter += 8; count += 8; } template fastfloat_really_inline FASTFLOAT_CONSTEXPR14 void parse_one_digit(UC const *&p, limb &value, size_t &counter, size_t &count) noexcept { value = value * 10 + limb(*p - UC('0')); p++; counter++; count++; } fastfloat_really_inline FASTFLOAT_CONSTEXPR20 void add_native(bigint &big, limb power, limb value) noexcept { big.mul(power); big.add(value); } fastfloat_really_inline FASTFLOAT_CONSTEXPR20 void round_up_bigint(bigint &big, size_t &count) noexcept { // need to round-up the digits, but need to avoid rounding // ....9999 to ...10000, which could cause a false halfway point. add_native(big, 10, 1); count++; } // parse the significant digits into a big integer template inline FASTFLOAT_CONSTEXPR20 void parse_mantissa(bigint &result, parsed_number_string_t &num, size_t max_digits, size_t &digits) noexcept { // try to minimize the number of big integer and scalar multiplication. // therefore, try to parse 8 digits at a time, and multiply by the largest // scalar value (9 or 19 digits) for each step. size_t counter = 0; digits = 0; limb value = 0; #ifdef FASTFLOAT_64BIT_LIMB size_t step = 19; #else size_t step = 9; #endif // process all integer digits. UC const *p = num.integer.ptr; UC const *pend = p + num.integer.len(); skip_zeros(p, pend); // process all digits, in increments of step per loop while (p != pend) { while ((std::distance(p, pend) >= 8) && (step - counter >= 8) && (max_digits - digits >= 8)) { parse_eight_digits(p, value, counter, digits); } while (counter < step && p != pend && digits < max_digits) { parse_one_digit(p, value, counter, digits); } if (digits == max_digits) { // add the temporary value, then check if we've truncated any digits add_native(result, limb(powers_of_ten_uint64[counter]), value); bool truncated = is_truncated(p, pend); if (num.fraction.ptr != nullptr) { truncated |= is_truncated(num.fraction); } if (truncated) { round_up_bigint(result, digits); } return; } else { add_native(result, limb(powers_of_ten_uint64[counter]), value); counter = 0; value = 0; } } // add our fraction digits, if they're available. if (num.fraction.ptr != nullptr) { p = num.fraction.ptr; pend = p + num.fraction.len(); if (digits == 0) { skip_zeros(p, pend); } // process all digits, in increments of step per loop while (p != pend) { while ((std::distance(p, pend) >= 8) && (step - counter >= 8) && (max_digits - digits >= 8)) { parse_eight_digits(p, value, counter, digits); } while (counter < step && p != pend && digits < max_digits) { parse_one_digit(p, value, counter, digits); } if (digits == max_digits) { // add the temporary value, then check if we've truncated any digits add_native(result, limb(powers_of_ten_uint64[counter]), value); bool truncated = is_truncated(p, pend); if (truncated) { round_up_bigint(result, digits); } return; } else { add_native(result, limb(powers_of_ten_uint64[counter]), value); counter = 0; value = 0; } } } if (counter != 0) { add_native(result, limb(powers_of_ten_uint64[counter]), value); } } template inline FASTFLOAT_CONSTEXPR20 adjusted_mantissa positive_digit_comp(bigint &bigmant, int32_t exponent) noexcept { FASTFLOAT_ASSERT(bigmant.pow10(uint32_t(exponent))); adjusted_mantissa answer; bool truncated; answer.mantissa = bigmant.hi64(truncated); int bias = binary_format::mantissa_explicit_bits() - binary_format::minimum_exponent(); answer.power2 = bigmant.bit_length() - 64 + bias; round(answer, [truncated](adjusted_mantissa &a, int32_t shift) { round_nearest_tie_even( a, shift, [truncated](bool is_odd, bool is_halfway, bool is_above) -> bool { return is_above || (is_halfway && truncated) || (is_odd && is_halfway); }); }); return answer; } // the scaling here is quite simple: we have, for the real digits `m * 10^e`, // and for the theoretical digits `n * 2^f`. Since `e` is always negative, // to scale them identically, we do `n * 2^f * 5^-f`, so we now have `m * 2^e`. // we then need to scale by `2^(f- e)`, and then the two significant digits // are of the same magnitude. template inline FASTFLOAT_CONSTEXPR20 adjusted_mantissa negative_digit_comp( bigint &bigmant, adjusted_mantissa am, int32_t exponent) noexcept { bigint &real_digits = bigmant; int32_t real_exp = exponent; // get the value of `b`, rounded down, and get a bigint representation of b+h adjusted_mantissa am_b = am; // gcc7 buf: use a lambda to remove the noexcept qualifier bug with // -Wnoexcept-type. round(am_b, [](adjusted_mantissa &a, int32_t shift) { round_down(a, shift); }); T b; to_float(false, am_b, b); adjusted_mantissa theor = to_extended_halfway(b); bigint theor_digits(theor.mantissa); int32_t theor_exp = theor.power2; // scale real digits and theor digits to be same power. int32_t pow2_exp = theor_exp - real_exp; uint32_t pow5_exp = uint32_t(-real_exp); if (pow5_exp != 0) { FASTFLOAT_ASSERT(theor_digits.pow5(pow5_exp)); } if (pow2_exp > 0) { FASTFLOAT_ASSERT(theor_digits.pow2(uint32_t(pow2_exp))); } else if (pow2_exp < 0) { FASTFLOAT_ASSERT(real_digits.pow2(uint32_t(-pow2_exp))); } // compare digits, and use it to direct rounding int ord = real_digits.compare(theor_digits); adjusted_mantissa answer = am; round(answer, [ord](adjusted_mantissa &a, int32_t shift) { round_nearest_tie_even( a, shift, [ord](bool is_odd, bool _, bool __) -> bool { (void)_; // not needed, since we've done our comparison (void)__; // not needed, since we've done our comparison if (ord > 0) { return true; } else if (ord < 0) { return false; } else { return is_odd; } }); }); return answer; } // parse the significant digits as a big integer to unambiguously round // the significant digits. here, we are trying to determine how to round // an extended float representation close to `b+h`, halfway between `b` // (the float rounded-down) and `b+u`, the next positive float. this // algorithm is always correct, and uses one of two approaches. when // the exponent is positive relative to the significant digits (such as // 1234), we create a big-integer representation, get the high 64-bits, // determine if any lower bits are truncated, and use that to direct // rounding. in case of a negative exponent relative to the significant // digits (such as 1.2345), we create a theoretical representation of // `b` as a big-integer type, scaled to the same binary exponent as // the actual digits. we then compare the big integer representations // of both, and use that to direct rounding. template inline FASTFLOAT_CONSTEXPR20 adjusted_mantissa digit_comp(parsed_number_string_t &num, adjusted_mantissa am) noexcept { // remove the invalid exponent bias am.power2 -= invalid_am_bias; int32_t sci_exp = scientific_exponent(num.mantissa, static_cast(num.exponent)); size_t max_digits = binary_format::max_digits(); size_t digits = 0; bigint bigmant; parse_mantissa(bigmant, num, max_digits, digits); // can't underflow, since digits is at most max_digits. int32_t exponent = sci_exp + 1 - int32_t(digits); if (exponent >= 0) { return positive_digit_comp(bigmant, exponent); } else { return negative_digit_comp(bigmant, am, exponent); } } } // namespace fast_float #endif #ifndef FASTFLOAT_PARSE_NUMBER_H #define FASTFLOAT_PARSE_NUMBER_H //#include // amalgamate: included above //#include // amalgamate: included above //#include // amalgamate: included above //#include // amalgamate: included above namespace fast_float { namespace detail { /** * Special case +inf, -inf, nan, infinity, -infinity. * The case comparisons could be made much faster given that we know that the * strings a null-free and fixed. **/ template from_chars_result_t FASTFLOAT_CONSTEXPR14 parse_infnan(UC const *first, UC const *last, T &value, chars_format fmt) noexcept { from_chars_result_t answer{}; answer.ptr = first; answer.ec = std::errc(); // be optimistic // assume first < last, so dereference without checks; bool const minusSign = (*first == UC('-')); // C++17 20.19.3.(7.1) explicitly forbids '+' sign here if ((*first == UC('-')) || (uint64_t(fmt & chars_format::allow_leading_plus) && (*first == UC('+')))) { ++first; } if (last - first >= 3) { if (fastfloat_strncasecmp3(first, str_const_nan())) { answer.ptr = (first += 3); value = minusSign ? -std::numeric_limits::quiet_NaN() : std::numeric_limits::quiet_NaN(); // Check for possible nan(n-char-seq-opt), C++17 20.19.3.7, // C11 7.20.1.3.3. At least MSVC produces nan(ind) and nan(snan). if (first != last && *first == UC('(')) { for (UC const *ptr = first + 1; ptr != last; ++ptr) { if (*ptr == UC(')')) { answer.ptr = ptr + 1; // valid nan(n-char-seq-opt) break; } else if (!((UC('a') <= *ptr && *ptr <= UC('z')) || (UC('A') <= *ptr && *ptr <= UC('Z')) || (UC('0') <= *ptr && *ptr <= UC('9')) || *ptr == UC('_'))) break; // forbidden char, not nan(n-char-seq-opt) } } return answer; } if (fastfloat_strncasecmp3(first, str_const_inf())) { if ((last - first >= 8) && fastfloat_strncasecmp5(first + 3, str_const_inf() + 3)) { answer.ptr = first + 8; } else { answer.ptr = first + 3; } value = minusSign ? -std::numeric_limits::infinity() : std::numeric_limits::infinity(); return answer; } } answer.ec = std::errc::invalid_argument; return answer; } /** * Returns true if the floating-pointing rounding mode is to 'nearest'. * It is the default on most system. This function is meant to be inexpensive. * Credit : @mwalcott3 */ fastfloat_really_inline bool rounds_to_nearest() noexcept { // https://lemire.me/blog/2020/06/26/gcc-not-nearest/ #if (FLT_EVAL_METHOD != 1) && (FLT_EVAL_METHOD != 0) return false; #endif // See // A fast function to check your floating-point rounding mode // https://lemire.me/blog/2022/11/16/a-fast-function-to-check-your-floating-point-rounding-mode/ // // This function is meant to be equivalent to : // prior: #include // return fegetround() == FE_TONEAREST; // However, it is expected to be much faster than the fegetround() // function call. // // The volatile keyword prevents the compiler from computing the function // at compile-time. // There might be other ways to prevent compile-time optimizations (e.g., // asm). The value does not need to be std::numeric_limits::min(), any // small value so that 1 + x should round to 1 would do (after accounting for // excess precision, as in 387 instructions). static float volatile fmin = std::numeric_limits::min(); float fmini = fmin; // we copy it so that it gets loaded at most once. // // Explanation: // Only when fegetround() == FE_TONEAREST do we have that // fmin + 1.0f == 1.0f - fmin. // // FE_UPWARD: // fmin + 1.0f > 1 // 1.0f - fmin == 1 // // FE_DOWNWARD or FE_TOWARDZERO: // fmin + 1.0f == 1 // 1.0f - fmin < 1 // // Note: This may fail to be accurate if fast-math has been // enabled, as rounding conventions may not apply. #ifdef FASTFLOAT_VISUAL_STUDIO #pragma warning(push) // todo: is there a VS warning? // see // https://stackoverflow.com/questions/46079446/is-there-a-warning-for-floating-point-equality-checking-in-visual-studio-2013 #elif defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wfloat-equal" #elif defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wfloat-equal" #endif return (fmini + 1.0f == 1.0f - fmini); #ifdef FASTFLOAT_VISUAL_STUDIO #pragma warning(pop) #elif defined(__clang__) #pragma clang diagnostic pop #elif defined(__GNUC__) #pragma GCC diagnostic pop #endif } } // namespace detail template struct from_chars_caller { template FASTFLOAT_CONSTEXPR20 static from_chars_result_t call(UC const *first, UC const *last, T &value, parse_options_t options) noexcept { return from_chars_advanced(first, last, value, options); } }; #ifdef __STDCPP_FLOAT32_T__ template <> struct from_chars_caller { template FASTFLOAT_CONSTEXPR20 static from_chars_result_t call(UC const *first, UC const *last, std::float32_t &value, parse_options_t options) noexcept { // if std::float32_t is defined, and we are in C++23 mode; macro set for // float32; set value to float due to equivalence between float and // float32_t float val = 0.0f; auto ret = from_chars_advanced(first, last, val, options); value = val; return ret; } }; #endif #ifdef __STDCPP_FLOAT64_T__ template <> struct from_chars_caller { template FASTFLOAT_CONSTEXPR20 static from_chars_result_t call(UC const *first, UC const *last, std::float64_t &value, parse_options_t options) noexcept { // if std::float64_t is defined, and we are in C++23 mode; macro set for // float64; set value as double due to equivalence between double and // float64_t double val = 0.0; auto ret = from_chars_advanced(first, last, val, options); value = val; return ret; } }; #endif template FASTFLOAT_CONSTEXPR20 from_chars_result_t from_chars(UC const *first, UC const *last, T &value, chars_format fmt /*= chars_format::general*/) noexcept { return from_chars_caller::call(first, last, value, parse_options_t(fmt)); } template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 bool clinger_fast_path_impl(uint64_t mantissa, int64_t exponent, bool is_negative, T &value) noexcept { // The implementation of the Clinger's fast path is convoluted because // we want round-to-nearest in all cases, irrespective of the rounding mode // selected on the thread. // We proceed optimistically, assuming that detail::rounds_to_nearest() // returns true. if (binary_format::min_exponent_fast_path() <= exponent && exponent <= binary_format::max_exponent_fast_path()) { // Unfortunately, the conventional Clinger's fast path is only possible // when the system rounds to the nearest float. // // We expect the next branch to almost always be selected. // We could check it first (before the previous branch), but // there might be performance advantages at having the check // be last. if (!cpp20_and_in_constexpr() && detail::rounds_to_nearest()) { // We have that fegetround() == FE_TONEAREST. // Next is Clinger's fast path. if (mantissa <= binary_format::max_mantissa_fast_path()) { value = T(mantissa); if (exponent < 0) { value = value / binary_format::exact_power_of_ten(-exponent); } else { value = value * binary_format::exact_power_of_ten(exponent); } if (is_negative) { value = -value; } return true; } } else { // We do not have that fegetround() == FE_TONEAREST. // Next is a modified Clinger's fast path, inspired by Jakub Jelínek's // proposal if (exponent >= 0 && mantissa <= binary_format::max_mantissa_fast_path(exponent)) { #if defined(__clang__) || defined(FASTFLOAT_32BIT) // Clang may map 0 to -0.0 when fegetround() == FE_DOWNWARD if (mantissa == 0) { value = is_negative ? T(-0.) : T(0.); return true; } #endif value = T(mantissa) * binary_format::exact_power_of_ten(exponent); if (is_negative) { value = -value; } return true; } } } return false; } /** * This function overload takes parsed_number_string_t structure that is created * and populated either by from_chars_advanced function taking chars range and * parsing options or other parsing custom function implemented by user. */ template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 from_chars_result_t from_chars_advanced(parsed_number_string_t &pns, T &value) noexcept { static_assert(is_supported_float_type::value, "only some floating-point types are supported"); static_assert(is_supported_char_type::value, "only char, wchar_t, char16_t and char32_t are supported"); from_chars_result_t answer; answer.ec = std::errc(); // be optimistic answer.ptr = pns.lastmatch; if (!pns.too_many_digits && clinger_fast_path_impl(pns.mantissa, pns.exponent, pns.negative, value)) return answer; adjusted_mantissa am = compute_float>(pns.exponent, pns.mantissa); if (pns.too_many_digits && am.power2 >= 0) { if (am != compute_float>(pns.exponent, pns.mantissa + 1)) { am = compute_error>(pns.exponent, pns.mantissa); } } // If we called compute_float>(pns.exponent, pns.mantissa) // and we have an invalid power (am.power2 < 0), then we need to go the long // way around again. This is very uncommon. if (am.power2 < 0) { am = digit_comp(pns, am); } to_float(pns.negative, am, value); // Test for over/underflow. if ((pns.mantissa != 0 && am.mantissa == 0 && am.power2 == 0) || am.power2 == binary_format::infinite_power()) { answer.ec = std::errc::result_out_of_range; } return answer; } // Slow path: re-parse materializing the integer/fraction spans the hot no-span // parse skipped, then run the full algorithm. The two callers reach it only // through a fastfloat_unlikely branch, so the optimizer keeps this re-parse off // the hot path on its own (no function-level noinline needed). // from_chars_advanced already handles both the too_many_digits disambiguation // and the am.power2<0 digit_comp recompute, so both slow branches collapse to // one helper call. template FASTFLOAT_CONSTEXPR20 from_chars_result_t parse_number_slow_path(UC const *first, UC const *last, T &value, parse_options_t options, bool bjf) noexcept { parsed_number_string_t pns = bjf ? parse_number_string(first, last, options, true) : parse_number_string(first, last, options, true); return from_chars_advanced(pns, value); } template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 from_chars_result_t from_chars_float_advanced(UC const *first, UC const *last, T &value, parse_options_t options) noexcept { static_assert(is_supported_float_type::value, "only some floating-point types are supported"); static_assert(is_supported_char_type::value, "only char, wchar_t, char16_t and char32_t are supported"); chars_format const fmt = detail::adjust_for_feature_macros(options.format); from_chars_result_t answer; if (uint64_t(fmt & chars_format::skip_white_space)) { while ((first != last) && fast_float::is_space(*first)) { first++; } } if (first == last) { answer.ec = std::errc::invalid_argument; answer.ptr = first; return answer; } bool const bjf = uint64_t(fmt & detail::basic_json_fmt) != 0; // Fast path: parse WITHOUT materializing the integer/fraction spans (read // only by the rare slow paths). Skipping their stores keeps the fat // parsed_number_string_t off the hot path. store_spans is a runtime argument, // so this reuses the single parse_number_string instantiation. parsed_number_string_t pns = bjf ? parse_number_string(first, last, options, false) : parse_number_string(first, last, options, false); if (!pns.valid) { if (uint64_t(fmt & chars_format::no_infnan)) { answer.ec = std::errc::invalid_argument; answer.ptr = first; return answer; } else { return detail::parse_infnan(first, last, value, fmt); } } // Slow path A (rare): > 19 significant digits. The no-span parse left the // mantissa un-truncated and skipped the span-based recompute; the cold helper // re-parses with spans and runs the full algorithm. // // We have to disable -Wc++20-extensions for the [[unlikely]] attribute // See comment for @jwakely at // https://github.com/fastfloat/fast_float/pull/387#discussion_r3366943539 // This is unfortunate. #ifdef __clang__ #pragma clang diagnostic push #if (!defined(__APPLE_CC__) && __clang_major__ >= 10) || (__clang_major__ >= 13) #pragma clang diagnostic ignored "-Wc++20-extensions" #endif #endif if fastfloat_unlikely (pns.too_many_digits) { return parse_number_slow_path(first, last, value, options, bjf); } answer.ec = std::errc(); // be optimistic answer.ptr = pns.lastmatch; if (clinger_fast_path_impl(pns.mantissa, pns.exponent, pns.negative, value)) { return answer; } adjusted_mantissa am = compute_float>(pns.exponent, pns.mantissa); // Slow path B (rare): Eisel-Lemire could not resolve; digit_comp needs the // integer/fraction spans. Route to the cold helper (clinger there is a // dead-effect since it already failed here; the cold re-parse + digit_comp // via from_chars_advanced reproduces this branch). if fastfloat_unlikely (am.power2 < 0) { return parse_number_slow_path(first, last, value, options, bjf); } #ifdef __clang__ #pragma clang diagnostic pop #endif to_float(pns.negative, am, value); // Test for over/underflow. if ((pns.mantissa != 0 && am.mantissa == 0 && am.power2 == 0) || am.power2 == binary_format::infinite_power()) { answer.ec = std::errc::result_out_of_range; } return answer; } template FASTFLOAT_CONSTEXPR20 from_chars_result_t from_chars(UC const *first, UC const *last, T &value, int base) noexcept { static_assert(is_supported_integer_type::value, "only integer types are supported"); static_assert(is_supported_char_type::value, "only char, wchar_t, char16_t and char32_t are supported"); parse_options_t options; options.base = base; return from_chars_advanced(first, last, value, options); } template FASTFLOAT_CONSTEXPR20 typename std::enable_if::value, T>::type integer_times_pow10(uint64_t mantissa, int decimal_exponent) noexcept { T value; if (clinger_fast_path_impl(mantissa, decimal_exponent, false, value)) return value; adjusted_mantissa am = compute_float>(decimal_exponent, mantissa); to_float(false, am, value); return value; } template FASTFLOAT_CONSTEXPR20 typename std::enable_if::value, T>::type integer_times_pow10(int64_t mantissa, int decimal_exponent) noexcept { const bool is_negative = mantissa < 0; const uint64_t m = static_cast(is_negative ? -mantissa : mantissa); T value; if (clinger_fast_path_impl(m, decimal_exponent, is_negative, value)) return value; adjusted_mantissa am = compute_float>(decimal_exponent, m); to_float(is_negative, am, value); return value; } FASTFLOAT_CONSTEXPR20 inline double integer_times_pow10(uint64_t mantissa, int decimal_exponent) noexcept { return integer_times_pow10(mantissa, decimal_exponent); } FASTFLOAT_CONSTEXPR20 inline double integer_times_pow10(int64_t mantissa, int decimal_exponent) noexcept { return integer_times_pow10(mantissa, decimal_exponent); } // the following overloads are here to avoid surprising ambiguity for int, // unsigned, etc. template FASTFLOAT_CONSTEXPR20 typename std::enable_if::value && std::is_integral::value && !std::is_signed::value, T>::type integer_times_pow10(Int mantissa, int decimal_exponent) noexcept { return integer_times_pow10(static_cast(mantissa), decimal_exponent); } template FASTFLOAT_CONSTEXPR20 typename std::enable_if::value && std::is_integral::value && std::is_signed::value, T>::type integer_times_pow10(Int mantissa, int decimal_exponent) noexcept { return integer_times_pow10(static_cast(mantissa), decimal_exponent); } template FASTFLOAT_CONSTEXPR20 typename std::enable_if< std::is_integral::value && !std::is_signed::value, double>::type integer_times_pow10(Int mantissa, int decimal_exponent) noexcept { return integer_times_pow10(static_cast(mantissa), decimal_exponent); } template FASTFLOAT_CONSTEXPR20 typename std::enable_if< std::is_integral::value && std::is_signed::value, double>::type integer_times_pow10(Int mantissa, int decimal_exponent) noexcept { return integer_times_pow10(static_cast(mantissa), decimal_exponent); } template FASTFLOAT_CONSTEXPR20 from_chars_result_t from_chars_int_advanced(UC const *first, UC const *last, T &value, parse_options_t options) noexcept { static_assert(is_supported_integer_type::value, "only integer types are supported"); static_assert(is_supported_char_type::value, "only char, wchar_t, char16_t and char32_t are supported"); chars_format const fmt = detail::adjust_for_feature_macros(options.format); int const base = options.base; from_chars_result_t answer; if (uint64_t(fmt & chars_format::skip_white_space)) { while ((first != last) && fast_float::is_space(*first)) { first++; } } if (first == last || base < 2 || base > 36) { answer.ec = std::errc::invalid_argument; answer.ptr = first; return answer; } return parse_int_string(first, last, value, options); } template struct from_chars_advanced_caller { static_assert(TypeIx > 0, "unsupported type"); }; template <> struct from_chars_advanced_caller<1> { template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 static from_chars_result_t call(UC const *first, UC const *last, T &value, parse_options_t options) noexcept { return from_chars_float_advanced(first, last, value, options); } }; template <> struct from_chars_advanced_caller<2> { template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 static from_chars_result_t call(UC const *first, UC const *last, T &value, parse_options_t options) noexcept { return from_chars_int_advanced(first, last, value, options); } }; template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 from_chars_result_t from_chars_advanced(UC const *first, UC const *last, T &value, parse_options_t options) noexcept { return from_chars_advanced_caller< size_t(is_supported_float_type::value) + 2 * size_t(is_supported_integer_type::value)>::call(first, last, value, options); } } // namespace fast_float #endif #else #include #endif #ifdef _MSC_VER # pragma warning(pop) #elif defined(__clang__) || defined(__APPLE_CC__) # pragma clang diagnostic pop #elif defined(__GNUC__) # pragma GCC diagnostic pop #endif #endif // C4_EXT_FAST_FLOAT_HPP_ // (end ext/c4core.src/c4/ext/fast_float.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/std/vector_fwd.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_STD_VECTOR_FWD_HPP_ #define C4_STD_VECTOR_FWD_HPP_ /** @file vector_fwd.hpp Provides forward declaration of std::vector * to enable order-independent includes for use with ref * @ref c4::to_chars() and @ref c4::from_chars(). */ //#include // amalgamate: included above // NOLINTBEGIN(cert-dcl58-cpp) // forward declarations for std::vector #if defined(__GLIBCXX__) || defined(__GLIBCPP__) || defined(_MSC_VER) #if defined(_MSC_VER) __pragma(warning(push)) __pragma(warning(disable : 4643)) #endif namespace std { template class allocator; // NOLINT #ifdef _GLIBCXX_DEBUG inline namespace __debug { template class vector; // NOLINT } #else template class vector; // NOLINT #endif } // namespace std #if defined(_MSC_VER) __pragma(warning(pop)) #endif #elif defined(_LIBCPP_ABI_NAMESPACE) namespace std { inline namespace _LIBCPP_ABI_NAMESPACE { template class allocator; // NOLINT template class vector; // NOLINT } // namespace _LIBCPP_ABI_NAMESPACE } // namespace std #else #error "unknown standard library" #endif #ifndef C4CORE_SINGLE_HEADER #ifndef C4_SUBSTR_FWD_HPP_ //#include "c4/substr_fwd.hpp" // amalgamate: remove include #error "amalgamate: c4/substr_fwd.hpp must have been amalgamated before this point" #endif /* C4_SUBSTR_FWD_HPP_ */ #endif namespace c4 { template struct is_string; template struct is_writeable_string; template struct is_string>; template struct is_string>; template struct is_writeable_string>; template c4::substr to_substr(std::vector &vec); template c4::csubstr to_csubstr(std::vector const& vec); template bool operator!= (c4::csubstr ss, std::vector const& s); template bool operator== (c4::csubstr ss, std::vector const& s); template bool operator>= (c4::csubstr ss, std::vector const& s); template bool operator> (c4::csubstr ss, std::vector const& s); template bool operator<= (c4::csubstr ss, std::vector const& s); template bool operator< (c4::csubstr ss, std::vector const& s); template bool operator!= (std::vector const& s, c4::csubstr ss); template bool operator== (std::vector const& s, c4::csubstr ss); template bool operator>= (std::vector const& s, c4::csubstr ss); template bool operator> (std::vector const& s, c4::csubstr ss); template bool operator<= (std::vector const& s, c4::csubstr ss); template bool operator< (std::vector const& s, c4::csubstr ss); template size_t to_chars(c4::substr buf, std::vector const& s); template bool from_chars(c4::csubstr buf, std::vector * s); } // namespace c4 // NOLINTEND(cert-dcl58-cpp) #endif // C4_STD_VECTOR_FWD_HPP_ // (end ext/c4core.src/c4/std/vector_fwd.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/std/span_fwd.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_STD_SPAN_FWD_HPP_ #define C4_STD_SPAN_FWD_HPP_ /** @file span_fwd.hpp Provides forward declaration of std::span * to enable order-independent includes for use with ref @ref * c4::to_chars() and @ref c4::from_chars(). */ #ifndef C4CORE_SINGLE_HEADER #ifndef C4_LANGUAGE_HPP_ //#include "c4/language.hpp" // amalgamate: remove include #error "amalgamate: c4/language.hpp must have been amalgamated before this point" #endif /* C4_LANGUAGE_HPP_ */ #endif #if (C4_CPP >= 20) || defined(__DOXYGEN__) #ifndef C4CORE_SINGLE_HEADER #ifndef C4_SUBSTR_FWD_HPP_ //#include "c4/substr_fwd.hpp" // amalgamate: remove include #error "amalgamate: c4/substr_fwd.hpp must have been amalgamated before this point" #endif /* C4_SUBSTR_FWD_HPP_ */ #endif #include // AFAICT it's not possible to fwd-declare std::span namespace c4 { template struct is_string; template struct is_writeable_string; // mark std::span as a string type template<> struct is_string>; template<> struct is_string>; // mark std::span as a string type template<> struct is_string>; template<> struct is_string>; template<> struct is_writeable_string>; template<> struct is_writeable_string>; //----------------------------------------------------------------------------- c4::csubstr to_csubstr(std::span s) noexcept; c4::csubstr to_csubstr(std::span s) noexcept; c4::substr to_substr(std::span s) noexcept; //----------------------------------------------------------------------------- bool operator== (c4::csubstr ss, std::span s); bool operator!= (c4::csubstr ss, std::span s); bool operator>= (c4::csubstr ss, std::span s); bool operator> (c4::csubstr ss, std::span s); bool operator<= (c4::csubstr ss, std::span s); bool operator< (c4::csubstr ss, std::span s); bool operator== (std::span s, c4::csubstr ss); bool operator!= (std::span s, c4::csubstr ss); bool operator<= (std::span s, c4::csubstr ss); bool operator< (std::span s, c4::csubstr ss); bool operator>= (std::span s, c4::csubstr ss); bool operator> (std::span s, c4::csubstr ss); bool operator== (c4::csubstr ss, std::span s); bool operator!= (c4::csubstr ss, std::span s); bool operator>= (c4::csubstr ss, std::span s); bool operator> (c4::csubstr ss, std::span s); bool operator<= (c4::csubstr ss, std::span s); bool operator< (c4::csubstr ss, std::span s); bool operator== (std::span s, c4::csubstr ss); bool operator!= (std::span s, c4::csubstr ss); bool operator<= (std::span s, c4::csubstr ss); bool operator< (std::span s, c4::csubstr ss); bool operator>= (std::span s, c4::csubstr ss); bool operator> (std::span s, c4::csubstr ss); //----------------------------------------------------------------------------- size_t to_chars(c4::substr buf, std::span s); size_t to_chars(c4::substr buf, std::span s); bool from_chars(c4::csubstr buf, std::span * s); } // namespace c4 #endif // SPAN_AVAILABLE #endif // C4_STD_SPAN_FWD_HPP_ // (end ext/c4core.src/c4/std/span_fwd.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/std/string_fwd.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_STD_STRING_FWD_HPP_ #define C4_STD_STRING_FWD_HPP_ /** @file string_fwd.hpp Provides forward declaration of std::string * to enable order-independent includes for use with ref @ref * c4::to_chars() and @ref c4::from_chars(). */ #ifndef DOXYGEN #ifndef C4CORE_SINGLE_HEADER #ifndef C4_SUBSTR_FWD_HPP_ //#include "c4/substr_fwd.hpp" // amalgamate: remove include #error "amalgamate: c4/substr_fwd.hpp must have been amalgamated before this point" #endif /* C4_SUBSTR_FWD_HPP_ */ #endif //#include // amalgamate: included above // forward declarations for std::string #if defined(__GLIBCXX__) || defined(__GLIBCPP__) #include // use the fwd header in glibcxx #elif defined(_LIBCPP_VERSION) || defined(__APPLE_CC__) #include // use the fwd header in stdlibc++ #elif defined(_MSC_VER) #ifndef C4_ERROR_HPP_ //#include "c4/error.hpp" // amalgamate: remove include #error "amalgamate: c4/error.hpp must have been amalgamated before this point" #endif /* C4_ERROR_HPP_ */ //! @todo is there a fwd header in msvc? namespace std { C4_SUPPRESS_WARNING_MSVC_WITH_PUSH(4643) // Forward declaring 'char_traits' in namespace std is not permitted by the C++ Standard. template struct char_traits; template class allocator; template class basic_string; using string = basic_string, allocator>; C4_SUPPRESS_WARNING_MSVC_POP } /* namespace std */ #else #error "unknown standard library" #endif namespace c4 { // mark std::string as a string type template struct is_string; template<> struct is_string; template<> struct is_string; // mark std::string as a writeable string type template struct is_writeable_string; template<> struct is_writeable_string; c4::substr to_substr(std::string &s) noexcept; c4::csubstr to_csubstr(std::string const& s) noexcept; bool operator== (c4::csubstr ss, std::string const& s); bool operator!= (c4::csubstr ss, std::string const& s); bool operator>= (c4::csubstr ss, std::string const& s); bool operator> (c4::csubstr ss, std::string const& s); bool operator<= (c4::csubstr ss, std::string const& s); bool operator< (c4::csubstr ss, std::string const& s); bool operator== (std::string const& s, c4::csubstr ss); bool operator!= (std::string const& s, c4::csubstr ss); bool operator>= (std::string const& s, c4::csubstr ss); bool operator> (std::string const& s, c4::csubstr ss); bool operator<= (std::string const& s, c4::csubstr ss); bool operator< (std::string const& s, c4::csubstr ss); size_t to_chars(c4::substr buf, std::string const& s); bool from_chars(c4::csubstr buf, std::string * s); } // namespace c4 #endif // DOXYGEN #endif // C4_STD_STRING_FWD_HPP_ // (end ext/c4core.src/c4/std/string_fwd.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/std/string_view_fwd.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_STD_STRING_VIEW_FWD_HPP_ #define C4_STD_STRING_VIEW_FWD_HPP_ /** @file string_view_fwd.hpp Provides forward declaration of std::string_view * to enable order-independent includes for use with ref @ref * c4::to_chars() and @ref c4::from_chars(). */ #ifndef C4CORE_SINGLE_HEADER #ifndef C4_LANGUAGE_HPP_ //#include "c4/language.hpp" // amalgamate: remove include #error "amalgamate: c4/language.hpp must have been amalgamated before this point" #endif /* C4_LANGUAGE_HPP_ */ #endif #if (C4_CPP >= 17) || defined(__DOXYGEN__) #ifndef C4CORE_SINGLE_HEADER #ifndef C4_SUBSTR_FWD_HPP_ //#include "c4/substr_fwd.hpp" // amalgamate: remove include #error "amalgamate: c4/substr_fwd.hpp must have been amalgamated before this point" #endif /* C4_SUBSTR_FWD_HPP_ */ #endif #include // AFAICT it's not possible to fwd-declare std::string_view namespace c4 { template struct is_string; // mark std::string_view as a string type template<> struct is_string; template<> struct is_string; //----------------------------------------------------------------------------- c4::csubstr to_csubstr(std::string_view s) noexcept; //----------------------------------------------------------------------------- bool operator== (c4::csubstr ss, std::string_view s); bool operator!= (c4::csubstr ss, std::string_view s); bool operator>= (c4::csubstr ss, std::string_view s); bool operator> (c4::csubstr ss, std::string_view s); bool operator<= (c4::csubstr ss, std::string_view s); bool operator< (c4::csubstr ss, std::string_view s); bool operator== (std::string_view s, c4::csubstr ss); bool operator!= (std::string_view s, c4::csubstr ss); bool operator<= (std::string_view s, c4::csubstr ss); bool operator< (std::string_view s, c4::csubstr ss); bool operator>= (std::string_view s, c4::csubstr ss); bool operator> (std::string_view s, c4::csubstr ss); //----------------------------------------------------------------------------- size_t to_chars(c4::substr buf, std::string_view s); } // namespace c4 #endif // STRING_VIEW_AVAILABLE #endif // C4_STD_STRING_VIEW_FWD_HPP_ // (end ext/c4core.src/c4/std/string_view_fwd.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/std/std_fwd.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_STD_STD_FWD_HPP_ #define C4_STD_STD_FWD_HPP_ /** @file std_fwd.hpp includes all c4-std interop fwd files * to enable order-independent includes for use with ref @ref * c4::to_chars() and @ref c4::from_chars(). */ #ifndef C4_STD_VECTOR_FWD_HPP_ //#include "c4/std/vector_fwd.hpp" // amalgamate: remove include #error "amalgamate: c4/std/vector_fwd.hpp must have been amalgamated before this point" #endif /* C4_STD_VECTOR_FWD_HPP_ */ #ifndef C4_STD_STRING_FWD_HPP_ //#include "c4/std/string_fwd.hpp" // amalgamate: remove include #error "amalgamate: c4/std/string_fwd.hpp must have been amalgamated before this point" #endif /* C4_STD_STRING_FWD_HPP_ */ #ifndef C4_STD_SPAN_FWD_HPP_ //#include "c4/std/span_fwd.hpp" // amalgamate: remove include #error "amalgamate: c4/std/span_fwd.hpp must have been amalgamated before this point" #endif /* C4_STD_SPAN_FWD_HPP_ */ #ifndef C4_STD_STRING_VIEW_FWD_HPP_ //#include "c4/std/string_view_fwd.hpp" // amalgamate: remove include #error "amalgamate: c4/std/string_view_fwd.hpp must have been amalgamated before this point" #endif /* C4_STD_STRING_VIEW_FWD_HPP_ */ //#include "c4/std/tuple_fwd.hpp" #endif // C4_STD_STD_FWD_HPP_ // (end ext/c4core.src/c4/std/std_fwd.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/charconv.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_CHARCONV_HPP_ #define C4_CHARCONV_HPP_ /** @file charconv.hpp Lightweight generic type-safe wrappers for * converting individual values to/from strings. */ #ifndef C4_LANGUAGE_HPP_ //#include "c4/language.hpp" // amalgamate: remove include #error "amalgamate: c4/language.hpp must have been amalgamated before this point" #endif /* C4_LANGUAGE_HPP_ */ //#include // amalgamate: included above //#include // amalgamate: included above //#include // amalgamate: included above //#include // amalgamate: included above //#include // amalgamate: included above #ifndef C4_CONFIG_HPP_ //#include "c4/config.hpp" // amalgamate: remove include #error "amalgamate: c4/config.hpp must have been amalgamated before this point" #endif /* C4_CONFIG_HPP_ */ #ifndef C4_SUBSTR_HPP_ //#include "c4/substr.hpp" // amalgamate: remove include #error "amalgamate: c4/substr.hpp must have been amalgamated before this point" #endif /* C4_SUBSTR_HPP_ */ #ifndef C4_STD_STD_FWD_HPP_ //#include "c4/std/std_fwd.hpp" // amalgamate: remove include #error "amalgamate: c4/std/std_fwd.hpp must have been amalgamated before this point" #endif /* C4_STD_STD_FWD_HPP_ */ #ifndef C4_MEMORY_UTIL_HPP_ //#include "c4/memory_util.hpp" // amalgamate: remove include #error "amalgamate: c4/memory_util.hpp must have been amalgamated before this point" #endif /* C4_MEMORY_UTIL_HPP_ */ #ifndef C4CORE_NO_FAST_FLOAT # if (C4_CPP >= 17) # if defined(_MSC_VER) # if (C4_MSVC_VERSION >= C4_MSVC_VERSION_2019) // VS2017 and lower do not have these macros //# include // amalgamate: included above # define C4CORE_HAVE_STD_TOCHARS 1 # define C4CORE_HAVE_STD_FROMCHARS 0 // prefer fast_float with MSVC # define C4CORE_HAVE_FAST_FLOAT 1 # else # define C4CORE_HAVE_STD_TOCHARS 0 # define C4CORE_HAVE_STD_FROMCHARS 0 # define C4CORE_HAVE_FAST_FLOAT 1 # endif # else # if __has_include() //# include // amalgamate: included above # if defined(__cpp_lib_to_chars) # define C4CORE_HAVE_STD_TOCHARS 1 # define C4CORE_HAVE_STD_FROMCHARS 0 // glibc uses fast_float internally # define C4CORE_HAVE_FAST_FLOAT 1 # else # define C4CORE_HAVE_STD_TOCHARS 0 # define C4CORE_HAVE_STD_FROMCHARS 0 # define C4CORE_HAVE_FAST_FLOAT 1 # endif # else # define C4CORE_HAVE_STD_TOCHARS 0 # define C4CORE_HAVE_STD_FROMCHARS 0 # define C4CORE_HAVE_FAST_FLOAT 1 # endif # endif # else # define C4CORE_HAVE_STD_TOCHARS 0 # define C4CORE_HAVE_STD_FROMCHARS 0 # define C4CORE_HAVE_FAST_FLOAT 1 # endif # if C4CORE_HAVE_FAST_FLOAT #ifndef C4_EXT_FAST_FLOAT_HPP_ //# include "c4/ext/fast_float.hpp" // amalgamate: remove include #error "amalgamate: c4/ext/fast_float.hpp must have been amalgamated before this point" #endif /* C4_EXT_FAST_FLOAT_HPP_ */ # endif #elif (C4_CPP >= 17) # define C4CORE_HAVE_FAST_FLOAT 0 # if defined(_MSC_VER) # if (C4_MSVC_VERSION >= C4_MSVC_VERSION_2019) // VS2017 and lower do not have these macros //# include // amalgamate: included above # define C4CORE_HAVE_STD_TOCHARS 1 # define C4CORE_HAVE_STD_FROMCHARS 1 # else # define C4CORE_HAVE_STD_TOCHARS 0 # define C4CORE_HAVE_STD_FROMCHARS 0 # endif # else # if __has_include() //# include // amalgamate: included above # if defined(__cpp_lib_to_chars) # define C4CORE_HAVE_STD_TOCHARS 1 # define C4CORE_HAVE_STD_FROMCHARS 1 // glibc uses fast_float internally # else # define C4CORE_HAVE_STD_TOCHARS 0 # define C4CORE_HAVE_STD_FROMCHARS 0 # endif # else # define C4CORE_HAVE_STD_TOCHARS 0 # define C4CORE_HAVE_STD_FROMCHARS 0 # endif # endif #else # define C4CORE_HAVE_STD_TOCHARS 0 # define C4CORE_HAVE_STD_FROMCHARS 0 # define C4CORE_HAVE_FAST_FLOAT 0 #endif #if !C4CORE_HAVE_STD_FROMCHARS #include #endif #if defined(_MSC_VER) && !defined(__clang__) # pragma warning(push) # pragma warning(disable: 4996) // snprintf/scanf: this function or variable may be unsafe # if C4_MSVC_VERSION != C4_MSVC_VERSION_2017 # pragma warning(disable: 4800) //'int': forcing value to bool 'true' or 'false' (performance warning) # endif #elif defined(__clang__) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wtautological-constant-out-of-range-compare" # pragma clang diagnostic ignored "-Wformat-nonliteral" # pragma clang diagnostic ignored "-Wdouble-promotion" // implicit conversion increases floating-point precision # pragma clang diagnostic ignored "-Wold-style-cast" #elif defined(__GNUC__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wformat-nonliteral" # pragma GCC diagnostic ignored "-Wdouble-promotion" // implicit conversion increases floating-point precision # pragma GCC diagnostic ignored "-Wuseless-cast" # pragma GCC diagnostic ignored "-Wold-style-cast" #endif #if defined(__clang__) #define C4_NO_UBSAN_IOVRFLW __attribute__((no_sanitize("signed-integer-overflow"))) #elif defined(__GNUC__) #if __GNUC__ > 7 #define C4_NO_UBSAN_IOVRFLW __attribute__((no_sanitize("signed-integer-overflow"))) #else #define C4_NO_UBSAN_IOVRFLW #endif #else #define C4_NO_UBSAN_IOVRFLW #endif // NOLINTBEGIN(hicpp-signed-bitwise) namespace c4 { /** @defgroup doc_charconv Charconv utilities * * Lightweight, very fast generic type-safe wrappers for converting * individual values to/from strings. These are the main generic * functions: * - @ref doc_to_chars and its alias @ref xtoa(): implemented by calling @ref itoa() / @ref utoa() / @ref ftoa() / @ref dtoa() (or generically @ref xtoa()) * - @ref doc_from_chars and its alias @ref atox(): implemented by calling @ref atoi() / @ref atou() / @ref atof() / @ref atod() (or generically @ref atox()) * - @ref to_chars_sub() * - @ref from_chars_first() * - @ref xtoa() and @ref atox() are implemented in terms of @ref write_dec() / @ref read_dec() et al (see @ref doc_write / @ref doc_read()) * * And also some modest brag is in order: these functions are really * fast: faster even than C++17 `std::to_chars()` and * `std::to_chars()`, and many dozens of times faster than the * iostream abominations. * * For example, here are some benchmark comparisons for @ref * doc_from_chars (link leads to the main project README, where these * results are shown more systematically). * * * *
atox,int64_t
g++12, linux Visual Studio 2019 *
\image html linux-x86_64-gxx12.1-Release-c4core-bm-charconv-atox-mega_bytes_per_second-i64.png \image html windows-x86_64-vs2019-Release-c4core-bm-charconv-atox-mega_bytes_per_second-i64.png *
* * * *
xtoa,int64_t
g++12, linux Visual Studio 2019 *
\image html linux-x86_64-gxx12.1-Release-c4core-bm-charconv-xtoa-mega_bytes_per_second-i64.png \image html windows-x86_64-vs2019-Release-c4core-bm-charconv-xtoa-mega_bytes_per_second-i64.png *
* * To parse floating point, c4core uses * [fastfloat](https://github.com/fastfloat/fast_float), which is * extremely fast, by an even larger factor: * * * *
atox,float
g++12, linux Visual Studio 2019 *
\image html linux-x86_64-gxx12.1-Release-c4core-bm-charconv-atof-mega_bytes_per_second-float.png \image html windows-x86_64-vs2019-Release-c4core-bm-charconv-atof-mega_bytes_per_second-float.png *
* * @{ */ #if C4CORE_HAVE_STD_TOCHARS /** @warning Use only the symbol. Do not rely on the type or naked value of this enum. */ typedef enum : std::underlying_type::type { /** print the real number in floating point format (like %f) */ FTOA_FLOAT = static_cast::type>(std::chars_format::fixed), /** print the real number in scientific format (like %e) */ FTOA_SCIENT = static_cast::type>(std::chars_format::scientific), /** print the real number in flexible format (like %g) */ FTOA_FLEX = static_cast::type>(std::chars_format::general), /** print the real number in hexadecimal format (like %a) */ FTOA_HEXA = static_cast::type>(std::chars_format::hex), } RealFormat_e; #else /** @warning Use only the symbol. Do not rely on the type or naked value of this enum. */ typedef enum : char { /** print the real number in floating point format (like %f) */ FTOA_FLOAT = 'f', /** print the real number in scientific format (like %e) */ FTOA_SCIENT = 'e', /** print the real number in flexible format (like %g) */ FTOA_FLEX = 'g', /** print the real number in hexadecimal format (like %a) */ FTOA_HEXA = 'a', } RealFormat_e; #endif /** @cond dev */ /** in some platforms, int,unsigned int * are not any of int8_t...int64_t and * long,unsigned long are not any of uint8_t...uint64_t */ template struct is_fixed_length { enum : bool { /** true if T is one of the fixed length signed types */ value_i = (std::is_integral::value && (std::is_same::value || std::is_same::value || std::is_same::value || std::is_same::value)), /** true if T is one of the fixed length unsigned types */ value_u = (std::is_integral::value && (std::is_same::value || std::is_same::value || std::is_same::value || std::is_same::value)), /** true if T is one of the fixed length signed or unsigned types */ value = value_i || value_u }; }; /** @endcond */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- #if defined(_MSC_VER) && !defined(__clang__) # pragma warning(push) #elif defined(__clang__) # pragma clang diagnostic push #elif defined(__GNUC__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wconversion" # if __GNUC__ >= 6 # pragma GCC diagnostic ignored "-Wnull-dereference" # endif #endif /** @cond dev */ namespace detail { /* python command to get the values below: def dec(v): return str(v) for bits in (8, 16, 32, 64): imin, imax, umax = (-(1 << (bits - 1))), (1 << (bits - 1)) - 1, (1 << bits) - 1 for vname, v in (("imin", imin), ("imax", imax), ("umax", umax)): for f in (bin, oct, dec, hex): print(f"{bits}b: {vname}={v} {f.__name__}: len={len(f(v)):2d}: {v} {f(v)}") */ // do not use the type as the template argument because in some // platforms long!=int32 and long!=int64. Just use the numbytes // which is more generic and spares lengthy SFINAE code. template struct charconv_digits_; template using charconv_digits = charconv_digits_::value>; template<> struct charconv_digits_<1u, true> // int8_t { enum : size_t { maxdigits_bin = 1 + 2 + 8, // -128==-0b10000000 maxdigits_oct = 1 + 2 + 3, // -128==-0o200 maxdigits_dec = 1 + 3, // -128 maxdigits_hex = 1 + 2 + 2, // -128==-0x80 maxdigits_bin_nopfx = 8, // -128==-0b10000000 maxdigits_oct_nopfx = 3, // -128==-0o200 maxdigits_dec_nopfx = 3, // -128 maxdigits_hex_nopfx = 2, // -128==-0x80 }; // min values without sign! static constexpr csubstr min_value_dec() noexcept { return csubstr("128"); } static constexpr csubstr min_value_hex() noexcept { return csubstr("80"); } static constexpr csubstr min_value_oct() noexcept { return csubstr("200"); } static constexpr csubstr min_value_bin() noexcept { return csubstr("10000000"); } static constexpr csubstr max_value_dec() noexcept { return csubstr("127"); } static constexpr bool is_oct_overflow(csubstr str) noexcept { return !((str.len < 3) || (str.len == 3 && str.str[0] <= '1')); } }; template<> struct charconv_digits_<1u, false> // uint8_t { enum : size_t { maxdigits_bin = 2 + 8, // 255 0b11111111 maxdigits_oct = 2 + 3, // 255 0o377 maxdigits_dec = 3, // 255 maxdigits_hex = 2 + 2, // 255 0xff maxdigits_bin_nopfx = 8, // 255 0b11111111 maxdigits_oct_nopfx = 3, // 255 0o377 maxdigits_dec_nopfx = 3, // 255 maxdigits_hex_nopfx = 2, // 255 0xff }; static constexpr csubstr max_value_dec() noexcept { return csubstr("255"); } static constexpr bool is_oct_overflow(csubstr str) noexcept { return !((str.len < 3) || (str.len == 3 && str.str[0] <= '3')); } }; template<> struct charconv_digits_<2u, true> // int16_t { enum : size_t { maxdigits_bin = 1 + 2 + 16, // -32768 -0b1000000000000000 maxdigits_oct = 1 + 2 + 6, // -32768 -0o100000 maxdigits_dec = 1 + 5, // -32768 -32768 maxdigits_hex = 1 + 2 + 4, // -32768 -0x8000 maxdigits_bin_nopfx = 16, // -32768 -0b1000000000000000 maxdigits_oct_nopfx = 6, // -32768 -0o100000 maxdigits_dec_nopfx = 5, // -32768 -32768 maxdigits_hex_nopfx = 4, // -32768 -0x8000 }; // min values without sign! static constexpr csubstr min_value_dec() noexcept { return csubstr("32768"); } static constexpr csubstr min_value_hex() noexcept { return csubstr("8000"); } static constexpr csubstr min_value_oct() noexcept { return csubstr("100000"); } static constexpr csubstr min_value_bin() noexcept { return csubstr("1000000000000000"); } static constexpr csubstr max_value_dec() noexcept { return csubstr("32767"); } static constexpr bool is_oct_overflow(csubstr str) noexcept { return !(str.len < 6); } }; template<> struct charconv_digits_<2u, false> // uint16_t { enum : size_t { maxdigits_bin = 2 + 16, // 65535 0b1111111111111111 maxdigits_oct = 2 + 6, // 65535 0o177777 maxdigits_dec = 6, // 65535 65535 maxdigits_hex = 2 + 4, // 65535 0xffff maxdigits_bin_nopfx = 16, // 65535 0b1111111111111111 maxdigits_oct_nopfx = 6, // 65535 0o177777 maxdigits_dec_nopfx = 6, // 65535 65535 maxdigits_hex_nopfx = 4, // 65535 0xffff }; static constexpr csubstr max_value_dec() noexcept { return csubstr("65535"); } static constexpr bool is_oct_overflow(csubstr str) noexcept { return !((str.len < 6) || (str.len == 6 && str.str[0] <= '1')); } }; template<> struct charconv_digits_<4u, true> // int32_t { enum : size_t { maxdigits_bin = 1 + 2 + 32, // len=35: -2147483648 -0b10000000000000000000000000000000 maxdigits_oct = 1 + 2 + 11, // len=14: -2147483648 -0o20000000000 maxdigits_dec = 1 + 10, // len=11: -2147483648 -2147483648 maxdigits_hex = 1 + 2 + 8, // len=11: -2147483648 -0x80000000 maxdigits_bin_nopfx = 32, // len=35: -2147483648 -0b10000000000000000000000000000000 maxdigits_oct_nopfx = 11, // len=14: -2147483648 -0o20000000000 maxdigits_dec_nopfx = 10, // len=11: -2147483648 -2147483648 maxdigits_hex_nopfx = 8, // len=11: -2147483648 -0x80000000 }; // min values without sign! static constexpr csubstr min_value_dec() noexcept { return csubstr("2147483648"); } static constexpr csubstr min_value_hex() noexcept { return csubstr("80000000"); } static constexpr csubstr min_value_oct() noexcept { return csubstr("20000000000"); } static constexpr csubstr min_value_bin() noexcept { return csubstr("10000000000000000000000000000000"); } static constexpr csubstr max_value_dec() noexcept { return csubstr("2147483647"); } static constexpr bool is_oct_overflow(csubstr str) noexcept { return !((str.len < 11) || (str.len == 11 && str.str[0] <= '1')); } }; template<> struct charconv_digits_<4u, false> // uint32_t { enum : size_t { maxdigits_bin = 2 + 32, // len=34: 4294967295 0b11111111111111111111111111111111 maxdigits_oct = 2 + 11, // len=13: 4294967295 0o37777777777 maxdigits_dec = 10, // len=10: 4294967295 4294967295 maxdigits_hex = 2 + 8, // len=10: 4294967295 0xffffffff maxdigits_bin_nopfx = 32, // len=34: 4294967295 0b11111111111111111111111111111111 maxdigits_oct_nopfx = 11, // len=13: 4294967295 0o37777777777 maxdigits_dec_nopfx = 10, // len=10: 4294967295 4294967295 maxdigits_hex_nopfx = 8, // len=10: 4294967295 0xffffffff }; static constexpr csubstr max_value_dec() noexcept { return csubstr("4294967295"); } static constexpr bool is_oct_overflow(csubstr str) noexcept { return !((str.len < 11) || (str.len == 11 && str.str[0] <= '3')); } }; template<> struct charconv_digits_<8u, true> // int64_t { enum : size_t { maxdigits_bin = 1 + 2 + 64, // len=67: -9223372036854775808 -0b1000000000000000000000000000000000000000000000000000000000000000 maxdigits_oct = 1 + 2 + 22, // len=25: -9223372036854775808 -0o1000000000000000000000 maxdigits_dec = 1 + 19, // len=20: -9223372036854775808 -9223372036854775808 maxdigits_hex = 1 + 2 + 16, // len=19: -9223372036854775808 -0x8000000000000000 maxdigits_bin_nopfx = 64, // len=67: -9223372036854775808 -0b1000000000000000000000000000000000000000000000000000000000000000 maxdigits_oct_nopfx = 22, // len=25: -9223372036854775808 -0o1000000000000000000000 maxdigits_dec_nopfx = 19, // len=20: -9223372036854775808 -9223372036854775808 maxdigits_hex_nopfx = 16, // len=19: -9223372036854775808 -0x8000000000000000 }; static constexpr csubstr min_value_dec() noexcept { return csubstr("9223372036854775808"); } static constexpr csubstr min_value_hex() noexcept { return csubstr("8000000000000000"); } static constexpr csubstr min_value_oct() noexcept { return csubstr("1000000000000000000000"); } static constexpr csubstr min_value_bin() noexcept { return csubstr("1000000000000000000000000000000000000000000000000000000000000000"); } static constexpr csubstr max_value_dec() noexcept { return csubstr("9223372036854775807"); } static constexpr bool is_oct_overflow(csubstr str) noexcept { return !(str.len < 22); } }; template<> struct charconv_digits_<8u, false> // uint64_t { enum : size_t { maxdigits_bin = 2 + 64, // len=66: 18446744073709551615 0b1111111111111111111111111111111111111111111111111111111111111111 maxdigits_oct = 2 + 22, // len=24: 18446744073709551615 0o1777777777777777777777 maxdigits_dec = 20, // len=20: 18446744073709551615 18446744073709551615 maxdigits_hex = 2 + 16, // len=18: 18446744073709551615 0xffffffffffffffff maxdigits_bin_nopfx = 64, // len=66: 18446744073709551615 0b1111111111111111111111111111111111111111111111111111111111111111 maxdigits_oct_nopfx = 22, // len=24: 18446744073709551615 0o1777777777777777777777 maxdigits_dec_nopfx = 20, // len=20: 18446744073709551615 18446744073709551615 maxdigits_hex_nopfx = 16, // len=18: 18446744073709551615 0xffffffffffffffff }; static constexpr csubstr max_value_dec() noexcept { return csubstr("18446744073709551615"); } static constexpr bool is_oct_overflow(csubstr str) noexcept { return !((str.len < 22) || (str.len == 22 && str.str[0] <= '1')); } }; } // namespace detail // Helper macros, undefined below #define c4append_(c) { if C4_LIKELY(pos < buf.len) { buf.str[pos++] = static_cast(c); } else { ++pos; } } /** @endcond */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @defgroup doc_digits Get number of digits * * @note At first sight this code may look heavily branchy and * therefore inefficient. However, measurements revealed this to be * the fastest among the alternatives. * * @see https://github.com/biojppm/c4core/pull/77 * * @{ */ /** decimal digits for 8 bit integers */ template C4_CONSTEXPR14 C4_ALWAYS_INLINE auto digits_dec(T v) noexcept -> typename std::enable_if::type { C4_STATIC_ASSERT(std::is_integral::value); C4_ASSERT(v >= 0); return ((v >= 100) ? 3u : ((v >= 10) ? 2u : 1u)); } /** decimal digits for 16 bit integers */ template C4_CONSTEXPR14 C4_ALWAYS_INLINE auto digits_dec(T v) noexcept -> typename std::enable_if::type { C4_STATIC_ASSERT(std::is_integral::value); C4_ASSERT(v >= 0); return ((v >= 10000) ? 5u : (v >= 1000) ? 4u : (v >= 100) ? 3u : (v >= 10) ? 2u : 1u); } /** decimal digits for 32 bit integers */ template C4_CONSTEXPR14 C4_ALWAYS_INLINE auto digits_dec(T v) noexcept -> typename std::enable_if::type { C4_STATIC_ASSERT(std::is_integral::value); C4_ASSERT(v >= 0); return ((v >= 1000000000) ? 10u : (v >= 100000000) ? 9u : (v >= 10000000) ? 8u : (v >= 1000000) ? 7u : (v >= 100000) ? 6u : (v >= 10000) ? 5u : (v >= 1000) ? 4u : (v >= 100) ? 3u : (v >= 10) ? 2u : 1u); } /** decimal digits for 64 bit integers */ template C4_CONSTEXPR14 C4_ALWAYS_INLINE auto digits_dec(T v) noexcept -> typename std::enable_if::type { // thanks @fargies!!! // https://github.com/biojppm/c4core/pull/77#issuecomment-1063753568 C4_STATIC_ASSERT(std::is_integral::value); C4_ASSERT(v >= 0); if(v >= 1000000000) // 10 { if(v >= 100000000000000) // 15 [15-20] range { if(v >= 100000000000000000) // 18 (15 + (20 - 15) / 2) { if((typename std::make_unsigned::type)v >= 10000000000000000000u) // 20 return 20u; else return (v >= 1000000000000000000) ? 19u : 18u; } else if(v >= 10000000000000000) // 17 { return 17u; } else { return(v >= 1000000000000000) ? 16u : 15u; } } else if(v >= 1000000000000) // 13 { return (v >= 10000000000000) ? 14u : 13u; } else if(v >= 100000000000) // 12 { return 12; } else { return(v >= 10000000000) ? 11u : 10u; } } else if(v >= 10000) // 5 [5-9] range { if(v >= 10000000) // 8 return (v >= 100000000) ? 9u : 8u; else if(v >= 1000000) // 7 return 7; else return (v >= 100000) ? 6u : 5u; } else if(v >= 100) { return (v >= 1000) ? 4u : 3u; } else { return (v >= 10) ? 2u : 1u; } } /** return the number of digits required to encode an hexadecimal number. */ template C4_CONSTEXPR14 C4_ALWAYS_INLINE unsigned digits_hex(T v) noexcept { C4_STATIC_ASSERT(std::is_integral::value); C4_ASSERT(v >= 0); return v ? 1u + (msb((typename std::make_unsigned::type)v) >> 2u) : 1u; } /** return the number of digits required to encode a binary number. */ template C4_CONSTEXPR14 C4_ALWAYS_INLINE unsigned digits_bin(T v) noexcept { C4_STATIC_ASSERT(std::is_integral::value); C4_ASSERT(v >= 0); return v ? 1u + msb((typename std::make_unsigned::type)v) : 1u; } /** return the number of digits required to encode an octal number. */ template C4_CONSTEXPR14 C4_ALWAYS_INLINE unsigned digits_oct(T v_) noexcept { // TODO: is there a better way? C4_STATIC_ASSERT(std::is_integral::value); C4_ASSERT(v_ >= 0); using U = typename std::conditional::type>::type; U v = (U) v_; // safe because we require v_ >= 0 // NOLINT uint32_t n_ = 1; enum : U { b2_ = 64u, b3_ = 64u * 8u, b4_ = 64u * 8u * 8u, }; while(true) { if(v < 8u) return n_; else if(v < b2_) return n_ + 1; else if(v < b3_) return n_ + 2; else if(v < b4_) return n_ + 3; v /= (U) b4_; n_ += 4; } } /** @} */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @cond dev */ namespace detail { C4_INLINE_CONSTEXPR const char hexchars[] = "0123456789abcdef"; C4_INLINE_CONSTEXPR const char digits0099[] = "0001020304050607080910111213141516171819" "2021222324252627282930313233343536373839" "4041424344454647484950515253545556575859" "6061626364656667686970717273747576777879" "8081828384858687888990919293949596979899"; } // namespace detail /** @endcond */ C4_SUPPRESS_WARNING_GCC_PUSH C4_SUPPRESS_WARNING_GCC("-Warray-bounds") // gcc has false positives here #if (defined(__GNUC__) && (__GNUC__ >= 7)) C4_SUPPRESS_WARNING_GCC("-Wstringop-overflow") // gcc has false positives here #endif /** @defgroup doc_write_unchecked Write with known number of digits * * Writes a value without checking the buffer length with regards to * the required number of digits to encode the value. It is the * responsibility of the caller to ensure that the provided number of * digits is enough to write the given value. Notwithstanding the * name, assertions are liberally performed, so this code is safe. * * @{ */ template C4_HOT C4_ALWAYS_INLINE void write_dec_unchecked(substr buf, T v, unsigned digits_v) noexcept { C4_STATIC_ASSERT(std::is_integral::value); C4_ASSERT(v >= 0); C4_ASSERT(buf.len >= digits_v); C4_XASSERT(digits_v == digits_dec(v)); // in bm_xtoa: checkoncelog_singlediv_write2 while(v >= T(100)) { T quo = v; quo /= T(100); const auto num = (v - quo * T(100)) << 1u; // NOLINT v = quo; buf.str[--digits_v] = detail::digits0099[num + 1]; buf.str[--digits_v] = detail::digits0099[num]; } if(v >= T(10)) { C4_ASSERT(digits_v == 2); const auto num = v << 1u; buf.str[1] = detail::digits0099[num + 1]; buf.str[0] = detail::digits0099[num]; } else { C4_ASSERT(digits_v == 1); buf.str[0] = (char)('0' + v); } } template C4_HOT C4_ALWAYS_INLINE void write_hex_unchecked(substr buf, T v, unsigned digits_v) noexcept { C4_STATIC_ASSERT(std::is_integral::value); C4_ASSERT(v >= 0); C4_ASSERT(buf.len >= digits_v); C4_XASSERT(digits_v == digits_hex(v)); do { buf.str[--digits_v] = detail::hexchars[v & T(15)]; v >>= 4; } while(v); C4_ASSERT(digits_v == 0); } template C4_HOT C4_ALWAYS_INLINE void write_oct_unchecked(substr buf, T v, unsigned digits_v) noexcept { C4_STATIC_ASSERT(std::is_integral::value); C4_ASSERT(v >= 0); C4_ASSERT(buf.len >= digits_v); C4_XASSERT(digits_v == digits_oct(v)); do { buf.str[--digits_v] = (char)('0' + (v & T(7))); v >>= 3; } while(v); C4_ASSERT(digits_v == 0); } template C4_HOT C4_ALWAYS_INLINE void write_bin_unchecked(substr buf, T v, unsigned digits_v) noexcept { C4_STATIC_ASSERT(std::is_integral::value); C4_ASSERT(v >= 0); C4_ASSERT(buf.len >= digits_v); C4_XASSERT(digits_v == digits_bin(v)); do { buf.str[--digits_v] = (char)('0' + (v & T(1))); v >>= 1; } while(v); C4_ASSERT(digits_v == 0); } /** @} */ // write_unchecked //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @defgroup doc_write Write a value * * Writes a value without checking the buffer length * decimal number -- but asserting. * * @{ */ /** write an integer to a string in decimal format. This is the * lowest level (and the fastest) function to do this task. * @note does not accept negative numbers * @note the resulting string is NOT zero-terminated. * @note it is ok to call this with an empty or too-small buffer; * no writes will occur, and the required size will be returned * @return the number of characters required for the buffer. */ template C4_ALWAYS_INLINE size_t write_dec(substr buf, T v) noexcept { C4_STATIC_ASSERT(std::is_integral::value); C4_ASSERT(v >= 0); unsigned digits = digits_dec(v); if C4_LIKELY(buf.len >= digits) write_dec_unchecked(buf, v, digits); return digits; } /** write an integer to a string in hexadecimal format. This is the * lowest level (and the fastest) function to do this task. * @note does not accept negative numbers * @note does not prefix with 0x * @note the resulting string is NOT zero-terminated. * @note it is ok to call this with an empty or too-small buffer; * no writes will occur, and the required size will be returned * @return the number of characters required for the buffer. */ template C4_ALWAYS_INLINE size_t write_hex(substr buf, T v) noexcept { C4_STATIC_ASSERT(std::is_integral::value); C4_ASSERT(v >= 0); unsigned digits = digits_hex(v); if C4_LIKELY(buf.len >= digits) write_hex_unchecked(buf, v, digits); return digits; } /** write an integer to a string in octal format. This is the * lowest level (and the fastest) function to do this task. * @note does not accept negative numbers * @note does not prefix with 0o * @note the resulting string is NOT zero-terminated. * @note it is ok to call this with an empty or too-small buffer; * no writes will occur, and the required size will be returned * @return the number of characters required for the buffer. */ template C4_ALWAYS_INLINE size_t write_oct(substr buf, T v) noexcept { C4_STATIC_ASSERT(std::is_integral::value); C4_ASSERT(v >= 0); unsigned digits = digits_oct(v); if C4_LIKELY(buf.len >= digits) write_oct_unchecked(buf, v, digits); return digits; } /** write an integer to a string in binary format. This is the * lowest level (and the fastest) function to do this task. * @note does not accept negative numbers * @note does not prefix with 0b * @note the resulting string is NOT zero-terminated. * @note it is ok to call this with an empty or too-small buffer; * no writes will occur, and the required size will be returned * @return the number of characters required for the buffer. */ template C4_ALWAYS_INLINE size_t write_bin(substr buf, T v) noexcept { C4_STATIC_ASSERT(std::is_integral::value); C4_ASSERT(v >= 0); unsigned digits = digits_bin(v); C4_ASSERT(digits > 0); if C4_LIKELY(buf.len >= digits) write_bin_unchecked(buf, v, digits); return digits; } /** @cond dev */ namespace detail { template using NumberWriter = size_t (*)(substr, U); template writer> size_t write_num_digits(substr buf, T v, size_t num_digits) noexcept { C4_STATIC_ASSERT(std::is_integral::value); const size_t ret = writer(buf, v); if(ret >= num_digits) return ret; else if(ret >= buf.len || num_digits > buf.len) return num_digits; C4_ASSERT(num_digits >= ret); const size_t delta = static_cast(num_digits - ret); // NOLINT C4_ASSERT(ret + delta <= buf.len); if(ret) memmove(buf.str + delta, buf.str, ret); if(delta) memset(buf.str, '0', delta); return num_digits; } } // namespace detail /** @endcond */ /** same as c4::write_dec(), but pad with zeroes on the left such that * the resulting string is @p num_digits wide. If the given number * requires more than num_digits, then the number prevails. */ template C4_ALWAYS_INLINE size_t write_dec(substr buf, T val, size_t num_digits) noexcept { return detail::write_num_digits>(buf, val, num_digits); } /** same as c4::write_hex(), but pad with zeroes on the left such that * the resulting string is @p num_digits wide. If the given number * requires more than num_digits, then the number prevails. */ template C4_ALWAYS_INLINE size_t write_hex(substr buf, T val, size_t num_digits) noexcept { return detail::write_num_digits>(buf, val, num_digits); } /** same as c4::write_bin(), but pad with zeroes on the left such that * the resulting string is @p num_digits wide. If the given number * requires more than num_digits, then the number prevails. */ template C4_ALWAYS_INLINE size_t write_bin(substr buf, T val, size_t num_digits) noexcept { return detail::write_num_digits>(buf, val, num_digits); } /** same as c4::write_oct(), but pad with zeroes on the left such that * the resulting string is @p num_digits wide. If the given number * requires more than num_digits, then the number prevails. */ template C4_ALWAYS_INLINE size_t write_oct(substr buf, T val, size_t num_digits) noexcept { return detail::write_num_digits>(buf, val, num_digits); } /** @} */ // write C4_SUPPRESS_WARNING_GCC_POP //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- C4_SUPPRESS_WARNING_MSVC_PUSH C4_SUPPRESS_WARNING_MSVC(4365) // '=': conversion from 'int' to 'I', signed/unsigned mismatch /** @defgroup doc_read Read a value * * @{ */ /** read a decimal integer from a string. This is the * lowest level (and the fastest) function to do this task. * @note does not accept negative numbers * @note The string must be trimmed. Whitespace is not accepted. * @note the string must not be empty * @note there is no check for overflow; the value wraps around * in a way similar to the standard C/C++ overflow behavior. * For example, `read_dec("128", &val)` returns true * and val will be set to 0 because 127 is the max i8 value. * @see overflows() to find out if a number string overflows a type range * @return true if the conversion was successful (no overflow check) */ template C4_NO_UBSAN_IOVRFLW C4_ALWAYS_INLINE bool read_dec(csubstr s, I *C4_RESTRICT v) noexcept { C4_STATIC_ASSERT(std::is_integral::value); C4_ASSERT(!s.empty()); *v = 0; for(char c : s) { if C4_UNLIKELY(c < '0' || c > '9') return false; *v = ((*v) * I(10)) + (I(c) - I('0')); } return true; } /** read an hexadecimal integer from a string. This is the * lowest level (and the fastest) function to do this task. * @note does not accept negative numbers * @note does not accept leading 0x or 0X * @note the string must not be empty * @note the string must be trimmed. Whitespace is not accepted. * @note there is no check for overflow; the value wraps around * in a way similar to the standard C/C++ overflow behavior. * For example, `read_hex("80", &val)` returns true * and val will be set to 0 because 7f is the max i8 value. * @see overflows() to find out if a number string overflows a type range * @return true if the conversion was successful (no overflow check) */ template C4_NO_UBSAN_IOVRFLW C4_ALWAYS_INLINE bool read_hex(csubstr s, I *C4_RESTRICT v) noexcept { C4_STATIC_ASSERT(std::is_integral::value); C4_ASSERT(!s.empty()); *v = 0; for(char c : s) { I cv; if(c >= '0' && c <= '9') cv = I(c) - I('0'); else if(c >= 'a' && c <= 'f') cv = I(10) + (I(c) - I('a')); else if(c >= 'A' && c <= 'F') cv = I(10) + (I(c) - I('A')); else return false; *v = ((*v) * I(16)) + cv; } return true; } /** read a binary integer from a string. This is the * lowest level (and the fastest) function to do this task. * @note does not accept negative numbers * @note does not accept leading 0b or 0B * @note the string must not be empty * @note the string must be trimmed. Whitespace is not accepted. * @note there is no check for overflow; the value wraps around * in a way similar to the standard C/C++ overflow behavior. * For example, `read_bin("10000000", &val)` returns true * and val will be set to 0 because 1111111 is the max i8 value. * @see overflows() to find out if a number string overflows a type range * @return true if the conversion was successful (no overflow check) */ template C4_NO_UBSAN_IOVRFLW C4_ALWAYS_INLINE bool read_bin(csubstr s, I *C4_RESTRICT v) noexcept { C4_STATIC_ASSERT(std::is_integral::value); C4_ASSERT(!s.empty()); *v = 0; for(char c : s) { *v <<= 1; if(c == '1') *v |= 1; else if(c != '0') return false; } return true; } /** read an octal integer from a string. This is the * lowest level (and the fastest) function to do this task. * @note does not accept negative numbers * @note does not accept leading 0o or 0O * @note the string must not be empty * @note the string must be trimmed. Whitespace is not accepted. * @note there is no check for overflow; the value wraps around * in a way similar to the standard C/C++ overflow behavior. * For example, `read_oct("200", &val)` returns true * and val will be set to 0 because 177 is the max i8 value. * @see overflows() to find out if a number string overflows a type range * @return true if the conversion was successful (no overflow check) */ template C4_NO_UBSAN_IOVRFLW C4_ALWAYS_INLINE bool read_oct(csubstr s, I *C4_RESTRICT v) noexcept { C4_STATIC_ASSERT(std::is_integral::value); C4_ASSERT(!s.empty()); *v = 0; for(char c : s) { if C4_UNLIKELY(c < '0' || c > '7') return false; *v = ((*v) * I(8)) + (I(c) - I('0')); } return true; } /** @} */ C4_SUPPRESS_WARNING_MSVC_POP //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- C4_SUPPRESS_WARNING_GCC_WITH_PUSH("-Wswitch-default") /** @cond dev */ namespace detail { inline size_t _itoa2buf(substr buf, size_t pos, csubstr val) noexcept { C4_ASSERT(pos < buf.len); C4_ASSERT(pos + val.len <= buf.len); C4_ASSERT(val.len > 0); memcpy(buf.str + pos, val.str, val.len); return pos + val.len; } inline size_t _itoa2bufwithdigits(substr buf, size_t pos, size_t num_digits, csubstr val) noexcept { num_digits = num_digits > val.len ? num_digits - val.len : 0; C4_ASSERT(num_digits + val.len <= buf.len); for(size_t i = 0; i < num_digits; ++i) c4append_('0') return detail::_itoa2buf(buf, pos, val); } template C4_NO_INLINE size_t _itoadec2buf(substr buf) noexcept { using digits_type = detail::charconv_digits; if C4_UNLIKELY(buf.len < digits_type::maxdigits_dec) return digits_type::maxdigits_dec; buf.str[0] = '-'; return detail::_itoa2buf(buf, 1, digits_type::min_value_dec()); } template C4_NO_INLINE size_t _itoa2buf(substr buf, I radix) noexcept { using digits_type = detail::charconv_digits; size_t pos = 0; if C4_LIKELY(buf.len > 0) buf.str[pos++] = '-'; switch(radix) // NOLINT(hicpp-multiway-paths-covered) { case I(10): if C4_UNLIKELY(buf.len < digits_type::maxdigits_dec) return digits_type::maxdigits_dec; pos =_itoa2buf(buf, pos, digits_type::min_value_dec()); break; case I(16): if C4_UNLIKELY(buf.len < digits_type::maxdigits_hex) return digits_type::maxdigits_hex; buf.str[pos++] = '0'; buf.str[pos++] = 'x'; pos = _itoa2buf(buf, pos, digits_type::min_value_hex()); break; case I( 2): if C4_UNLIKELY(buf.len < digits_type::maxdigits_bin) return digits_type::maxdigits_bin; buf.str[pos++] = '0'; buf.str[pos++] = 'b'; pos = _itoa2buf(buf, pos, digits_type::min_value_bin()); break; case I( 8): if C4_UNLIKELY(buf.len < digits_type::maxdigits_oct) return digits_type::maxdigits_oct; buf.str[pos++] = '0'; buf.str[pos++] = 'o'; pos = _itoa2buf(buf, pos, digits_type::min_value_oct()); break; } return pos; } template C4_NO_INLINE size_t _itoa2buf(substr buf, I radix, size_t num_digits) noexcept { using digits_type = detail::charconv_digits; size_t pos = 0; size_t needed_digits = 0; if C4_LIKELY(buf.len > 0) buf.str[pos++] = '-'; switch(radix) // NOLINT(hicpp-multiway-paths-covered) { case I(10): // add 1 to account for - needed_digits = num_digits+1 > digits_type::maxdigits_dec ? num_digits+1 : digits_type::maxdigits_dec; if C4_UNLIKELY(buf.len < needed_digits) return needed_digits; pos = _itoa2bufwithdigits(buf, pos, num_digits, digits_type::min_value_dec()); break; case I(16): // add 3 to account for -0x needed_digits = num_digits+3 > digits_type::maxdigits_hex ? num_digits+3 : digits_type::maxdigits_hex; if C4_UNLIKELY(buf.len < needed_digits) return needed_digits; buf.str[pos++] = '0'; buf.str[pos++] = 'x'; pos = _itoa2bufwithdigits(buf, pos, num_digits, digits_type::min_value_hex()); break; case I(2): // add 3 to account for -0b needed_digits = num_digits+3 > digits_type::maxdigits_bin ? num_digits+3 : digits_type::maxdigits_bin; if C4_UNLIKELY(buf.len < needed_digits) return needed_digits; C4_ASSERT(buf.len >= digits_type::maxdigits_bin); buf.str[pos++] = '0'; buf.str[pos++] = 'b'; pos = _itoa2bufwithdigits(buf, pos, num_digits, digits_type::min_value_bin()); break; case I(8): // add 3 to account for -0o needed_digits = num_digits+3 > digits_type::maxdigits_oct ? num_digits+3 : digits_type::maxdigits_oct; if C4_UNLIKELY(buf.len < needed_digits) return needed_digits; C4_ASSERT(buf.len >= digits_type::maxdigits_oct); buf.str[pos++] = '0'; buf.str[pos++] = 'o'; pos = _itoa2bufwithdigits(buf, pos, num_digits, digits_type::min_value_oct()); break; } return pos; } } // namespace detail /** @endcond */ /** @defgroup doc_itoa itoa: signed to chars * * @{ */ /** convert an integral signed decimal to a string. * @note the resulting string is NOT zero-terminated. * @note it is ok to call this with an empty or too-small buffer; * no writes will occur, and the needed size will be returned * @return the number of characters required for the buffer. */ template C4_ALWAYS_INLINE size_t itoa(substr buf, T v) noexcept { C4_STATIC_ASSERT(std::is_signed::value); if(v >= T(0)) { // write_dec() checks the buffer size, so no need to check here return write_dec(buf, v); } // when T is the min value (eg i8: -128), negating it // will overflow, so treat the min as a special case if C4_LIKELY(v != std::numeric_limits::min()) { v = (T)-v; unsigned digits = digits_dec(v); if C4_LIKELY(buf.len >= digits + 1u) { buf.str[0] = '-'; write_dec_unchecked(buf.sub(1), v, digits); } return digits + 1u; } return detail::_itoadec2buf(buf); } /** convert an integral signed integer to a string, using a specific * radix. The radix must be 2, 8, 10 or 16. * * @note the resulting string is NOT zero-terminated. * @note it is ok to call this with an empty or too-small buffer; * no writes will occur, and the needed size will be returned * @return the number of characters required for the buffer. */ template C4_ALWAYS_INLINE size_t itoa(substr buf, T v, T radix) noexcept { C4_STATIC_ASSERT(std::is_signed::value); C4_ASSERT(radix == 2 || radix == 8 || radix == 10 || radix == 16); C4_SUPPRESS_WARNING_GCC_PUSH #if (defined(__GNUC__) && (__GNUC__ >= 7)) C4_SUPPRESS_WARNING_GCC("-Wstringop-overflow") // gcc has a false positive here #endif // when T is the min value (eg i8: -128), negating it // will overflow, so treat the min as a special case if C4_LIKELY(v != std::numeric_limits::min()) { unsigned pos = 0; if(v < 0) { v = (T)-v; if C4_LIKELY(buf.len > 0) buf.str[pos] = '-'; ++pos; } unsigned digits = 0; switch(radix) // NOLINT(hicpp-multiway-paths-covered) { case T(10): digits = digits_dec(v); if C4_LIKELY(buf.len >= pos + digits) write_dec_unchecked(buf.sub(pos), v, digits); break; case T(16): digits = digits_hex(v); if C4_LIKELY(buf.len >= pos + 2u + digits) { buf.str[pos + 0] = '0'; buf.str[pos + 1] = 'x'; write_hex_unchecked(buf.sub(pos + 2), v, digits); } digits += 2u; break; case T(2): digits = digits_bin(v); if C4_LIKELY(buf.len >= pos + 2u + digits) { buf.str[pos + 0] = '0'; buf.str[pos + 1] = 'b'; write_bin_unchecked(buf.sub(pos + 2), v, digits); } digits += 2u; break; case T(8): digits = digits_oct(v); if C4_LIKELY(buf.len >= pos + 2u + digits) { buf.str[pos + 0] = '0'; buf.str[pos + 1] = 'o'; write_oct_unchecked(buf.sub(pos + 2), v, digits); } digits += 2u; break; } return pos + digits; } C4_SUPPRESS_WARNING_GCC_POP // when T is the min value (eg i8: -128), negating it // will overflow return detail::_itoa2buf(buf, radix); } /** same as c4::itoa(), but pad with zeroes on the left such that the * resulting string is @p num_digits wide, not accounting for radix * prefix (0x,0o,0b). The @p radix must be 2, 8, 10 or 16. * * @note the resulting string is NOT zero-terminated. * @note it is ok to call this with an empty or too-small buffer; * no writes will occur, and the needed size will be returned * @return the number of characters required for the buffer. */ template C4_ALWAYS_INLINE size_t itoa(substr buf, T v, T radix, size_t num_digits) noexcept { C4_STATIC_ASSERT(std::is_signed::value); C4_ASSERT(radix == 2 || radix == 8 || radix == 10 || radix == 16); C4_SUPPRESS_WARNING_GCC_PUSH #if (defined(__GNUC__) && (__GNUC__ >= 7)) C4_SUPPRESS_WARNING_GCC("-Wstringop-overflow") // gcc has a false positive here #endif // when T is the min value (eg i8: -128), negating it // will overflow, so treat the min as a special case if C4_LIKELY(v != std::numeric_limits::min()) { unsigned pos = 0; if(v < 0) { v = (T)-v; if C4_LIKELY(buf.len > 0) buf.str[pos] = '-'; ++pos; } unsigned total_digits = 0; switch(radix) // NOLINT(hicpp-multiway-paths-covered) { case T(10): total_digits = digits_dec(v); total_digits = pos + (unsigned)(num_digits > total_digits ? num_digits : total_digits); if C4_LIKELY(buf.len >= total_digits) write_dec(buf.sub(pos), v, num_digits); break; case T(16): total_digits = digits_hex(v); total_digits = pos + 2u + (unsigned)(num_digits > total_digits ? num_digits : total_digits); if C4_LIKELY(buf.len >= total_digits) { buf.str[pos + 0] = '0'; buf.str[pos + 1] = 'x'; write_hex(buf.sub(pos + 2), v, num_digits); } break; case T(2): total_digits = digits_bin(v); total_digits = pos + 2u + (unsigned)(num_digits > total_digits ? num_digits : total_digits); if C4_LIKELY(buf.len >= total_digits) { buf.str[pos + 0] = '0'; buf.str[pos + 1] = 'b'; write_bin(buf.sub(pos + 2), v, num_digits); } break; case T(8): total_digits = digits_oct(v); total_digits = pos + 2u + (unsigned)(num_digits > total_digits ? num_digits : total_digits); if C4_LIKELY(buf.len >= total_digits) { buf.str[pos + 0] = '0'; buf.str[pos + 1] = 'o'; write_oct(buf.sub(pos + 2), v, num_digits); } break; } return total_digits; } C4_SUPPRESS_WARNING_GCC_POP // when T is the min value (eg i8: -128), negating it // will overflow return detail::_itoa2buf(buf, radix, num_digits); } /** @} */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @defgroup doc_utoa utoa: unsigned to chars * * @{ */ /** convert an integral unsigned decimal to a string. * * @note the resulting string is NOT zero-terminated. * @note it is ok to call this with an empty or too-small buffer; * no writes will occur, and the needed size will be returned * @return the number of characters required for the buffer. */ template C4_ALWAYS_INLINE size_t utoa(substr buf, T v) noexcept { C4_STATIC_ASSERT(std::is_unsigned::value); // write_dec() does the buffer length check, so no need to check here return write_dec(buf, v); } /** convert an integral unsigned integer to a string, using a specific * radix. The radix must be 2, 8, 10 or 16. * * @note the resulting string is NOT zero-terminated. * @note it is ok to call this with an empty or too-small buffer; * no writes will occur, and the needed size will be returned * @return the number of characters required for the buffer. */ template C4_ALWAYS_INLINE size_t utoa(substr buf, T v, T radix) noexcept { C4_STATIC_ASSERT(std::is_unsigned::value); C4_ASSERT(radix == 10 || radix == 16 || radix == 2 || radix == 8); unsigned digits = 0; switch(radix) // NOLINT(hicpp-multiway-paths-covered) { case T(10): digits = digits_dec(v); if C4_LIKELY(buf.len >= digits) write_dec_unchecked(buf, v, digits); break; case T(16): digits = digits_hex(v); if C4_LIKELY(buf.len >= digits+2u) { buf.str[0] = '0'; buf.str[1] = 'x'; write_hex_unchecked(buf.sub(2), v, digits); } digits += 2u; break; case T(2): digits = digits_bin(v); if C4_LIKELY(buf.len >= digits+2u) { buf.str[0] = '0'; buf.str[1] = 'b'; write_bin_unchecked(buf.sub(2), v, digits); } digits += 2u; break; case T(8): digits = digits_oct(v); if C4_LIKELY(buf.len >= digits+2u) { buf.str[0] = '0'; buf.str[1] = 'o'; write_oct_unchecked(buf.sub(2), v, digits); } digits += 2u; break; } return digits; } /** same as c4::utoa(), but pad with zeroes on the left such that the * resulting string is @p num_digits wide. The @p radix must be 2, * 8, 10 or 16. * * @note the resulting string is NOT zero-terminated. * @note it is ok to call this with an empty or too-small buffer; * no writes will occur, and the needed size will be returned * @return the number of characters required for the buffer. */ template C4_ALWAYS_INLINE size_t utoa(substr buf, T v, T radix, size_t num_digits) noexcept { C4_STATIC_ASSERT(std::is_unsigned::value); C4_ASSERT(radix == 10 || radix == 16 || radix == 2 || radix == 8); unsigned total_digits = 0; switch(radix) // NOLINT(hicpp-multiway-paths-covered) { case T(10): total_digits = digits_dec(v); total_digits = (unsigned)(num_digits > total_digits ? num_digits : total_digits); if C4_LIKELY(buf.len >= total_digits) write_dec(buf, v, num_digits); break; case T(16): total_digits = digits_hex(v); total_digits = 2u + (unsigned)(num_digits > total_digits ? num_digits : total_digits); if C4_LIKELY(buf.len >= total_digits) { buf.str[0] = '0'; buf.str[1] = 'x'; write_hex(buf.sub(2), v, num_digits); } break; case T(2): total_digits = digits_bin(v); total_digits = 2u + (unsigned)(num_digits > total_digits ? num_digits : total_digits); if C4_LIKELY(buf.len >= total_digits) { buf.str[0] = '0'; buf.str[1] = 'b'; write_bin(buf.sub(2), v, num_digits); } break; case T(8): total_digits = digits_oct(v); total_digits = 2u + (unsigned)(num_digits > total_digits ? num_digits : total_digits); if C4_LIKELY(buf.len >= total_digits) { buf.str[0] = '0'; buf.str[1] = 'o'; write_oct(buf.sub(2), v, num_digits); } break; } return total_digits; } C4_SUPPRESS_WARNING_GCC_POP /** @} */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @defgroup doc_atoi atoi: chars to signed * * @{ */ /** Convert a trimmed string to a signed integral value. The input * string can be formatted as decimal, binary (prefix 0b or 0B), octal * (prefix 0o or 0O) or hexadecimal (prefix 0x or 0X). Strings with * leading zeroes are considered as decimal and not octal (unlike the * C/C++ convention). Every character in the input string is read for * the conversion; the input string must not contain any leading or * trailing whitespace. * * @return true if the conversion was successful. * * @note a positive sign is not accepted. ie, the string must not * start with '+' * * @note overflow is not detected: the return status is true even if * the conversion would return a value outside of the type's range, in * which case the result will wrap around the type's range. This is * similar to native behavior. See @ref doc_overflows and @ref * doc_overflow_checked for overflow checking utilities. * * @see atoi_first() if the string is not trimmed to the value to read. */ template C4_NO_UBSAN_IOVRFLW C4_ALWAYS_INLINE bool atoi(csubstr str, T * C4_RESTRICT v) noexcept { C4_STATIC_ASSERT(std::is_integral::value); C4_STATIC_ASSERT(std::is_signed::value); if C4_UNLIKELY(str.len == 0) return false; // no need for the assertion, but we leave it here to document // the expectation: //C4_ASSERT(str.str[0] != '+'); T sign = 1; size_t start = 0; if(str.str[0] == '-') { if C4_UNLIKELY(str.len == ++start) return false; sign = -1; } bool parsed_ok = true; if(str.str[start] != '0') // this should be the common case, so put it first { parsed_ok = read_dec(str.sub(start), v); } else if(str.len > start + 1) { // starts with 0: is it 0x, 0o, 0b? const char pfx = str.str[start + 1]; if(pfx == 'x' || pfx == 'X') parsed_ok = str.len > start + 2 && read_hex(str.sub(start + 2), v); else if(pfx == 'b' || pfx == 'B') parsed_ok = str.len > start + 2 && read_bin(str.sub(start + 2), v); else if(pfx == 'o' || pfx == 'O') parsed_ok = str.len > start + 2 && read_oct(str.sub(start + 2), v); else parsed_ok = read_dec(str.sub(start + 1), v); } else { parsed_ok = read_dec(str.sub(start), v); } if C4_LIKELY(parsed_ok) *v *= sign; return parsed_ok; } /** Select the next range of characters in the string that can be parsed * as a signed integral value, and convert it using atoi(). Leading * whitespace (space, newline, tabs) is skipped. * @return the number of characters read for conversion, or csubstr::npos if the conversion failed * @see atoi() if the string is already trimmed to the value to read. * @see csubstr::first_int_span() */ template C4_ALWAYS_INLINE size_t atoi_first(csubstr str, T * C4_RESTRICT v) { csubstr trimmed = str.first_int_span(); if(trimmed.len && atoi(trimmed, v)) return static_cast(trimmed.end() - str.begin()); return csubstr::npos; } /** @} */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @defgroup doc_atou atou: chars to unsigned * * @{ */ /** Convert a trimmed string to an unsigned integral value. The string can be * formatted as decimal, binary (prefix 0b or 0B), octal (prefix 0o or 0O) * or hexadecimal (prefix 0x or 0X). Every character in the input string is read * for the conversion; it must not contain any leading or trailing whitespace. * * @return true if the conversion was successful. * * @note overflow is not detected: the return status is true even if * the conversion would return a value outside of the type's range, in * which case the result will wrap around the type's range. See @ref * doc_overflows and @ref doc_overflow_checked for overflow checking * utilities. * * @note If the string has a minus character, the return status * will be false. * * @see atou_first() if the string is not trimmed to the value to read. */ template bool atou(csubstr str, T * C4_RESTRICT v) noexcept { C4_STATIC_ASSERT(std::is_integral::value); if C4_UNLIKELY(str.len == 0 || str.front() == '-') return false; bool parsed_ok = true; if(str.str[0] != '0') { parsed_ok = read_dec(str, v); } else { if(str.len > 1) { const char pfx = str.str[1]; if(pfx == 'x' || pfx == 'X') parsed_ok = str.len > 2 && read_hex(str.sub(2), v); else if(pfx == 'b' || pfx == 'B') parsed_ok = str.len > 2 && read_bin(str.sub(2), v); else if(pfx == 'o' || pfx == 'O') parsed_ok = str.len > 2 && read_oct(str.sub(2), v); else parsed_ok = read_dec(str, v); } else { *v = 0; // we know the first character is 0 } } return parsed_ok; } /** Select the next range of characters in the string that can be parsed * as an unsigned integral value, and convert it using atou(). Leading * whitespace (space, newline, tabs) is skipped. * @return the number of characters read for conversion, or csubstr::npos if the conversion faileds * @see atou() if the string is already trimmed to the value to read. * @see csubstr::first_uint_span() */ template C4_ALWAYS_INLINE size_t atou_first(csubstr str, T *v) { csubstr trimmed = str.first_uint_span(); if(trimmed.len && atou(trimmed, v)) return static_cast(trimmed.end() - str.begin()); return csubstr::npos; } /** @} */ #if defined(_MSC_VER) && !defined(__clang__) # pragma warning(pop) #elif defined(__clang__) # pragma clang diagnostic pop #elif defined(__GNUC__) # pragma GCC diagnostic pop #endif //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @cond dev */ namespace detail { inline bool check_overflow(csubstr str, csubstr limit) noexcept { if(str.len != limit.len) return str.len > limit.len; for(size_t i = 0; i < limit.len; ++i) { if(str.str[i] < limit.str[i]) return false; else if(str.str[i] > limit.str[i]) return true; } return false; } } // namespace detail /** @endcond */ /** @defgroup doc_overflows overflows: does a number string overflow a type * * @{ */ /** Test if the following string would overflow when converted to * associated integral types; this function is dispatched with SFINAE * to handle differently signed and unsigned types. * @return true if number will overflow, false if it fits (or doesn't parse) * @see doc_overflow_checked for format specifiers to enforce no-overflow reads */ template auto overflows(csubstr str) noexcept -> typename std::enable_if::value, bool>::type { C4_STATIC_ASSERT(std::is_integral::value); if C4_UNLIKELY(str.len == 0) { return false; } else if(str.str[0] == '0') { if (str.len == 1) return false; switch (str.str[1]) { case 'x': case 'X': { size_t fno = str.first_not_of('0', 2); if (fno == csubstr::npos) return false; return !(str.len <= fno + (sizeof(T) * 2)); } case 'b': case 'B': { size_t fno = str.first_not_of('0', 2); if (fno == csubstr::npos) return false; return !(str.len <= fno +(sizeof(T) * 8)); } case 'o': case 'O': { size_t fno = str.first_not_of('0', 2); if(fno == csubstr::npos) return false; return detail::charconv_digits::is_oct_overflow(str.sub(fno)); } default: { size_t fno = str.first_not_of('0', 1); if(fno == csubstr::npos) return false; return detail::check_overflow(str.sub(fno), detail::charconv_digits::max_value_dec()); } } } else if C4_UNLIKELY(str.str[0] == '-') { return true; } else { return detail::check_overflow(str, detail::charconv_digits::max_value_dec()); } } /** Test if the following string would overflow when converted to * associated integral types; this function is dispatched with SFINAE * to handle differently signed and unsigned types. * * @return true if number will overflow, false if it fits (or doesn't parse) * @see doc_overflow_checked for format specifiers to enforce no-overflow reads */ template auto overflows(csubstr str) noexcept -> typename std::enable_if::value, bool>::type { C4_STATIC_ASSERT(std::is_integral::value); if C4_UNLIKELY(str.len == 0) return false; if(str.str[0] == '-') { if(str.str[1] == '0') { if(str.len == 2) return false; switch(str.str[2]) { case 'x': case 'X': { size_t fno = str.first_not_of('0', 3); if (fno == csubstr::npos) return false; return detail::check_overflow(str.sub(fno), detail::charconv_digits::min_value_hex()); } case 'b': case 'B': { size_t fno = str.first_not_of('0', 3); if (fno == csubstr::npos) return false; return detail::check_overflow(str.sub(fno), detail::charconv_digits::min_value_bin()); } case 'o': case 'O': { size_t fno = str.first_not_of('0', 3); if(fno == csubstr::npos) return false; return detail::check_overflow(str.sub(fno), detail::charconv_digits::min_value_oct()); } default: { size_t fno = str.first_not_of('0', 2); if(fno == csubstr::npos) return false; return detail::check_overflow(str.sub(fno), detail::charconv_digits::min_value_dec()); } } } else { return detail::check_overflow(str.sub(1), detail::charconv_digits::min_value_dec()); } } else if(str.str[0] == '0') { if (str.len == 1) return false; switch(str.str[1]) { case 'x': case 'X': { size_t fno = str.first_not_of('0', 2); if (fno == csubstr::npos) return false; const size_t len = str.len - fno; return !((len < sizeof (T) * 2) || (len == sizeof(T) * 2 && str.str[fno] <= '7')); } case 'b': case 'B': { size_t fno = str.first_not_of('0', 2); if (fno == csubstr::npos) return false; return !(str.len <= fno + (sizeof(T) * 8 - 1)); } case 'o': case 'O': { size_t fno = str.first_not_of('0', 2); if(fno == csubstr::npos) return false; return detail::charconv_digits::is_oct_overflow(str.sub(fno)); } default: { size_t fno = str.first_not_of('0', 1); if(fno == csubstr::npos) return false; return detail::check_overflow(str.sub(fno), detail::charconv_digits::max_value_dec()); } } } else { return detail::check_overflow(str, detail::charconv_digits::max_value_dec()); } } /** @} */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @cond dev */ namespace detail { #if (!C4CORE_HAVE_STD_FROMCHARS) /** @see http://www.exploringbinary.com/ for many good examples on float-str conversion */ template void get_real_format_str(char (& C4_RESTRICT fmt)[N], int precision, RealFormat_e formatting, const char* length_modifier="") { int iret; if(precision == -1) iret = snprintf(fmt, sizeof(fmt), "%%%s%c", length_modifier, formatting); else if(precision == 0) iret = snprintf(fmt, sizeof(fmt), "%%.%s%c", length_modifier, formatting); else iret = snprintf(fmt, sizeof(fmt), "%%.%d%s%c", precision, length_modifier, formatting); C4_ASSERT(iret >= 2 && size_t(iret) < sizeof(fmt)); C4_UNUSED(iret); } /** @todo we're depending on snprintf()/sscanf() for converting to/from * floating point numbers. Apparently, this increases the binary size * by a considerable amount. There are some lightweight printf * implementations: * * @see http://www.sparetimelabs.com/tinyprintf/tinyprintf.php (BSD) * @see https://github.com/weiss/c99-snprintf * @see https://github.com/nothings/stb/blob/master/stb_sprintf.h * @see http://www.exploringbinary.com/ * @see https://blog.benoitblanchon.fr/lightweight-float-to-string/ * @see http://www.ryanjuckett.com/programming/printing-floating-point-numbers/ */ template size_t print_one(substr str, const char* full_fmt, T v) { #ifdef _MSC_VER /** use _snprintf() to prevent early termination of the output * for writing the null character at the last position * @see https://msdn.microsoft.com/en-us/library/2ts7cx93.aspx */ int iret = _snprintf(str.str, str.len, full_fmt, v); if(iret < 0) { /* when buf.len is not enough, VS returns a negative value. * so call it again with a negative value for getting an * actual length of the string */ iret = snprintf(nullptr, 0, full_fmt, v); C4_ASSERT(iret > 0); } size_t ret = (size_t) iret; return ret; #else int iret = snprintf(str.str, str.len, full_fmt, v); C4_ASSERT(iret >= 0); size_t ret = (size_t) iret; if(ret >= str.len) ++ret; /* snprintf() reserves the last character to write \0 */ return ret; #endif } #endif // (!C4CORE_HAVE_STD_FROMCHARS) #if (!C4CORE_HAVE_STD_FROMCHARS) && (!C4CORE_HAVE_FAST_FLOAT) /** scans a string using the given type format, while at the same time * allowing non-null-terminated strings AND guaranteeing that the given * string length is strictly respected, so that no buffer overflows * might occur. */ template inline size_t scan_one(csubstr str, const char *type_fmt, T *v) { /* snscanf() is absolutely needed here as we must be sure that * str.len is strictly respected, because substr is * generally not null-terminated. * * Alas, there is no snscanf(). * * So we fake it by using a dynamic format with an explicit * field size set to the length of the given span. * This trick is taken from: * https://stackoverflow.com/a/18368910/5875572 */ /* this is the actual format we'll use for scanning */ char fmt[16]; /* write the length into it. Eg "%12f". * Also, get the number of characters read from the string. * So the final format ends up as "%12f%n"*/ int iret = std::snprintf(fmt, sizeof(fmt), "%%" "%zu" "%s" "%%n", str.len, type_fmt); /* no nasty surprises, please! */ C4_ASSERT(iret >= 0 && size_t(iret) < C4_COUNTOF(fmt)); /* now we scan with confidence that the span length is respected */ int num_chars; iret = std::sscanf(str.str, fmt, v, &num_chars); /* scanf returns the number of successful conversions */ if(iret != 1) return csubstr::npos; C4_ASSERT(num_chars >= 0); return (size_t)(num_chars); } #endif // (!C4CORE_HAVE_STD_FROMCHARS) && (!C4CORE_HAVE_FAST_FLOAT) #if C4CORE_HAVE_STD_TOCHARS template C4_ALWAYS_INLINE size_t rtoa(substr buf, T v, int precision=-1, RealFormat_e formatting=FTOA_FLEX) noexcept { std::to_chars_result result; size_t pos = 0; if(formatting == FTOA_HEXA) { if(buf.len > size_t(2)) { buf.str[0] = '0'; buf.str[1] = 'x'; } pos += size_t(2); } if(precision == -1) result = std::to_chars(buf.str + pos, buf.str + buf.len, v, (std::chars_format)formatting); else result = std::to_chars(buf.str + pos, buf.str + buf.len, v, (std::chars_format)formatting, precision); if(result.ec == std::errc()) { // all good, no errors. C4_ASSERT(result.ptr >= buf.str); ptrdiff_t delta = result.ptr - buf.str; return static_cast(delta); } C4_ASSERT(result.ec == std::errc::value_too_large); // This is unfortunate. // // When the result can't fit in the given buffer, // std::to_chars() returns the end pointer it was originally // given, which is useless because here we would like to know // _exactly_ how many characters the buffer must have to fit // the result. // // So we take the pessimistic view, and assume as many digits // as could ever be required: size_t ret = static_cast(std::numeric_limits::max_digits10); return ret > buf.len ? ret : buf.len + 1; } #endif // C4CORE_HAVE_STD_TOCHARS #if C4CORE_HAVE_FAST_FLOAT template C4_ALWAYS_INLINE bool scan_rhex(csubstr s, T *C4_RESTRICT val) noexcept { // no need for these asserts, but we leave them here to show // the expectation: //C4_ASSERT(s.len > 0); //C4_ASSERT(s.str[0] != '-'); //C4_ASSERT(s.str[0] != '+'); //C4_ASSERT(!s.begins_with("0x")); //C4_ASSERT(!s.begins_with("0X")); size_t pos = 0; // integer part for( ; pos < s.len; ++pos) { const char c = s.str[pos]; if(c >= '0' && c <= '9') *val = (*val * T(16)) + T(c - '0'); else if(c >= 'a' && c <= 'f') *val = (*val * T(16)) + T(c - 'a'); else if(c >= 'A' && c <= 'F') *val = (*val * T(16)) + T(c - 'A'); else if(c == '.') { ++pos; break; // follow on to mantissa } else if(c == 'p' || c == 'P') { ++pos; goto power; // no mantissa given, jump to power // NOLINT } else { return false; } } // mantissa { // 0.0625 == 1/16 == value of first digit after the comma for(T digit = T(0.0625); pos < s.len; ++pos, digit /= T(16)) // NOLINT { const char c = s.str[pos]; if(c >= '0' && c <= '9') *val += digit * T(c - '0'); else if(c >= 'a' && c <= 'f') *val += digit * T(c - 'a'); else if(c >= 'A' && c <= 'F') *val += digit * T(c - 'A'); else if(c == 'p' || c == 'P') { ++pos; goto power; // mantissa finished, jump to power // NOLINT } else { return false; } } } return true; power: if C4_LIKELY(pos < s.len) { if(s.str[pos] == '+') // atoi() cannot handle a leading '+' ++pos; if C4_LIKELY(pos < s.len) { int16_t powval = {}; if C4_LIKELY(atoi(s.sub(pos), &powval)) { *val *= ipow(powval); return true; } } } return false; } #endif } // namespace detail /** @endcond */ #undef _c4append /** @defgroup doc_ftoa ftoa: float32 to chars * * @{ */ /** Convert a single-precision real number to string. The string will * in general be NOT null-terminated. For FTOA_FLEX, \p precision is * the number of significand digits. Otherwise \p precision is the * number of decimals. It is safe to call this function with an empty * or too-small buffer. * * @return the size of the buffer needed to write the number */ C4_ALWAYS_INLINE size_t ftoa(substr str, float v, int precision=-1, RealFormat_e formatting=FTOA_FLEX) noexcept { #if C4CORE_HAVE_STD_TOCHARS return detail::rtoa(str, v, precision, formatting); #else char fmt[16]; detail::get_real_format_str(fmt, precision, formatting, /*length_modifier*/""); return detail::print_one(str, fmt, v); #endif } /** @} */ /** @defgroup doc_dtoa dtoa: float64 to chars * * @{ */ /** Convert a double-precision real number to string. The string will * in general be NOT null-terminated. For FTOA_FLEX, \p precision is * the number of significand digits. Otherwise \p precision is the * number of decimals. It is safe to call this function with an empty * or too-small buffer. * * @return the size of the buffer needed to write the number */ C4_ALWAYS_INLINE size_t dtoa(substr str, double v, int precision=-1, RealFormat_e formatting=FTOA_FLEX) noexcept { #if C4CORE_HAVE_STD_TOCHARS return detail::rtoa(str, v, precision, formatting); #else char fmt[16]; detail::get_real_format_str(fmt, precision, formatting, /*length_modifier*/"l"); return detail::print_one(str, fmt, v); #endif } /** @} */ /** @defgroup doc_atof atof: chars to float32 * * @{ */ /** Convert a string to a single precision real number. * The input string must be trimmed to the value, ie * no leading or trailing whitespace can be present. * @return true iff the conversion succeeded * @see atof_first() if the string is not trimmed */ C4_ALWAYS_INLINE bool atof(csubstr str, float * C4_RESTRICT v) noexcept { C4_ASSERT(str.len > 0); C4_ASSERT(str.triml(" \r\t\n").len == str.len); #if C4CORE_HAVE_FAST_FLOAT // fastfloat cannot parse hexadecimal floats bool isneg = (str.str[0] == '-'); csubstr rem = str.sub(isneg || str.str[0] == '+'); if( ! (rem.len >= 2 && (rem.str[0] == '0' && (rem.str[1] == 'x' || rem.str[1] == 'X')))) { fast_float::from_chars_result result; result = fast_float::from_chars(str.str, str.str + str.len, *v); return result.ec == std::errc(); } else if(detail::scan_rhex(rem.sub(2), v)) { *v *= isneg ? -1.f : 1.f; return true; } return false; #elif C4CORE_HAVE_STD_FROMCHARS std::from_chars_result result; result = std::from_chars(str.str, str.str + str.len, *v); return result.ec == std::errc(); #else csubstr rem = str.sub(str.str[0] == '-' || str.str[0] == '+'); if(!(rem.len >= 2 && (rem.str[0] == '0' && (rem.str[1] == 'x' || rem.str[1] == 'X')))) return detail::scan_one(str, "f", v) != csubstr::npos; else return detail::scan_one(str, "a", v) != csubstr::npos; #endif } /** Convert a string to a single precision real number. * Leading whitespace is skipped until valid characters are found. * @return the number of characters read from the string, or npos if * conversion was not successful or if the string was empty */ inline size_t atof_first(csubstr str, float * C4_RESTRICT v) noexcept { csubstr trimmed = str.first_real_span(); if(trimmed.len == 0) return csubstr::npos; if(atof(trimmed, v)) return static_cast(trimmed.end() - str.begin()); return csubstr::npos; } /** @} */ /** @defgroup doc_atod atod: chars to float64 * * @{ */ /** Convert a string to a double precision real number. * The input string must be trimmed to the value, ie * no leading or trailing whitespace can be present. * @return true iff the conversion succeeded * @see atod_first() if the string is not trimmed */ C4_ALWAYS_INLINE bool atod(csubstr str, double * C4_RESTRICT v) noexcept { C4_ASSERT(str.len > 0); C4_ASSERT(str.triml(" \r\t\n").len == str.len); #if C4CORE_HAVE_FAST_FLOAT // fastfloat cannot parse hexadecimal floats bool isneg = (str.str[0] == '-'); csubstr rem = str.sub(isneg || str.str[0] == '+'); if( ! (rem.len >= 2 && (rem.str[0] == '0' && (rem.str[1] == 'x' || rem.str[1] == 'X')))) { fast_float::from_chars_result result; #ifndef CLANG_TIDY // suppress a false-positive error (cannot be done with NOLINT: https://stackoverflow.com/questions/62838193/ ) result = fast_float::from_chars(str.str, str.str + str.len, *v); #else result = {}; #endif return result.ec == std::errc(); } else if(detail::scan_rhex(rem.sub(2), v)) { *v *= isneg ? -1. : 1.; return true; } return false; #elif C4CORE_HAVE_STD_FROMCHARS std::from_chars_result result; result = std::from_chars(str.str, str.str + str.len, *v); return result.ec == std::errc(); #else csubstr rem = str.sub(str.str[0] == '-' || str.str[0] == '+'); if(!(rem.len >= 2 && (rem.str[0] == '0' && (rem.str[1] == 'x' || rem.str[1] == 'X')))) return detail::scan_one(str, "lf", v) != csubstr::npos; else return detail::scan_one(str, "la", v) != csubstr::npos; #endif } /** Convert a string to a double precision real number. * Leading whitespace is skipped until valid characters are found. * @return the number of characters read from the string, or npos if * conversion was not successful or if the string was empty */ inline size_t atod_first(csubstr str, double * C4_RESTRICT v) noexcept { csubstr trimmed = str.first_real_span(); if(trimmed.len == 0) return csubstr::npos; if(atod(trimmed, v)) return static_cast(trimmed.end() - str.begin()); return csubstr::npos; } /** @} */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // generic versions /** @cond dev */ // on some platforms, (unsigned) int and (unsigned) long // are not any of the fixed length types above #define C4_IF_NOT_FIXED_LENGTH_I_(T, ty) typename std::enable_if::value && !is_fixed_length::value_i, ty> #define C4_IF_NOT_FIXED_LENGTH_U_(T, ty) typename std::enable_if::value && !is_fixed_length::value_u, ty> /** @endcond*/ /** @defgroup doc_xtoa xtoa: generic value to chars * * Dispatches to the most appropriate and efficient conversion * function * * @{ */ C4_ALWAYS_INLINE size_t xtoa(substr s, uint8_t v) noexcept { return write_dec(s, v); } C4_ALWAYS_INLINE size_t xtoa(substr s, uint16_t v) noexcept { return write_dec(s, v); } C4_ALWAYS_INLINE size_t xtoa(substr s, uint32_t v) noexcept { return write_dec(s, v); } C4_ALWAYS_INLINE size_t xtoa(substr s, uint64_t v) noexcept { return write_dec(s, v); } C4_ALWAYS_INLINE size_t xtoa(substr s, int8_t v) noexcept { return itoa(s, v); } C4_ALWAYS_INLINE size_t xtoa(substr s, int16_t v) noexcept { return itoa(s, v); } C4_ALWAYS_INLINE size_t xtoa(substr s, int32_t v) noexcept { return itoa(s, v); } C4_ALWAYS_INLINE size_t xtoa(substr s, int64_t v) noexcept { return itoa(s, v); } C4_ALWAYS_INLINE size_t xtoa(substr s, float v) noexcept { return ftoa(s, v); } C4_ALWAYS_INLINE size_t xtoa(substr s, double v) noexcept { return dtoa(s, v); } C4_ALWAYS_INLINE size_t xtoa(substr s, uint8_t v, uint8_t radix) noexcept { return utoa(s, v, radix); } C4_ALWAYS_INLINE size_t xtoa(substr s, uint16_t v, uint16_t radix) noexcept { return utoa(s, v, radix); } C4_ALWAYS_INLINE size_t xtoa(substr s, uint32_t v, uint32_t radix) noexcept { return utoa(s, v, radix); } C4_ALWAYS_INLINE size_t xtoa(substr s, uint64_t v, uint64_t radix) noexcept { return utoa(s, v, radix); } C4_ALWAYS_INLINE size_t xtoa(substr s, int8_t v, int8_t radix) noexcept { return itoa(s, v, radix); } C4_ALWAYS_INLINE size_t xtoa(substr s, int16_t v, int16_t radix) noexcept { return itoa(s, v, radix); } C4_ALWAYS_INLINE size_t xtoa(substr s, int32_t v, int32_t radix) noexcept { return itoa(s, v, radix); } C4_ALWAYS_INLINE size_t xtoa(substr s, int64_t v, int64_t radix) noexcept { return itoa(s, v, radix); } C4_ALWAYS_INLINE size_t xtoa(substr s, uint8_t v, uint8_t radix, size_t num_digits) noexcept { return utoa(s, v, radix, num_digits); } C4_ALWAYS_INLINE size_t xtoa(substr s, uint16_t v, uint16_t radix, size_t num_digits) noexcept { return utoa(s, v, radix, num_digits); } C4_ALWAYS_INLINE size_t xtoa(substr s, uint32_t v, uint32_t radix, size_t num_digits) noexcept { return utoa(s, v, radix, num_digits); } C4_ALWAYS_INLINE size_t xtoa(substr s, uint64_t v, uint64_t radix, size_t num_digits) noexcept { return utoa(s, v, radix, num_digits); } C4_ALWAYS_INLINE size_t xtoa(substr s, int8_t v, int8_t radix, size_t num_digits) noexcept { return itoa(s, v, radix, num_digits); } C4_ALWAYS_INLINE size_t xtoa(substr s, int16_t v, int16_t radix, size_t num_digits) noexcept { return itoa(s, v, radix, num_digits); } C4_ALWAYS_INLINE size_t xtoa(substr s, int32_t v, int32_t radix, size_t num_digits) noexcept { return itoa(s, v, radix, num_digits); } C4_ALWAYS_INLINE size_t xtoa(substr s, int64_t v, int64_t radix, size_t num_digits) noexcept { return itoa(s, v, radix, num_digits); } C4_ALWAYS_INLINE size_t xtoa(substr s, float v, int precision, RealFormat_e formatting=FTOA_FLEX) noexcept { return ftoa(s, v, precision, formatting); } C4_ALWAYS_INLINE size_t xtoa(substr s, double v, int precision, RealFormat_e formatting=FTOA_FLEX) noexcept { return dtoa(s, v, precision, formatting); } template C4_ALWAYS_INLINE auto xtoa(substr buf, T v) noexcept -> C4_IF_NOT_FIXED_LENGTH_I_(T, size_t)::type { return itoa(buf, v); } template C4_ALWAYS_INLINE auto xtoa(substr buf, T v) noexcept -> C4_IF_NOT_FIXED_LENGTH_U_(T, size_t)::type { return write_dec(buf, v); } template C4_ALWAYS_INLINE size_t xtoa(substr s, T *v) noexcept { return itoa(s, (intptr_t)v, (intptr_t)16); } /** @} */ /** @defgroup doc_atox atox: generic chars to value * * Dispatches to the most appropriate and efficient conversion * function * * @{ */ C4_ALWAYS_INLINE bool atox(csubstr s, uint8_t *C4_RESTRICT v) noexcept { return atou(s, v); } C4_ALWAYS_INLINE bool atox(csubstr s, uint16_t *C4_RESTRICT v) noexcept { return atou(s, v); } C4_ALWAYS_INLINE bool atox(csubstr s, uint32_t *C4_RESTRICT v) noexcept { return atou(s, v); } C4_ALWAYS_INLINE bool atox(csubstr s, uint64_t *C4_RESTRICT v) noexcept { return atou(s, v); } C4_ALWAYS_INLINE bool atox(csubstr s, int8_t *C4_RESTRICT v) noexcept { return atoi(s, v); } C4_ALWAYS_INLINE bool atox(csubstr s, int16_t *C4_RESTRICT v) noexcept { return atoi(s, v); } C4_ALWAYS_INLINE bool atox(csubstr s, int32_t *C4_RESTRICT v) noexcept { return atoi(s, v); } C4_ALWAYS_INLINE bool atox(csubstr s, int64_t *C4_RESTRICT v) noexcept { return atoi(s, v); } C4_ALWAYS_INLINE bool atox(csubstr s, float *C4_RESTRICT v) noexcept { return atof(s, v); } C4_ALWAYS_INLINE bool atox(csubstr s, double *C4_RESTRICT v) noexcept { return atod(s, v); } template C4_ALWAYS_INLINE auto atox(csubstr buf, T *C4_RESTRICT v) noexcept -> C4_IF_NOT_FIXED_LENGTH_I_(T, bool)::type { return atoi(buf, v); } template C4_ALWAYS_INLINE auto atox(csubstr buf, T *C4_RESTRICT v) noexcept -> C4_IF_NOT_FIXED_LENGTH_U_(T, bool)::type { return atou(buf, v); } template C4_ALWAYS_INLINE bool atox(csubstr s, T **v) noexcept { intptr_t tmp; bool ret = atox(s, &tmp); if(ret) { *v = (T*)tmp; } return ret; } /** @} */ /** @defgroup doc_to_chars to_chars: generalized chars to value * * Convert the given value, writing into the string. The resulting * string will NOT be null-terminated. Return the number of * characters needed. This function is safe to call when the string * is too small - no writes will occur beyond the string's last * character. * * Dispatches to the most appropriate and efficient conversion * function. * * @see write_dec, doc_utoa, doc_itoa, doc_ftoa, doc_dtoa * * @warning When serializing floating point values (float or double), * be aware that because it uses defaults, to_chars() may cause a * truncation of the precision. To enforce a particular precision, use * for example @ref c4::fmt::real, or call directly @ref c4::ftoa or * @ref c4::dtoa. * * @{ */ C4_ALWAYS_INLINE size_t to_chars(substr buf, uint8_t v) noexcept { return write_dec(buf, v); } C4_ALWAYS_INLINE size_t to_chars(substr buf, uint16_t v) noexcept { return write_dec(buf, v); } C4_ALWAYS_INLINE size_t to_chars(substr buf, uint32_t v) noexcept { return write_dec(buf, v); } C4_ALWAYS_INLINE size_t to_chars(substr buf, uint64_t v) noexcept { return write_dec(buf, v); } C4_ALWAYS_INLINE size_t to_chars(substr buf, int8_t v) noexcept { return itoa(buf, v); } C4_ALWAYS_INLINE size_t to_chars(substr buf, int16_t v) noexcept { return itoa(buf, v); } C4_ALWAYS_INLINE size_t to_chars(substr buf, int32_t v) noexcept { return itoa(buf, v); } C4_ALWAYS_INLINE size_t to_chars(substr buf, int64_t v) noexcept { return itoa(buf, v); } C4_ALWAYS_INLINE size_t to_chars(substr buf, float v) noexcept { return ftoa(buf, v); } C4_ALWAYS_INLINE size_t to_chars(substr buf, double v) noexcept { return dtoa(buf, v); } template C4_ALWAYS_INLINE auto to_chars(substr buf, T v) noexcept -> C4_IF_NOT_FIXED_LENGTH_I_(T, size_t)::type { return itoa(buf, v); } template C4_ALWAYS_INLINE auto to_chars(substr buf, T v) noexcept -> C4_IF_NOT_FIXED_LENGTH_U_(T, size_t)::type { return write_dec(buf, v); } template C4_ALWAYS_INLINE auto to_chars(substr s, T *v) noexcept -> typename std::enable_if::value && !std::is_same::value, size_t>::type { return itoa(s, (intptr_t)v, (intptr_t)16); } /** @} */ /** @defgroup doc_from_chars from_chars: generalized chars to value * * Read a value from the string, which must be trimmed to the value * (ie, no leading/trailing whitespace). return true if the * conversion succeeded. There is no check for overflow; the value * wraps around in a way similar to the standard C/C++ overflow * behavior. For example, from_chars("128", &val) returns true * and val will be set tot 0. See @ref doc_overflows and @ref * doc_overflow_checked for facilities enforcing no-overflow. * * Dispatches to the most appropriate and efficient conversion * function * * @see doc_from_chars_first, atou, atoi, atof, atod * @{ */ C4_ALWAYS_INLINE bool from_chars(csubstr buf, uint8_t *C4_RESTRICT v) noexcept { return atou(buf, v); } C4_ALWAYS_INLINE bool from_chars(csubstr buf, uint16_t *C4_RESTRICT v) noexcept { return atou(buf, v); } C4_ALWAYS_INLINE bool from_chars(csubstr buf, uint32_t *C4_RESTRICT v) noexcept { return atou(buf, v); } C4_ALWAYS_INLINE bool from_chars(csubstr buf, uint64_t *C4_RESTRICT v) noexcept { return atou(buf, v); } C4_ALWAYS_INLINE bool from_chars(csubstr buf, int8_t *C4_RESTRICT v) noexcept { return atoi(buf, v); } C4_ALWAYS_INLINE bool from_chars(csubstr buf, int16_t *C4_RESTRICT v) noexcept { return atoi(buf, v); } C4_ALWAYS_INLINE bool from_chars(csubstr buf, int32_t *C4_RESTRICT v) noexcept { return atoi(buf, v); } C4_ALWAYS_INLINE bool from_chars(csubstr buf, int64_t *C4_RESTRICT v) noexcept { return atoi(buf, v); } C4_ALWAYS_INLINE bool from_chars(csubstr buf, float *C4_RESTRICT v) noexcept { return atof(buf, v); } C4_ALWAYS_INLINE bool from_chars(csubstr buf, double *C4_RESTRICT v) noexcept { return atod(buf, v); } template C4_ALWAYS_INLINE auto from_chars(csubstr buf, T *C4_RESTRICT v) noexcept -> C4_IF_NOT_FIXED_LENGTH_I_(T, bool)::type { return atoi(buf, v); } template C4_ALWAYS_INLINE auto from_chars(csubstr buf, T *C4_RESTRICT v) noexcept -> C4_IF_NOT_FIXED_LENGTH_U_(T, bool)::type { return atou(buf, v); } template C4_ALWAYS_INLINE bool from_chars(csubstr buf, T **v) noexcept { intptr_t tmp; bool ret = from_chars(buf, &tmp); if(ret) { *v = (T*)tmp; } return ret; } /** @defgroup doc_from_chars_first from_chars_first: generalized chars to value * * Read the first valid sequence of characters from the string, * skipping leading whitespace, and convert it using @ref doc_from_chars . * Return the number of characters read for converting. * * Dispatches to the most appropriate and efficient conversion * function. * * @see atou_first, atoi_first, atof_first, atod_first * @{ */ C4_ALWAYS_INLINE size_t from_chars_first(csubstr buf, uint8_t *C4_RESTRICT v) noexcept { return atou_first(buf, v); } C4_ALWAYS_INLINE size_t from_chars_first(csubstr buf, uint16_t *C4_RESTRICT v) noexcept { return atou_first(buf, v); } C4_ALWAYS_INLINE size_t from_chars_first(csubstr buf, uint32_t *C4_RESTRICT v) noexcept { return atou_first(buf, v); } C4_ALWAYS_INLINE size_t from_chars_first(csubstr buf, uint64_t *C4_RESTRICT v) noexcept { return atou_first(buf, v); } C4_ALWAYS_INLINE size_t from_chars_first(csubstr buf, int8_t *C4_RESTRICT v) noexcept { return atoi_first(buf, v); } C4_ALWAYS_INLINE size_t from_chars_first(csubstr buf, int16_t *C4_RESTRICT v) noexcept { return atoi_first(buf, v); } C4_ALWAYS_INLINE size_t from_chars_first(csubstr buf, int32_t *C4_RESTRICT v) noexcept { return atoi_first(buf, v); } C4_ALWAYS_INLINE size_t from_chars_first(csubstr buf, int64_t *C4_RESTRICT v) noexcept { return atoi_first(buf, v); } C4_ALWAYS_INLINE size_t from_chars_first(csubstr buf, float *C4_RESTRICT v) noexcept { return atof_first(buf, v); } C4_ALWAYS_INLINE size_t from_chars_first(csubstr buf, double *C4_RESTRICT v) noexcept { return atod_first(buf, v); } template C4_ALWAYS_INLINE auto from_chars_first(csubstr buf, T *C4_RESTRICT v) noexcept -> C4_IF_NOT_FIXED_LENGTH_I_(T, size_t)::type { return atoi_first(buf, v); } template C4_ALWAYS_INLINE auto from_chars_first(csubstr buf, T *C4_RESTRICT v) noexcept -> C4_IF_NOT_FIXED_LENGTH_U_(T, size_t)::type { return atou_first(buf, v); } template C4_ALWAYS_INLINE size_t from_chars_first(csubstr buf, T **v) noexcept { intptr_t tmp; bool ret = from_chars_first(buf, &tmp); if(ret) { *v = (T*)tmp; } return ret; } /** @} */ /** @} */ #undef C4_IF_NOT_FIXED_LENGTH_I_ #undef C4_IF_NOT_FIXED_LENGTH_U_ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** call to_chars() and return a substr consisting of the * written portion of the input buffer. Ie, same as to_chars(), * but return a substr instead of a size_t. * Convert the given value to a string using to_chars(), and * return the resulting string, up to and including the last * written character. * @ingroup doc_to_chars * @see to_chars() */ template C4_ALWAYS_INLINE substr to_chars_sub(substr buf, T const& C4_RESTRICT v) noexcept { size_t sz = to_chars(buf, v); return buf.left_of(sz <= buf.len ? sz : buf.len); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // bool implementation /** @ingroup doc_to_chars */ C4_ALWAYS_INLINE size_t to_chars(substr buf, bool v) noexcept { int val = v; return to_chars(buf, val); } /** @ingroup doc_from_chars */ inline bool from_chars(csubstr buf, bool * C4_RESTRICT v) noexcept { if(buf.len == 1) { if(buf.str[0] == '0') { *v = false; return true; } else if(buf.str[0] == '1') { *v = true; return true; } } else if(buf.len == 4) { if(((buf.str[0] == 't') && (0 == memcmp(buf.str + 1, "rue", 3))) || ((buf.str[0] == 'T') && (0 == memcmp(buf.str + 1, "rue", 3) || 0 == memcmp(buf.str + 1, "RUE", 3)))) { *v = true; return true; } } else if(buf.len == 5) { if(((buf.str[0] == 'f') && (0 == memcmp(buf.str + 1, "alse", 4))) || ((buf.str[0] == 'F') && (0 == memcmp(buf.str + 1, "alse", 4) || 0 == memcmp(buf.str + 1, "ALSE", 4)))) { *v = false; return true; } } // fallback to c-style int bools int val = 0; bool ret = from_chars(buf, &val); if C4_LIKELY(ret) { *v = (val != 0); } return ret; } /** @ingroup doc_from_chars_first */ inline size_t from_chars_first(csubstr buf, bool * C4_RESTRICT v) noexcept { csubstr trimmed = buf.first_non_empty_span(); if(trimmed.len == 0 || !from_chars(buf, v)) return csubstr::npos; return trimmed.len; } //----------------------------------------------------------------------------- // single-char implementation /** @ingroup doc_to_chars */ inline size_t to_chars(substr buf, char v) noexcept { if(buf.len > 0) { C4_XASSERT(buf.str); buf.str[0] = v; } return 1; } /** extract a single character from a substring * @note to extract a string instead and not just a single character, use the csubstr overload * @ingroup doc_from_chars * */ inline bool from_chars(csubstr buf, char * C4_RESTRICT v) noexcept { if(buf.len != 1) return false; C4_XASSERT(buf.str); *v = buf.str[0]; return true; } /** @ingroup doc_from_chars_first */ inline size_t from_chars_first(csubstr buf, char * C4_RESTRICT v) noexcept { if(buf.len < 1) return csubstr::npos; *v = buf.str[0]; return 1; } //----------------------------------------------------------------------------- // csubstr implementation /** @ingroup doc_to_chars */ inline size_t to_chars(substr buf, csubstr v) noexcept { C4_ASSERT(!buf.overlaps(v)); size_t len = buf.len < v.len ? buf.len : v.len; // calling memcpy with null strings is undefined behavior // and will wreak havoc in calling code's branches. // see https://github.com/biojppm/rapidyaml/pull/264#issuecomment-1262133637 if(len) { C4_ASSERT(buf.str != nullptr); C4_ASSERT(v.str != nullptr); memcpy(buf.str, v.str, len); } return v.len; } /** @ingroup doc_from_chars */ inline bool from_chars(csubstr buf, csubstr *C4_RESTRICT v) noexcept { *v = buf; return true; } /** @ingroup doc_from_chars_first */ inline size_t from_chars_first(csubstr buf, csubstr * C4_RESTRICT v) noexcept { csubstr trimmed = buf.first_non_empty_span(); if(trimmed.len == 0) return csubstr::npos; *v = trimmed; return static_cast(trimmed.end() - buf.begin()); } //----------------------------------------------------------------------------- // substr /** @ingroup doc_to_chars */ inline size_t to_chars(substr buf, substr v) noexcept { C4_ASSERT(!buf.overlaps(v)); size_t len = buf.len < v.len ? buf.len : v.len; // calling memcpy zero len is undefined behavior // and will wreak havoc in calling code's branches. // see https://github.com/biojppm/rapidyaml/pull/264#issuecomment-1262133637 if(len) { C4_ASSERT(buf.str != nullptr); C4_ASSERT(v.str != nullptr); memcpy(buf.str, v.str, len); } return v.len; } /** @ingroup doc_from_chars */ inline bool from_chars(csubstr buf, substr * C4_RESTRICT v) noexcept { C4_ASSERT(!buf.overlaps(*v)); // is the destination buffer wide enough? if(v->len >= buf.len) { // calling memcpy with zero len is undefined behavior // and will wreak havoc in calling code's branches. // see https://github.com/biojppm/rapidyaml/pull/264#issuecomment-1262133637 if(buf.len) { C4_ASSERT(buf.str != nullptr); C4_ASSERT(v->str != nullptr); memcpy(v->str, buf.str, buf.len); } v->len = buf.len; return true; } return false; } /** @ingroup doc_from_chars_first */ inline size_t from_chars_first(csubstr buf, substr * C4_RESTRICT v) noexcept { csubstr trimmed = buf.first_non_empty_span(); C4_ASSERT(!trimmed.overlaps(*v)); if C4_UNLIKELY(trimmed.len == 0) return csubstr::npos; size_t len = trimmed.len > v->len ? v->len : trimmed.len; // calling memcpy with zero len is undefined behavior // and will wreak havoc in calling code's branches. // see https://github.com/biojppm/rapidyaml/pull/264#issuecomment-1262133637 if(len) { C4_ASSERT(buf.str != nullptr); C4_ASSERT(v->str != nullptr); memcpy(v->str, trimmed.str, len); } if C4_UNLIKELY(trimmed.len > v->len) return csubstr::npos; return static_cast(trimmed.end() - buf.begin()); } //----------------------------------------------------------------------------- /** @ingroup doc_to_chars * (1) overload for `char(&)[N]` and `const char(&)[N]` */ template size_t to_chars(substr buf, const char (& C4_RESTRICT v)[N]) noexcept { return to_chars(buf, csubstr{v, N-1}); } /** @ingroup doc_to_chars * (2) overload for `char*` and `const char*`. Must be zero-terminated! * @warning will call strlen() * @note this overload uses SFINAE to prevent it from overriding the array overload * @see For a more detailed explanation on why the plain pointer overloads cannot * coexist with the array overloads, see http://cplusplus.bordoon.com/specializeForCharacterArrays.html */ template auto to_chars(substr buf, CharPtr v) noexcept -> typename std::enable_if::value || std::is_same::value, size_t>::type { return v ? to_chars(buf, csubstr{v, strlen(v)}) : 0; } //----------------------------------------------------------------------------- // nullptr implementation /** @ingroup doc_to_chars */ C4_ALWAYS_INLINE size_t to_chars(substr, std::nullptr_t) noexcept { return 0; } // from_chars() and from_chars_sub() must not exist for nullptr /** @} */ } // namespace c4 // NOLINTEND(hicpp-signed-bitwise) #if defined(_MSC_VER) && !defined(__clang__) # pragma warning(pop) #elif defined(__clang__) # pragma clang diagnostic pop #elif defined(__GNUC__) # pragma GCC diagnostic pop #endif #endif /* C4_CHARCONV_HPP_ */ // (end ext/c4core.src/c4/charconv.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/utf.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_UTF_HPP_ #define C4_UTF_HPP_ #ifndef C4_LANGUAGE_HPP_ //#include "c4/language.hpp" // amalgamate: remove include #error "amalgamate: c4/language.hpp must have been amalgamated before this point" #endif /* C4_LANGUAGE_HPP_ */ #ifndef C4_SUBSTR_FWD_HPP_ //#include "c4/substr_fwd.hpp" // amalgamate: remove include #error "amalgamate: c4/substr_fwd.hpp must have been amalgamated before this point" #endif /* C4_SUBSTR_FWD_HPP_ */ #ifndef C4_EXPORT_HPP_ //#include "c4/export.hpp" // amalgamate: remove include #error "amalgamate: c4/export.hpp must have been amalgamated before this point" #endif /* C4_EXPORT_HPP_ */ //#include // amalgamate: included above //#include // amalgamate: included above /** @file utf.hpp utilities for UTF and Byte Order Mark */ namespace c4 { /** @defgroup doc_utf UTF utilities * @{ */ /** skip the Byte Order Mark, or get the full string if there is Byte Order Mark. * @see Implements the Byte Order Marks as described in https://en.wikipedia.org/wiki/Byte_order_mark#Byte-order_marks_by_encoding */ C4CORE_EXPORT substr skip_bom(substr s); /** skip the Byte Order Mark, or get the full string if there is Byte Order Mark * @see Implements the Byte Order Marks as described in https://en.wikipedia.org/wiki/Byte_order_mark#Byte-order_marks_by_encoding */ C4CORE_EXPORT csubstr skip_bom(csubstr s); /** get the Byte Order Mark, or an empty string if there is no Byte Order Mark * @see Implements the Byte Order Marks as described in https://en.wikipedia.org/wiki/Byte_order_mark#Byte-order_marks_by_encoding */ C4CORE_EXPORT substr get_bom(substr s); /** get the Byte Order Mark, or an empty string if there is no Byte Order Mark * @see Implements the Byte Order Marks as described in https://en.wikipedia.org/wiki/Byte_order_mark#Byte-order_marks_by_encoding */ C4CORE_EXPORT csubstr get_bom(csubstr s); /** return the position of the first character not belonging to the * Byte Order Mark, or 0 if there is no Byte Order Mark. * @see Implements the Byte Order Marks as described in https://en.wikipedia.org/wiki/Byte_order_mark#Byte-order_marks_by_encoding */ C4CORE_EXPORT size_t first_non_bom(csubstr s); /** decode the given @p code_point, writing into the output string in * @p out. * * @param out the output string. must have at least 4 bytes (this is * asserted), and must not have a null string. * * @param code_point: must have length in ]0,8], and must not begin * with any of @verbatim `U+`,`\x`,`\u`,`\U`,`0` @endverbatim (asserted) * * @return the part of @p out that was written, which will always be * at most 4 bytes. */ C4CORE_EXPORT substr decode_code_point(substr out, csubstr code_point); /** decode the given @p code point, writing into the output string @p * buf, of size @p buflen * * @param buf the output string. must have at least 4 bytes (this is * asserted), and must not be null * * @param buflen the length of the output string. must be at least 4 * * @param code: the code point must have length in ]0,8], and must not begin * with any of @verbatim `U+`,`\x`,`\u`,`\U`,`0` @endverbatim (asserted) * * @return the number of written characters, which will always be * at most 4 bytes. */ C4CORE_EXPORT size_t decode_code_point(uint8_t *C4_RESTRICT buf, size_t buflen, uint32_t code); /** @} */ } // namespace c4 #endif // C4_UTF_HPP_ // (end ext/c4core.src/c4/utf.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/format.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_FORMAT_HPP_ #define C4_FORMAT_HPP_ /** @file format.hpp provides type-safe facilities for formatting arguments * to string buffers */ #ifndef C4_CHARCONV_HPP_ //#include "c4/charconv.hpp" // amalgamate: remove include #error "amalgamate: c4/charconv.hpp must have been amalgamated before this point" #endif /* C4_CHARCONV_HPP_ */ #ifndef C4_BLOB_HPP_ //#include "c4/blob.hpp" // amalgamate: remove include #error "amalgamate: c4/blob.hpp must have been amalgamated before this point" #endif /* C4_BLOB_HPP_ */ #if defined(_MSC_VER) && !defined(__clang__) # pragma warning(push) # if C4_MSVC_VERSION != C4_MSVC_VERSION_2017 # pragma warning(disable: 4800) // forcing value to bool 'true' or 'false' (performance warning) # endif # pragma warning(disable: 4996) // snprintf/scanf: this function or variable may be unsafe #elif defined(__clang__) # pragma clang diagnostic push #elif defined(__GNUC__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wuseless-cast" #endif // NOLINTBEGIN(cppcoreguidelines-pro-type-reinterpret-cast,*avoid-goto*) /** @defgroup doc_format_utils Format utilities * * @brief Provides generic and type-safe formatting/scanning utilities * built on top of @ref doc_to_chars() and @ref doc_from_chars, * forwarding the arguments to these functions, which in turn use the * @ref doc_charconv utilities. Like @ref doc_charconv, the formatting * facilities are very efficient and many times faster than printf(). * * @see [a formatting sample in rapidyaml's docs](https://rapidyaml.readthedocs.io/latest/doxygen/group__doc__quickstart.html#gac2425b515eb552589708cfff70c52b14) * */ /** @defgroup doc_format_specifiers Format specifiers * * @brief Format specifiers are tag types and functions that are used * together with @ref doc_to_chars and @ref doc_from_chars * * @see [a formatting sample in rapidyaml's docs](https://rapidyaml.readthedocs.io/latest/doxygen/group__doc__quickstart.html#gac2425b515eb552589708cfff70c52b14) * @ingroup doc_format_utils */ namespace c4 { /** @addtogroup doc_format_utils * @{ */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // formatting truthy types as booleans namespace fmt { /** @addtogroup doc_format_specifiers * @{ */ /** @defgroup doc_boolean_specifiers boolean specifiers * @{ */ struct boolalpha_ { bool val; }; /** tag function to mark a variable to be written as an alphabetic * boolean, ie as either true or false */ template boolalpha_ boolalpha(T const& val=false) { return boolalpha_{val ? true : false}; } /** @} */ /** @} */ } // namespace fmt /** write a variable as an alphabetic boolean, ie as either true or * false * @ingroup doc_to_chars */ inline size_t to_chars(substr buf, fmt::boolalpha_ fmt) { return to_chars(buf, fmt.val ? "true" : "false"); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // formatting integral types namespace fmt { /** @addtogroup doc_format_specifiers * @{ */ /** @defgroup doc_integer_specifiers Integer specifiers * @{ */ /** format an integral type with a custom radix */ template struct integral_ { C4_STATIC_ASSERT(std::is_integral::value); T val; T radix; C4_ALWAYS_INLINE integral_(T val_, T radix_) : val(val_), radix(radix_) {} }; /** format an integral type with a custom radix, and pad with zeroes on the left */ template struct integral_padded_ { C4_STATIC_ASSERT(std::is_integral::value); T val; T radix; size_t num_digits; C4_ALWAYS_INLINE integral_padded_(T val_, T radix_, size_t nd) : val(val_), radix(radix_), num_digits(nd) {} }; /** format an integral type with a custom radix */ template C4_ALWAYS_INLINE integral_ integral(T val, T radix=10) { return integral_(val, radix); } /** format an integral type with a custom radix */ template C4_ALWAYS_INLINE integral_ integral(T const* val, T radix=10) { return integral_(reinterpret_cast(val), static_cast(radix)); } /** format an integral type with a custom radix */ template C4_ALWAYS_INLINE integral_ integral(std::nullptr_t, T radix=10) { return integral_(intptr_t(0), static_cast(radix)); } /** format the pointer as an hexadecimal value */ template inline integral_ hex(T * v) { return integral_(reinterpret_cast(v), intptr_t(16)); } /** format the pointer as an hexadecimal value */ template inline integral_ hex(T const* v) { return integral_(reinterpret_cast(v), intptr_t(16)); } /** format null as an hexadecimal value * @overload hex */ inline integral_ hex(std::nullptr_t) { return integral_(0, intptr_t(16)); } /** format the integral_ argument as an hexadecimal value * @overload hex */ template inline integral_ hex(T v) { return integral_(v, T(16)); } /** format the pointer as an octal value */ template inline integral_ oct(T const* v) { return integral_(reinterpret_cast(v), intptr_t(8)); } /** format the pointer as an octal value */ template inline integral_ oct(T * v) { return integral_(reinterpret_cast(v), intptr_t(8)); } /** format null as an octal value */ inline integral_ oct(std::nullptr_t) { return integral_(intptr_t(0), intptr_t(8)); } /** format the integral_ argument as an octal value */ template inline integral_ oct(T v) { return integral_(v, T(8)); } /** format the pointer as a binary 0-1 value * @see c4::raw() if you want to use a binary memcpy instead of 0-1 formatting */ template inline integral_ bin(T const* v) { return integral_(reinterpret_cast(v), intptr_t(2)); } /** format the pointer as a binary 0-1 value * @see c4::raw() if you want to use a binary memcpy instead of 0-1 formatting */ template inline integral_ bin(T * v) { return integral_(reinterpret_cast(v), intptr_t(2)); } /** format null as a binary 0-1 value * @see c4::raw() if you want to use a binary memcpy instead of 0-1 formatting */ inline integral_ bin(std::nullptr_t) { return integral_(intptr_t(0), intptr_t(2)); } /** format the integral_ argument as a binary 0-1 value * @see c4::raw() if you want to use a raw memcpy-based binary dump instead of 0-1 formatting */ template inline integral_ bin(T v) { return integral_(v, T(2)); } /** @} */ // integer_specifiers /** @defgroup doc_zpad Pad the number with zeroes on the left * @{ */ /** pad the argument with zeroes on the left, with decimal radix */ template C4_ALWAYS_INLINE integral_padded_ zpad(T val, size_t num_digits) { return integral_padded_(val, T(10), num_digits); } /** pad the argument with zeroes on the left */ template C4_ALWAYS_INLINE integral_padded_ zpad(integral_ val, size_t num_digits) { return integral_padded_(val.val, val.radix, num_digits); } /** pad the argument with zeroes on the left */ C4_ALWAYS_INLINE integral_padded_ zpad(std::nullptr_t, size_t num_digits) { return integral_padded_(0, 16, num_digits); } /** pad the argument with zeroes on the left */ template C4_ALWAYS_INLINE integral_padded_ zpad(T const* val, size_t num_digits) { return integral_padded_(reinterpret_cast(val), 16, num_digits); } template C4_ALWAYS_INLINE integral_padded_ zpad(T * val, size_t num_digits) { return integral_padded_(reinterpret_cast(val), 16, num_digits); } /** @} */ // zpad /** @defgroup doc_overflow_checked Check read for overflow * @{ */ template struct overflow_checked_ { static_assert(std::is_integral::value, "range checking only for integral types"); C4_ALWAYS_INLINE overflow_checked_(T &val_) : val(&val_) {} T *val; }; template C4_ALWAYS_INLINE overflow_checked_ overflow_checked(T &val) { return overflow_checked_(val); } /** @} */ // overflow_checked /** @} */ // format_specifiers } // namespace fmt /** format an integer signed type * @ingroup doc_to_chars */ template C4_ALWAYS_INLINE auto to_chars(substr buf, fmt::integral_ fmt) -> typename std::enable_if::value, size_t>::type { return itoa(buf, fmt.val, fmt.radix); } /** format an integer signed type, pad with zeroes * @ingroup doc_to_chars */ template C4_ALWAYS_INLINE auto to_chars(substr buf, fmt::integral_padded_ fmt) -> typename std::enable_if::value, size_t>::type { return itoa(buf, fmt.val, fmt.radix, fmt.num_digits); } /** format an integer unsigned type * @ingroup doc_to_chars */ template C4_ALWAYS_INLINE auto to_chars(substr buf, fmt::integral_ fmt) -> typename std::enable_if::value, size_t>::type { return utoa(buf, fmt.val, fmt.radix); } /** format an integer unsigned type, pad with zeroes * @ingroup doc_to_chars */ template C4_ALWAYS_INLINE auto to_chars(substr buf, fmt::integral_padded_ fmt) -> typename std::enable_if::value, size_t>::type { return utoa(buf, fmt.val, fmt.radix, fmt.num_digits); } /** read an integer type, detecting overflow (returns false on overflow) * @ingroup doc_from_chars */ template C4_ALWAYS_INLINE bool from_chars(csubstr s, fmt::overflow_checked_ wrapper) { if C4_LIKELY(!overflows(s)) return atox(s, wrapper.val); return false; } /** read an integer type, detecting overflow (returns false on overflow) * @ingroup doc_from_chars */ template C4_ALWAYS_INLINE bool from_chars(csubstr s, fmt::overflow_checked_ *wrapper) { if C4_LIKELY(!overflows(s)) return atox(s, wrapper->val); return false; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // formatting real types namespace fmt { /** @addtogroup doc_format_specifiers * @{ */ /** @defgroup doc_real_specifiers Real specifiers * @{ */ template struct real_ { T val; int precision; RealFormat_e fmt; real_(T v, int prec=-1, RealFormat_e f=FTOA_FLOAT) : val(v), precision(prec), fmt(f) {} }; template real_ real(T val, int precision, RealFormat_e fmt=FTOA_FLOAT) { return real_(val, precision, fmt); } /** @} */ // real_specifiers /** @} */ // format_specifiers } // namespace fmt /** @ingroup doc_to_chars */ inline size_t to_chars(substr buf, fmt::real_< float> fmt) { return ftoa(buf, fmt.val, fmt.precision, fmt.fmt); } /** @ingroup doc_to_chars */ inline size_t to_chars(substr buf, fmt::real_ fmt) { return dtoa(buf, fmt.val, fmt.precision, fmt.fmt); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // writing raw binary data namespace fmt { /** @addtogroup doc_format_specifiers * @{ */ /** @defgroup doc_raw_binary_specifiers Raw binary data * @{ */ /** @see blob_ */ template struct raw_wrapper_ : public blob_ { size_t alignment; C4_ALWAYS_INLINE raw_wrapper_(blob_ data, size_t alignment_) noexcept : blob_(data), alignment(alignment_) { C4_ASSERT_MSG(alignment > 0 && (alignment & (alignment - 1)) == 0, "alignment must be a power of two"); } }; using const_raw_wrapper = raw_wrapper_; using raw_wrapper = raw_wrapper_; /** mark a variable to be written in raw binary format, using memcpy * @see blob_ */ inline const_raw_wrapper craw(cblob data, size_t alignment=alignof(max_align_t)) { return const_raw_wrapper(data, alignment); } /** mark a variable to be written in raw binary format, using memcpy * @see blob_ */ inline const_raw_wrapper raw(cblob data, size_t alignment=alignof(max_align_t)) { return const_raw_wrapper(data, alignment); } /** mark a variable to be written in raw binary format, using memcpy * @see blob_ */ template inline const_raw_wrapper craw(T const& C4_RESTRICT data, size_t alignment=alignof(T)) { return const_raw_wrapper(cblob(data), alignment); } /** mark a variable to be written in raw binary format, using memcpy * @see blob_ */ template inline const_raw_wrapper raw(T const& C4_RESTRICT data, size_t alignment=alignof(T)) { return const_raw_wrapper(cblob(data), alignment); } /** mark a variable to be read in raw binary format, using memcpy */ inline raw_wrapper raw(blob data, size_t alignment=alignof(max_align_t)) { return raw_wrapper(data, alignment); } /** mark a variable to be read in raw binary format, using memcpy */ template inline raw_wrapper raw(T & C4_RESTRICT data, size_t alignment=alignof(T)) { return raw_wrapper(blob(data), alignment); } /** @} */ // raw_binary_specifiers /** @} */ // format_specifiers } // namespace fmt /** write a variable in raw binary format, using memcpy * @ingroup doc_to_chars */ C4CORE_EXPORT size_t to_chars(substr buf, fmt::const_raw_wrapper r); /** read a variable in raw binary format, using memcpy * @ingroup doc_from_chars */ C4CORE_EXPORT bool from_chars(csubstr buf, fmt::raw_wrapper *r); /** read a variable in raw binary format, using memcpy * @ingroup doc_from_chars */ inline bool from_chars(csubstr buf, fmt::raw_wrapper r) { return from_chars(buf, &r); } /** read a variable in raw binary format, using memcpy * @ingroup doc_from_chars_first */ inline size_t from_chars_first(csubstr buf, fmt::raw_wrapper *r) { return from_chars(buf, r); } /** read a variable in raw binary format, using memcpy * @ingroup doc_from_chars_first */ inline size_t from_chars_first(csubstr buf, fmt::raw_wrapper r) { return from_chars(buf, &r); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // formatting aligned to left/right/center namespace fmt { /** @addtogroup doc_format_specifiers * @{ */ /** @defgroup doc_alignment_specifiers Alignment specifiers * @{ */ template struct left_ { T val; size_t width; char padchar; C4_ALWAYS_INLINE left_ (T v, size_t w, char c) noexcept : val(v), width(w), padchar(c) {} }; template struct center_ { T val; size_t width; char padchar; C4_ALWAYS_INLINE center_(T v, size_t w, char c) noexcept : val(v), width(w), padchar(c) {} }; template struct right_ { T val; size_t width; char padchar; C4_ALWAYS_INLINE right_ (T v, size_t w, char c) noexcept : val(v), width(w), padchar(c) {} }; /** tag type to mark an argument to be aligned left. * @param val the argument to be aligned left * @param width the length of the field * @param padchar the padding character, defaults to ' ' * * @note This function (and the return structure) uses value semantics. To * avoid copies on larger types, you can use std::cref(). For example: * @code{.cpp} * char buf[512]; * std::string large_string = .....; * size_t len = cat(buf, fmt::left(std::cref(large_string), 100)); * @endcode */ template left_ left(T val, size_t width, char padchar=' ') { return left_(val, width, padchar); } /** tag function to mark an argument to be aligned center * @param val the argument to be aligned center * @param width the length of the field * @param padchar the padding character, defaults to ' ' * * @note This function (and the return value) uses value semantics. To * avoid copies on larger types, you can use std::cref(). For example: * @code{.cpp} * char buf[512]; * std::string large_string = .....; * size_t len = cat(buf, fmt::center(std::cref(large_string), 100)); * @endcode */ template center_ center(T val, size_t width, char padchar=' ') { return center_(val, width, padchar); } /** tag function to mark an argument to be aligned right * @param val the argument to be aligned right * @param width the length of the field * @param padchar the padding character, defaults to ' ' * * @note This function (and the return value) uses value semantics. To * avoid copies on larger types, you can use std::cref(). For example: * @code{.cpp} * char buf[512]; * std::string large_string = .....; * size_t len = cat(buf, fmt::right(std::cref(large_string), 100)); * @endcode */ template right_ right(T val, size_t width, char padchar=' ') { return right_(val, width, padchar); } /** @} */ // alignment_specifiers /** @} */ // format_specifiers } // namespace fmt /** @ingroup doc_to_chars */ template size_t to_chars(substr buf, fmt::left_ const& C4_RESTRICT align) { size_t ret = to_chars(buf, align.val); if(ret >= buf.len || ret >= align.width) return ret > align.width ? ret : align.width; buf.first(align.width).sub(ret).fill(align.padchar); return align.width; } /** @ingroup doc_to_chars */ template size_t to_chars(substr buf, fmt::right_ const& C4_RESTRICT align) { size_t ret = to_chars(buf, align.val); if(ret >= buf.len || ret >= align.width) return ret > align.width ? ret : align.width; size_t rem = align.width - ret; if(ret) memmove(buf.str + rem, buf.str, ret); buf.first(rem).fill(align.padchar); return align.width; } /** @ingroup doc_to_chars */ template size_t to_chars(substr buf, fmt::center_ const& C4_RESTRICT align) { size_t ret = to_chars(buf, align.val); if(ret >= buf.len || ret >= align.width) return ret > align.width ? ret : align.width; size_t first = (align.width - ret) / 2u; if(ret) memmove(buf.str + first, buf.str, ret); buf.first(first).fill(align.padchar); buf.sub(first + ret).fill(align.padchar); return align.width; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @defgroup doc_cat cat: concatenate arguments to string * @{ */ /** @cond dev */ // terminates the variadic recursion inline size_t cat(substr /*buf*/) { return 0; } /** @endcond */ /** serialize the arguments, concatenating them to the given fixed-size buffer. * The buffer size is strictly respected: no writes will occur beyond its end. * @return the number of characters needed to write all the arguments into the buffer. * @see @ref c4::catrs() if instead of a fixed-size buffer, a resizeable container is desired * @see @ref c4::uncat() for the inverse function * @see @ref c4::catsep() if a separator between each argument is to be used * @see @ref c4::format() if a format string is desired * * @note The arguments to format are restricted (legal because they * are rvalues). This may require a workaround when arguments of type * char[]/const char[] are passed repeatedly to the function. For * example, * @code{.cpp} * const char str[] = "Hi! "; * cat(buf, str, str, str); // compile error: 'passing argument 2 to ‘restrict’-qualified parameter aliases with arguments 3, 4' * @endcode * It is possible to work around the problem by suppressing -Wrestrict * or by using the decayed type char* or const char*, or even wrapping * the argument in a csubstr(): * @code{.cpp} * const char str[] = "Hi! "; * csubstr ss = to_csubstr(str); * cat(buf, ss, ss, ss); // ok! compiles cleanly * @endcode */ template size_t cat(substr buf, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { size_t num = to_chars(buf, a); buf = buf.len >= num ? buf.sub(num) : substr{}; num += cat(buf, more...); return num; } /** like @ref c4::cat() but return a substr instead of a size */ template substr cat_sub(substr buf, Args const& C4_RESTRICT ...args) { size_t sz = cat(buf, args...); C4_CHECK(sz <= buf.len); return {buf.str, sz <= buf.len ? sz : buf.len}; } /** @} */ //----------------------------------------------------------------------------- /** @defgroup doc_uncat uncat: read concatenated arguments from string * @{ */ /** @cond dev */ // terminates the variadic recursion inline size_t uncat(csubstr /*buf*/) { return 0; } /** @endcond */ /** deserialize the arguments from the given buffer. * * @return the number of characters read from the buffer, or csubstr::npos * if a conversion was not successful. * @see @ref c4::cat(). @ref c4::uncat() is the inverse of @ref c4::cat(). */ template size_t uncat(csubstr buf, Arg & C4_RESTRICT a, Args & C4_RESTRICT ...more) { size_t out = from_chars_first(buf, &a); if C4_UNLIKELY(out == csubstr::npos) return csubstr::npos; buf = buf.len >= out ? buf.sub(out) : substr{}; size_t num = uncat(buf, more...); if C4_UNLIKELY(num == csubstr::npos) return csubstr::npos; return out + num; } /** @} */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @defgroup doc_catsep catsep: cat arguments to string with separator * @{ */ /** @cond dev */ namespace detail { template C4_ALWAYS_INLINE size_t catsep_more(substr /*buf*/, Sep const& C4_RESTRICT /*sep*/) { return 0; } template size_t catsep_more(substr buf, Sep const& C4_RESTRICT sep, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { size_t ret = to_chars(buf, sep); size_t num = ret; buf = buf.len >= ret ? buf.sub(ret) : substr{}; ret = to_chars(buf, a); num += ret; buf = buf.len >= ret ? buf.sub(ret) : substr{}; ret = catsep_more(buf, sep, more...); num += ret; return num; } } // namespace detail // terminates the variadic recursion template size_t catsep(substr /*buf*/, Sep const& C4_RESTRICT /*sep*/) { return 0; } /** @endcond */ /** serialize the arguments, concatenating them to the given fixed-size * buffer, using a separator between each argument. * The buffer size is strictly respected: no writes will occur beyond its end. * @return the number of characters needed to write all the arguments into the buffer. * @see @ref c4::catseprs() if instead of a fixed-size buffer, a resizeable container is desired * @see @ref c4::uncatsep() for the inverse function (ie, reading instead of writing) * @see @ref c4::cat() if no separator is needed * @see @ref c4::format() if a format string is desired * * * @note The arguments to format are restricted (legal because they * are rvalues). This may require a workaround when arguments of type * char[]/const char[] are passed repeatedly to the function. For * example, * @code{.cpp} * const char str[] = "Hi! "; * cat(buf, str, str, str); // compile error: 'passing argument 2 to ‘restrict’-qualified parameter aliases with arguments 3, 4' * @endcode * It is possible to work around the problem by suppressing -Wrestrict * or by using the decayed type char* or const char*, or even wrapping * the argument in a csubstr(): * @code{.cpp} * const char str[] = "Hi! "; * csubstr ss = to_csubstr(str); * cat(buf, ss, ss, ss); // ok! compiles cleanly * @endcode */ template size_t catsep(substr buf, Sep const& C4_RESTRICT sep, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { size_t num = to_chars(buf, a); buf = buf.len >= num ? buf.sub(num) : substr{}; num += detail::catsep_more(buf, sep, more...); return num; } /** like @ref c4::catsep() but return a substr instead of a size @see * @ref c4::catsep(). @ref c4::uncatsep() is the inverse of @ref * c4::catsep(). */ template substr catsep_sub(substr buf, Args && ...args) { size_t sz = catsep(buf, std::forward(args)...); C4_CHECK(sz <= buf.len); return {buf.str, sz <= buf.len ? sz : buf.len}; } /** @} */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @defgroup doc_uncatsep uncatsep: deserialize the separated arguments from a string * @{ */ /** @cond dev */ template inline size_t uncatsep(csubstr buf, csubstr /*sep*/, Arg &C4_RESTRICT a) { return from_chars(buf, &a) ? buf.len : csubstr::npos; } /** @endcond */ /** deserialize the arguments from the given buffer, using a separator. * * @return the number of characters read from the buffer, or csubstr::npos * if a conversion was not successful * * @see c4::catsep(). @ref c4::uncatsep() is the inverse of @ref c4::catsep(). */ template size_t uncatsep(csubstr buf, csubstr sep, Arg & C4_RESTRICT a, Args & C4_RESTRICT ...more) { if C4_LIKELY(sep.len > 0) { size_t pos = buf.find(sep); if C4_LIKELY(pos != csubstr::npos) { if C4_LIKELY(from_chars(buf.first(pos), &a)) { pos += sep.len; size_t num = uncatsep(buf.sub(pos), sep, more...); if C4_LIKELY(num != csubstr::npos) return pos + num; } } } return csubstr::npos; } /** @} */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @defgroup doc_format format: formatted string interpolation * @{ */ /// @cond dev // terminates the variadic recursion inline size_t format(substr buf, csubstr fmt) { return to_chars(buf, fmt); } /// @endcond /** Using a format string, serialize the arguments into the given * fixed-size buffer. The buffer size is strictly respected: no writes * will occur beyond its end. In the format string, each argument is * marked with a compact curly-bracket pair "{}". This pair does not * take any interior sequence numbers or extra formatting arguments * inside it (contrary to eg the C++20 std::format implementation or * the Python formatting facilities). To enable argument * customization, use the formatting facilities in @ref * doc_format_specifiers wrapping the arguments passed to this * function. * * @return the number of bytes needed to write into the buffer. * * @see @ref c4::formatrs() if instead of a fixed-size buffer, a resizeable container is desired * @see @ref c4::unformat() for the inverse function * @see @ref c4::cat() if no format or separator is needed * @see @ref c4::catsep() if no format is needed, but a separator must be used * * For example: * @code{.cpp} * c4::format(buf, "the {} drank {} {}", "partier", 5, "beers"); // the partier drank 5 beers * c4::format(buf, "the {} drank {} {}", "programmer", 6, "coffees"); // the programmer drank 6 coffees * @endcode * * Using @ref * doc_format_specifiers enables control of the result. For example: * @code{.cpp} * c4::format(buf, "the {} drank {} {}", "partier", c4::fmt::real(5, 3), "beers"); // the partier drank 5.000 beers * c4::format(buf, "the {} drank {} {}", "partier", c4::fmt::zpad(5, 3), "beers"); // the partier drank 005 beers * c4::format(buf, "the {} drank {} {}", "partier", c4::fmt::bin(5), "beers"); // the partier drank 0b101 beers * c4::format(buf, "the {} drank {} {}", "partier", c4::fmt::oct(5), "beers"); // the partier drank 0o6 beers * c4::format(buf, "the {} drank {} {}", "partier", c4::fmt::hex(5), "beers"); // the partier drank 0x6 beers * c4::format(buf, "the {} drank {} {}", "programmer", c4::fmt::real(6, 3), "coffees"); // the programmer drank 6.000 coffees * c4::format(buf, "the {} drank {} {}", "programmer", c4::fmt::zpad(6, 3), "coffees"); // the programmer drank 006 coffees * c4::format(buf, "the {} drank {} {}", "programmer", c4::fmt::bin(6), "coffees"); // the programmer drank 0b110 coffees * c4::format(buf, "the {} drank {} {}", "programmer", c4::fmt::oct(6), "coffees"); // the programmer drank 0o6 coffees * c4::format(buf, "the {} drank {} {}", "programmer", c4::fmt::hex(6), "coffees"); // the programmer drank 0x6 coffees * @endcode * * @note Arguments beyond the last curly bracket pair are silently * ignored. Curly bracket pairs without a corresponding argument are * printed as part of the result. * @code{.cpp} * // note "and nothing else" being ignored * c4::format(buf, "the {} drank {} {}", "partier", 5, "beers", "and nothing else"); // the partier drank 5 beers * * // note "this is ignored {}" being part of the result * c4::format(buf, "the {} drank {} {} this is ignored: {}", "programmer", 6, "coffees"); // the programmer drank 6 coffees this is ignored: {} * @endcode * * @note The curly bracket pair cannot be escaped, but can of course * be placed into the result by passing an "{}" argument in its place, * or if it is provided beyond the last argument passed to the * function (see prior note). * @code{.cpp} * // as above: no argument given, so no substitution made: * c4::format(buf, "let's show {} on the result"); // let's show {} on the result * // or just pass "{}" as an argument to force the substitution: * c4::format(buf, "let's show {} on the result and then {}", "{}", "this"); // let's show {} on the result and then this * @endcode * * @note The arguments to format are restricted (legal because they * are rvalues). This may require a workaround when arguments of type * char[]/const char[] are passed repeatedly to the function. For * example, * @code{.cpp} * const char str[] = "Hi! "; * cat(buf, str, str, str); // compile error: 'passing argument 2 to ‘restrict’-qualified parameter aliases with arguments 3, 4' * @endcode * It is possible to work around the problem by suppressing -Wrestrict * or by using the decayed type char* or const char*, or even wrapping * the argument in a csubstr(): * @code{.cpp} * const char str[] = "Hi! "; * csubstr ss = to_csubstr(str); * cat(buf, ss, ss, ss); // ok! compiles cleanly * @endcode */ template size_t format(substr buf, csubstr fmt, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { size_t pos = fmt.find("{}"); if C4_UNLIKELY(pos == csubstr::npos) return to_chars(buf, fmt); size_t num = to_chars(buf, fmt.first(pos)); size_t out = num; buf = buf.len >= num ? buf.sub(num) : substr{}; num = to_chars(buf, a); out += num; buf = buf.len >= num ? buf.sub(num) : substr{}; num = format(buf, fmt.sub(pos + 2), more...); out += num; return out; } /** like @ref c4::format() but return a substr instead of a size * @see c4::format() * @see c4::catsep(). @ref c4::uncatsep() is the inverse of @ref c4::catsep(). */ template substr format_sub(substr buf, csubstr fmt, Args const& C4_RESTRICT ...args) { size_t sz = c4::format(buf, fmt, args...); C4_CHECK(sz <= buf.len); return {buf.str, sz <= buf.len ? sz : buf.len}; } /** @} */ //----------------------------------------------------------------------------- /** @defgroup doc_unformat unformat: formatted read from string * @{ */ /// @cond dev // terminates the variadic recursion inline size_t unformat(csubstr /*buf*/, csubstr fmt) { return fmt.len; } /// @endcond /** using a format string, deserialize the arguments from the given * buffer. This is the inverse function to @ref c4::format(). * * @return the number of characters read from the buffer, or npos if a conversion failed. * * @see @ref c4::format(). */ template size_t unformat(csubstr buf, csubstr fmt, Arg & C4_RESTRICT a, Args & C4_RESTRICT ...more) { const size_t pos = fmt.find("{}"); if C4_UNLIKELY(pos == csubstr::npos) return unformat(buf, fmt); size_t num = pos; size_t out = num; buf = buf.len >= num ? buf.sub(num) : substr{}; num = from_chars_first(buf, &a); if C4_UNLIKELY(num == csubstr::npos) return csubstr::npos; out += num; buf = buf.len >= num ? buf.sub(num) : substr{}; num = unformat(buf, fmt.sub(pos + 2), more...); if C4_UNLIKELY(num == csubstr::npos) return csubstr::npos; out += num; return out; } /** @} */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** cat+resize: like @ref c4::cat(), but receives a container, and * resizes it as needed to contain the result. The container is * overwritten. To append to it, use @ref c4::catrs_append(). * * @see @ref c4::cat() * @see @ref c4::catrs_append() * @ingroup doc_cat * * @note The arguments to format are restricted (legal because they * are rvalues). This may require a workaround when arguments of type * char[]/const char[] are passed repeatedly to the function. For * example, * @code{.cpp} * const char str[] = "Hi! "; * cat(buf, str, str, str); // compile error: 'passing argument 2 to ‘restrict’-qualified parameter aliases with arguments 3, 4' * @endcode * It is possible to work around the problem by suppressing -Wrestrict * or by using the decayed type char* or const char*, or even wrapping * the argument in a csubstr(): * @code{.cpp} * const char str[] = "Hi! "; * csubstr ss = to_csubstr(str); * cat(buf, ss, ss, ss); // ok! compiles cleanly * @endcode */ template inline void catrs(CharOwningContainer * C4_RESTRICT cont, Args const& C4_RESTRICT ...args) { cont->resize(cont->capacity()); // improve the odds of fitting in the original buffer retry: substr buf = to_substr(*cont); size_t ret = cat(buf, args...); cont->resize(ret); if(ret > buf.len) goto retry; } /** cat+resize: like @ref c4::cat(), but creates and returns a new * container sized as needed to contain the result. * * @see @ref c4::cat() * @ingroup doc_cat * * @note The arguments to format are restricted (legal because they * are rvalues). This may require a workaround when arguments of type * char[]/const char[] are passed repeatedly to the function. For * example, * @code{.cpp} * const char str[] = "Hi! "; * cat(buf, str, str, str); // compile error: 'passing argument 2 to ‘restrict’-qualified parameter aliases with arguments 3, 4' * @endcode * It is possible to work around the problem by suppressing -Wrestrict * or by using the decayed type char* or const char*, or even wrapping * the argument in a csubstr(): * @code{.cpp} * const char str[] = "Hi! "; * csubstr ss = to_csubstr(str); * cat(buf, ss, ss, ss); // ok! compiles cleanly * @endcode */ template inline CharOwningContainer catrs(Args const& C4_RESTRICT ...args) { CharOwningContainer cont; catrs(&cont, args...); return cont; } /** cat+resize+append: like @ref c4::cat(), but receives a container, * and appends to it instead of overwriting it. The container is * resized as needed to contain the result. * * @return the region newly appended to the original container * @see @ref c4::cat() * @see @ref c4::catrs() * @ingroup doc_cat * * @note The arguments to format are restricted (legal because they * are rvalues). This may require a workaround when arguments of type * char[]/const char[] are passed repeatedly to the function. For * example, * @code{.cpp} * const char str[] = "Hi! "; * cat(buf, str, str, str); // compile error: 'passing argument 2 to ‘restrict’-qualified parameter aliases with arguments 3, 4' * @endcode * It is possible to work around the problem by suppressing -Wrestrict * or by using the decayed type char* or const char*, or even wrapping * the argument in a csubstr(): * @code{.cpp} * const char str[] = "Hi! "; * csubstr ss = to_csubstr(str); * cat(buf, ss, ss, ss); // ok! compiles cleanly * @endcode */ template inline csubstr catrs_append(CharOwningContainer * C4_RESTRICT cont, Args const& C4_RESTRICT ...args) { const size_t pos = cont->size(); cont->resize(cont->capacity()); // improve the odds of fitting in the original buffer retry: substr buf = to_substr(*cont).sub(pos); size_t ret = cat(buf, args...); cont->resize(pos + ret); if(ret > buf.len) goto retry; return to_csubstr(*cont).range(pos, cont->size()); } //----------------------------------------------------------------------------- /** catsep+resize: like @ref c4::catsep(), but receives a container, * and resizes it as needed to contain the result. The container is * overwritten. To append to the container use @ref * c4::catseprs_append(). * * @see @ref c4::catsep() * @see @ref c4::catseprs_append() * @ingroup doc_catsep * * @note The arguments to format are restricted (legal because they * are rvalues). This may require a workaround when arguments of type * char[]/const char[] are passed repeatedly to the function. For * example, * @code{.cpp} * const char str[] = "Hi! "; * cat(buf, str, str, str); // compile error: 'passing argument 2 to ‘restrict’-qualified parameter aliases with arguments 3, 4' * @endcode * It is possible to work around the problem by suppressing -Wrestrict * or by using the decayed type char* or const char*, or even wrapping * the argument in a csubstr(): * @code{.cpp} * const char str[] = "Hi! "; * csubstr ss = to_csubstr(str); * cat(buf, ss, ss, ss); // ok! compiles cleanly * @endcode */ template inline void catseprs(CharOwningContainer * C4_RESTRICT cont, Sep const& C4_RESTRICT sep, Args const& C4_RESTRICT ...args) { cont->resize(cont->capacity()); // improve the odds of fitting in the original buffer retry: substr buf = to_substr(*cont); size_t ret = catsep(buf, sep, args...); cont->resize(ret); if(ret > buf.len) goto retry; } /** catsep+resize: like @ref c4::catsep(), but create a new container * with the result. * * @return the requested container * @ingroup doc_catsep * * @note The arguments to format are restricted (legal because they * are rvalues). This may require a workaround when arguments of type * char[]/const char[] are passed repeatedly to the function. For * example, * @code{.cpp} * const char str[] = "Hi! "; * cat(buf, str, str, str); // compile error: 'passing argument 2 to ‘restrict’-qualified parameter aliases with arguments 3, 4' * @endcode * It is possible to work around the problem by suppressing -Wrestrict * or by using the decayed type char* or const char*, or even wrapping * the argument in a csubstr(): * @code{.cpp} * const char str[] = "Hi! "; * csubstr ss = to_csubstr(str); * cat(buf, ss, ss, ss); // ok! compiles cleanly * @endcode */ template inline CharOwningContainer catseprs(Sep const& C4_RESTRICT sep, Args const& C4_RESTRICT ...args) { CharOwningContainer cont; catseprs(&cont, sep, args...); return cont; } /** catsep+resize+append: like @ref c4::catsep(), but receives a * container, and appends the arguments, resizing the container as * needed to contain the result. The buffer is appended to. * * @return a csubstr of the appended part * @ingroup doc_catsep * * @note The arguments to format are restricted (legal because they * are rvalues). This may require a workaround when arguments of type * char[]/const char[] are passed repeatedly to the function. For * example, * @code{.cpp} * const char str[] = "Hi! "; * cat(buf, str, str, str); // compile error: 'passing argument 2 to ‘restrict’-qualified parameter aliases with arguments 3, 4' * @endcode * It is possible to work around the problem by suppressing -Wrestrict * or by using the decayed type char* or const char*, or even wrapping * the argument in a csubstr(): * @code{.cpp} * const char str[] = "Hi! "; * csubstr ss = to_csubstr(str); * cat(buf, ss, ss, ss); // ok! compiles cleanly * @endcode */ template inline csubstr catseprs_append(CharOwningContainer * C4_RESTRICT cont, Sep const& C4_RESTRICT sep, Args const& C4_RESTRICT ...args) { const size_t pos = cont->size(); cont->resize(cont->capacity()); // improve the odds of fitting in the original buffer retry: substr buf = to_substr(*cont).sub(pos); size_t ret = catsep(buf, sep, args...); cont->resize(pos + ret); if(ret > buf.len) goto retry; return to_csubstr(*cont).range(pos, cont->size()); } //----------------------------------------------------------------------------- /** format+resize: like @ref c4::format(), but receives a container, * and resizes it as needed to contain the result. The container is * overwritten. To append to the container use @ref * c4::formatrs_append(). * * @see @ref c4::format() * @see @ref c4::formatrs_append() * @ingroup doc_format * * @note The arguments to format are restricted (legal because they * are rvalues). This may require a workaround when arguments of type * char[]/const char[] are passed repeatedly to the function. For * example, * @code{.cpp} * const char str[] = "Hi! "; * cat(buf, str, str, str); // compile error: 'passing argument 2 to ‘restrict’-qualified parameter aliases with arguments 3, 4' * @endcode * It is possible to work around the problem by suppressing -Wrestrict * or by using the decayed type char* or const char*, or even wrapping * the argument in a csubstr(): * @code{.cpp} * const char str[] = "Hi! "; * csubstr ss = to_csubstr(str); * cat(buf, ss, ss, ss); // ok! compiles cleanly * @endcode */ template inline void formatrs(CharOwningContainer * C4_RESTRICT cont, csubstr fmt, Args const& C4_RESTRICT ...args) { cont->resize(cont->capacity()); // improve the odds of fitting in the original buffer retry: substr buf = to_substr(*cont); size_t ret = format(buf, fmt, args...); cont->resize(ret); if(ret > buf.len) goto retry; } /** format+resize: like @ref c4::format(), but create a new container * with the result. * * @return the requested container * @ingroup doc_format * * @note The arguments to format are restricted (legal because they * are rvalues). This may require a workaround when arguments of type * char[]/const char[] are passed repeatedly to the function. For * example, * @code{.cpp} * const char str[] = "Hi! "; * cat(buf, str, str, str); // compile error: 'passing argument 2 to ‘restrict’-qualified parameter aliases with arguments 3, 4' * @endcode * It is possible to work around the problem by suppressing -Wrestrict * or by using the decayed type char* or const char*, or even wrapping * the argument in a csubstr(): * @code{.cpp} * const char str[] = "Hi! "; * csubstr ss = to_csubstr(str); * cat(buf, ss, ss, ss); // ok! compiles cleanly * @endcode */ template inline CharOwningContainer formatrs(csubstr fmt, Args const& C4_RESTRICT ...args) { CharOwningContainer cont; formatrs(&cont, fmt, args...); return cont; } /** format+resize+append: like @ref c4::format(), but receives a * container, and appends the arguments, resizing the container as * needed to contain the result. The buffer is appended to. * * @return the region newly appended to the original container * @ingroup doc_format * * @note The arguments to format are restricted (legal because they * are rvalues). This may require a workaround when arguments of type * char[]/const char[] are passed repeatedly to the function. For * example, * @code{.cpp} * const char str[] = "Hi! "; * cat(buf, str, str, str); // compile error: 'passing argument 2 to ‘restrict’-qualified parameter aliases with arguments 3, 4' * @endcode * It is possible to work around the problem by suppressing -Wrestrict * or by using the decayed type char* or const char*, or even wrapping * the argument in a csubstr(): * @code{.cpp} * const char str[] = "Hi! "; * csubstr ss = to_csubstr(str); * cat(buf, ss, ss, ss); // ok! compiles cleanly * @endcode */ template inline csubstr formatrs_append(CharOwningContainer * C4_RESTRICT cont, csubstr fmt, Args const& C4_RESTRICT ...args) { const size_t pos = cont->size(); C4_SUPPRESS_WARNING_GCC_WITH_PUSH("-Warray-bounds") cont->resize(cont->capacity()); // improve the odds of fitting in the original buffer C4_SUPPRESS_WARNING_GCC_POP retry: substr buf = to_substr(*cont).sub(pos); size_t ret = format(buf, fmt, args...); cont->resize(pos + ret); if(ret > buf.len) goto retry; return to_csubstr(*cont).range(pos, cont->size()); } /** @} */ } // namespace c4 // NOLINTEND(cppcoreguidelines-pro-type-reinterpret-cast,*avoid-goto*) #ifdef _MSC_VER # pragma warning(pop) #elif defined(__clang__) # pragma clang diagnostic pop #elif defined(__GNUC__) # pragma GCC diagnostic pop #endif #endif /* C4_FORMAT_HPP_ */ // (end ext/c4core.src/c4/format.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/dump.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_DUMP_HPP_ #define C4_DUMP_HPP_ #ifndef C4_SUBSTR_HPP_ //#include // amalgamate: remove include #error "amalgamate: c4/substr.hpp must have been amalgamated before this point" #endif /* C4_SUBSTR_HPP_ */ //#include // for std::forward // amalgamate: included above /** @file dump.hpp This file provides functions to dump several * arguments as strings to a user-provided function sink, for example * to implement a type-safe printf()-like function (where the sink * would just be a plain call to putchars()). The function sink can be * passed either by dynamic dispatching or by static dispatching (as a * template argument). There are analogs to @ref c4::cat() (@ref * c4::cat_dump() and @ref c4::cat_dump_resume()), @ref c4::catsep() * (@ref c4::catsep_dump() and @ref c4::catsep_dump_resume()) and @ref * c4::format() (@ref c4::format_dump() and @ref * c4::format_dump_resume()). The analogs have two types: immediate * and resuming. An analog of immediate type cannot be retried when * the work buffer is too small; this means that successful dumps in * the first (successful) arguments will be dumped again in the * subsequent attempt to call. An analog of resuming type will only * ever dump as-yet-undumped arguments, through the use of @ref * c4::DumpResults return type. */ namespace c4 { C4_SUPPRESS_WARNING_GCC_CLANG_WITH_PUSH("-Wold-style-cast") //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @defgroup dump_building_blocks Basic building blocks for dumping. * * The basic building block: given an argument and a * buffer, serialize the argument to the buffer using @ref * c4::to_chars(), and dump the buffer to the provided sink * function. When the argument is a string, no serialization is * performed, and the argument is dumped directly to the sink. * * @{ */ /** Type of the function to be used as the sink. This function * receives as its argument the string with characters to send to the * sink. * * @warning the string passed to the sink may have zero length. If the * user sink uses memcpy(), the call to memcpy() should be defended * with a check for zero length (calling memcpy with zero length is * undefined behavior). * */ using SinkPfn = void (*)(csubstr str); /** @cond dev */ namespace detail { // std::remove_cvref appeared in c++20 template struct _remove_cvref { using type = typename std::remove_cv::type>::type; }; } // namespace detail /** @endcond */ template struct is_string; // fwd-decl /** a traits class used by @ref c4::dump() to decide whether a type is * treated as a string type (which is dumped directly to the sink via * to_csubstr()), or if the type is treated as a value, which is first * serialized to the dump buffer using to_chars() prior to dumping it * to the sink. This type defaults to @ref c4::is_string, but can be * overriden independently. */ template struct dump_directly : public is_string::type> {}; #if (C4_CPP >= 17) || defined(__DOXYGEN__) /** Dump a serializable object to the (statically dispatched) * sink. Before dumping, the object may be serialized to a string if * @ref c4::dump_directly is a false type (the default if * dump_directly does not have a specialization). Otherwise the object * is considered a string object and is therefore dumped directly, * without any intermediate serialization. * * @return the number of bytes needed to serialize the string-type * object, which may be 0 when there is no serialization * * @note the argument is considered a value when @ref * c4::dump_directly is a false type, which is the default. To enable * the argument to be treated as a string type, which is dumped * directly to the sink without intermediate serialization, define * @ref c4::dump_directly to a true type. * * @warning the string passed to the sink may have zero length. If the * user sink uses memcpy(), the call to memcpy() should be defended * with a check for zero length (calling memcpy with zero length is * undefined behavior). * * @see @ref c4::dump_directly */ template size_t dump(substr buf, Arg const& a) { if constexpr (dump_directly::value) { C4_UNUSED(buf); csubstr sa = to_csubstr(a); C4_ASSERT(!buf.overlaps(sa)); // dump directly, no need to serialize to the buffer sinkfn(sa); return 0; // no space was used in the buffer } else { // serialize to the buffer const size_t sz = to_chars(buf, a); // dump the buffer to the sink if C4_LIKELY(sz <= buf.len) { // NOTE: don't do this: //sinkfn(buf.first(sz)); // ... but do this instead: sinkfn({buf.str, sz}); // ... this is needed because Release builds for armv5 and // armv6 were failing for the first call, with the wrong // buffer being passed into the function (!) } return sz; } } /** Dump a serializable object to the (dynamically dispatched) * sink. Before dumping, the object may be serialized to a string if * @ref c4::dump_directly is a false type (the default if * dump_directly does not have a specialization). Otherwise the object * is considered a string object is dumped directly, without any * intermediate serialization. * * @return the number of bytes needed to serialize the string-type * object, which may be 0 when there is no serialization * * @note the argument is considered a value when @ref * c4::dump_directly is a false type, which is the default. To enable * the argument to be treated as a string type, which is dumped * directly to the sink without intermediate serialization, define * @ref c4::dump_directly to a true type. * * @warning the string passed to the sink may have zero length. If the * user sink uses memcpy(), the call to memcpy() should be defended * with a check for zero length (calling memcpy with zero length is * undefined behavior). * * @see @ref c4::dump_directly */ template size_t dump(SinkFn &&sinkfn, substr buf, Arg const& a) { if constexpr (dump_directly::value) { C4_UNUSED(buf); csubstr sa = to_csubstr(a); C4_ASSERT(!buf.overlaps(sa)); // dump directly, no need to serialize to the buffer std::forward(sinkfn)(sa); return 0; // no space was used in the buffer } else { // serialize to the buffer const size_t sz = to_chars(buf, a); // dump the buffer to the sink if C4_LIKELY(sz <= buf.len) { // NOTE: don't do this: //std::forward(sinkfn)(buf.first(sz)); // ... but do this instead: std::forward(sinkfn)({buf.str, sz}); // ... this is needed because Release builds for armv5 and // armv6 were failing for the first call, with the wrong // buffer being passed into the function (!) } return sz; } } #else // C4_CPP < 17 template inline auto dump(substr buf, Arg const& a) -> typename std::enable_if::value, size_t>::type { C4_UNUSED(buf); csubstr sa = to_csubstr(a); C4_ASSERT(!buf.overlaps(sa)); // dump directly, no need to serialize to the buffer sinkfn(sa); return 0; // no space was used in the buffer } template inline auto dump(SinkFn &&sinkfn, substr buf, Arg const& a) -> typename std::enable_if::value, size_t>::type { C4_UNUSED(buf); csubstr sa = to_csubstr(a); C4_ASSERT(!buf.overlaps(sa)); // dump directly, no need to serialize to the buffer std::forward(sinkfn)(sa); return 0; // no space was used in the buffer } template inline auto dump(substr buf, Arg const& a) -> typename std::enable_if::value, size_t>::type { // serialize to the buffer const size_t sz = to_chars(buf, a); // dump the buffer to the sink if C4_LIKELY(sz <= buf.len) { // NOTE: don't do this: //sinkfn(buf.first(sz)); // ... but do this instead: sinkfn({buf.str, sz}); // ... this is needed because Release builds for armv5 and // armv6 were failing for the first call, with the wrong // buffer being passed into the function (!) } return sz; } template inline auto dump(SinkFn &&sinkfn, substr buf, Arg const& a) -> typename std::enable_if::value, size_t>::type { // serialize to the buffer const size_t sz = to_chars(buf, a); // dump the buffer to the sink if C4_LIKELY(sz <= buf.len) { // NOTE: don't do this: //std::forward(sinkfn)(buf.first(sz)); // ... but do this instead: std::forward(sinkfn)({buf.str, sz}); // ... this is needed because Release builds for armv5 and // armv6 were failing for the first call, with the wrong // buffer being passed into the function (!) } return sz; } #endif // C4_CPP < 17 /** An opaque type used by resumeable dump functions like @ref * c4::cat_dump_resume(), @ref c4::catsep_dump_resume() or @ref * c4::format_dump_resume(). */ struct DumpResults { enum : size_t { noarg = (size_t)-1 }; size_t bufsize = 0; size_t lastok = noarg; bool success_until(size_t expected) const { return lastok == noarg ? false : lastok >= expected; } bool write_arg(size_t arg) const { return lastok == noarg || arg > lastok; } size_t argfail() const { return lastok + 1; } }; /** @} */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @defgroup cat_dump Dump several arguments to a sink, * concatenated. This is the analog to @ref c4::cat(), with the * significant difference that each argument is immediately sent to * the sink (resulting in multiple calls to the sink function, once * per argument), whereas equivalent usage of c4::cat() would first * serialize all the arguments to the buffer, and then call the sink * once at the end. As a consequence, the size needed for the buffer * is only the maximum of the size needed for the arguments, whereas * with c4::cat(), the size needed for the buffer would be the sum of * the size needed for the arguments. When the size of dump * * @{ */ /// @cond dev // terminates the variadic recursion template size_t cat_dump(SinkFn &&, substr) // NOLINT { return 0; } // terminates the variadic recursion template size_t cat_dump(substr) // NOLINT { return 0; } /// @endcond /** Dump several arguments to the (dynamically dispatched) sink * function, as if through c4::cat(). For each argument, @ref dump() * is called with the buffer and sink. If any of the arguments is too * large for the buffer, no subsequent argument is sent to the sink, * (but all the arguments are still processed to compute the size * required for the buffer). This function can be safely called with an * empty buffer. * * @return the size required for the buffer, which is the maximum size * across all arguments * * @note subsequent calls with the same set of arguments will dump * again the first successful arguments. If each argument must only be * sent once to the sink (for example with printf-like behavior), use * instead @ref cat_dump_resume(). */ template size_t cat_dump(SinkFn &&sinkfn, substr buf, Arg const& a, Args const& ...more) { const size_t size_for_a = dump(std::forward(sinkfn), buf, a); if C4_UNLIKELY(size_for_a > buf.len) buf.len = 0; // ensure no more calls to the sink const size_t size_for_more = cat_dump(std::forward(sinkfn), buf, more...); return size_for_more > size_for_a ? size_for_more : size_for_a; } /** Dump several arguments to the (statically dispatched) sink * function, as if through c4::cat(). For each argument, @ref dump() * is called with the buffer and sink. If any of the arguments is too * large for the buffer, no subsequent argument is sent to the sink, * (but all the arguments are still processed to compute the size * required for the buffer). This function can be safely called with an * empty buffer. * * @return the size required for the buffer, which is the maximum size * across all arguments * * @note subsequent calls with the same set of arguments will dump * again the first successful arguments. If each argument must only be * sent once to the sink (for example with printf-like behavior), use * instead @ref cat_dump_resume(). */ template size_t cat_dump(substr buf, Arg const& a, Args const& ...more) { const size_t size_for_a = dump(buf, a); if C4_UNLIKELY(size_for_a > buf.len) buf.len = 0; // ensure no more calls to the sink const size_t size_for_more = cat_dump(buf, more...); return size_for_more > size_for_a ? size_for_more : size_for_a; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /// @cond dev namespace detail { // terminates the variadic recursion template C4_ALWAYS_INLINE DumpResults cat_dump_resume(size_t, DumpResults results, substr) { return results; } // terminates the variadic recursion template C4_ALWAYS_INLINE DumpResults cat_dump_resume(size_t, SinkFn &&, DumpResults results, substr) // NOLINT { return results; } template DumpResults cat_dump_resume(size_t currarg, DumpResults results, substr buf, Arg const& C4_RESTRICT a, Args const& ...more) { if C4_LIKELY(results.write_arg(currarg)) { size_t sz = dump(buf, a); // yield to the specialized function if(currarg == results.lastok + 1 && sz <= buf.len) results.lastok = currarg; results.bufsize = sz > results.bufsize ? sz : results.bufsize; } return detail::cat_dump_resume(currarg + 1u, results, buf, more...); } template DumpResults cat_dump_resume(size_t currarg, SinkFn &&sinkfn, DumpResults results, substr buf, Arg const& C4_RESTRICT a, Args const& ...more) { if C4_LIKELY(results.write_arg(currarg)) { size_t sz = dump(std::forward(sinkfn), buf, a); // yield to the specialized function if(currarg == results.lastok + 1 && sz <= buf.len) results.lastok = currarg; results.bufsize = sz > results.bufsize ? sz : results.bufsize; } return detail::cat_dump_resume(currarg + 1u, std::forward(sinkfn), results, buf, more...); } } // namespace detail /// @endcond template C4_ALWAYS_INLINE DumpResults cat_dump_resume(substr buf, Arg const& C4_RESTRICT a, Args const& ...more) { return detail::cat_dump_resume(0u, DumpResults{}, buf, a, more...); } template C4_ALWAYS_INLINE DumpResults cat_dump_resume(SinkFn &&sinkfn, substr buf, Arg const& C4_RESTRICT a, Args const& ...more) { return detail::cat_dump_resume(0u, std::forward(sinkfn), DumpResults{}, buf, a, more...); } template C4_ALWAYS_INLINE DumpResults cat_dump_resume(DumpResults results, substr buf, Arg const& C4_RESTRICT a, Args const& ...more) { if(results.bufsize > buf.len) return results; return detail::cat_dump_resume(0u, results, buf, a, more...); } template C4_ALWAYS_INLINE DumpResults cat_dump_resume(SinkFn &&sinkfn, DumpResults results, substr buf, Arg const& C4_RESTRICT a, Args const& ...more) { if(results.bufsize > buf.len) return results; return detail::cat_dump_resume(0u, std::forward(sinkfn), results, buf, a, more...); } /** @} */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /// @cond dev // terminate the recursion template size_t catsep_dump(SinkFn &&, substr, Sep const& C4_RESTRICT) // NOLINT { return 0; } // terminate the recursion template size_t catsep_dump(substr, Sep const& C4_RESTRICT) // NOLINT { return 0; } /// @endcond /** take the function pointer as a function argument */ template size_t catsep_dump(SinkFn &&sinkfn, substr buf, Sep const& sep, Arg const& a, Args const& ...more) { size_t sz = dump(std::forward(sinkfn), buf, a); if C4_UNLIKELY(sz > buf.len) buf.len = 0; // ensure no more calls if C4_IF_CONSTEXPR (sizeof...(more) > 0) { size_t szsep = dump(std::forward(sinkfn), buf, sep); if C4_UNLIKELY(szsep > buf.len) buf.len = 0; // ensure no more calls sz = sz > szsep ? sz : szsep; } size_t size_for_more = catsep_dump(std::forward(sinkfn), buf, sep, more...); return size_for_more > sz ? size_for_more : sz; } /** take the function pointer as a template argument */ template size_t catsep_dump(substr buf, Sep const& sep, Arg const& a, Args const& ...more) { size_t sz = dump(buf, a); if C4_UNLIKELY(sz > buf.len) buf.len = 0; // ensure no more calls if C4_IF_CONSTEXPR (sizeof...(more) > 0) { size_t szsep = dump(buf, sep); if C4_UNLIKELY(szsep > buf.len) buf.len = 0; // ensure no more calls sz = sz > szsep ? sz : szsep; } size_t size_for_more = catsep_dump(buf, sep, more...); return size_for_more > sz ? size_for_more : sz; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /// @cond dev namespace detail { template void catsep_dump_resume_(size_t currarg, DumpResults *C4_RESTRICT results, substr *buf, Arg const& a) { if C4_LIKELY(results->write_arg(currarg)) { size_t sz = dump(*buf, a); results->bufsize = sz > results->bufsize ? sz : results->bufsize; if C4_LIKELY(sz <= buf->len) results->lastok = currarg; else buf->len = 0; } } template void catsep_dump_resume_(size_t currarg, SinkFn &&sinkfn, DumpResults *C4_RESTRICT results, substr *C4_RESTRICT buf, Arg const& C4_RESTRICT a) { if C4_LIKELY(results->write_arg(currarg)) { size_t sz = dump(std::forward(sinkfn), *buf, a); results->bufsize = sz > results->bufsize ? sz : results->bufsize; if C4_LIKELY(sz <= buf->len) results->lastok = currarg; else buf->len = 0; } } template C4_ALWAYS_INLINE void catsep_dump_resume(size_t currarg, DumpResults *C4_RESTRICT results, substr *C4_RESTRICT buf, Sep const&, Arg const& a) { detail::catsep_dump_resume_(currarg, results, buf, a); } template C4_ALWAYS_INLINE void catsep_dump_resume(size_t currarg, SinkFn &&sinkfn, DumpResults *C4_RESTRICT results, substr *C4_RESTRICT buf, Sep const&, Arg const& a) { detail::catsep_dump_resume_(currarg, std::forward(sinkfn), results, buf, a); } template C4_ALWAYS_INLINE void catsep_dump_resume(size_t currarg, DumpResults *C4_RESTRICT results, substr *C4_RESTRICT buf, Sep const& sep, Arg const& a, Args const& ...more) { detail::catsep_dump_resume_(currarg , results, buf, a); detail::catsep_dump_resume_(currarg + 1u, results, buf, sep); detail::catsep_dump_resume (currarg + 2u, results, buf, sep, more...); } template C4_ALWAYS_INLINE void catsep_dump_resume(size_t currarg, SinkFn &&sinkfn, DumpResults *C4_RESTRICT results, substr *C4_RESTRICT buf, Sep const& sep, Arg const& a, Args const& ...more) { detail::catsep_dump_resume_(currarg , std::forward(sinkfn), results, buf, a); detail::catsep_dump_resume_(currarg + 1u, std::forward(sinkfn), results, buf, sep); detail::catsep_dump_resume (currarg + 2u, std::forward(sinkfn), results, buf, sep, more...); } } // namespace detail /// @endcond template C4_ALWAYS_INLINE DumpResults catsep_dump_resume(substr buf, Sep const& sep, Args const& ...args) { DumpResults results; detail::catsep_dump_resume(0u, &results, &buf, sep, args...); return results; } template C4_ALWAYS_INLINE DumpResults catsep_dump_resume(SinkFn &&sinkfn, substr buf, Sep const& sep, Args const& ...args) { DumpResults results; detail::catsep_dump_resume(0u, std::forward(sinkfn), &results, &buf, sep, args...); return results; } template C4_ALWAYS_INLINE DumpResults catsep_dump_resume(DumpResults results, substr buf, Sep const& sep, Args const& ...args) { detail::catsep_dump_resume(0u, &results, &buf, sep, args...); return results; } template C4_ALWAYS_INLINE DumpResults catsep_dump_resume(SinkFn &&sinkfn, DumpResults results, substr buf, Sep const& sep, Args const& ...args) { detail::catsep_dump_resume(0u, std::forward(sinkfn), &results, &buf, sep, args...); return results; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /// @cond dev namespace detail { // terminate the recursion C4_ALWAYS_INLINE size_t _format_dump_compute_size() { return 0u; } template C4_ALWAYS_INLINE auto _format_dump_compute_size(T const&) -> typename std::enable_if::value, size_t>::type { return 0u; // no buffer needed } template C4_ALWAYS_INLINE auto _format_dump_compute_size(T const& v) -> typename std::enable_if::value, size_t>::type { return to_chars(substr{}, v); } template size_t _format_dump_compute_size(Arg const& a, Args const& ...more) { const size_t sz = _format_dump_compute_size(a); // don't call to_chars() directly const size_t rest = _format_dump_compute_size(more...); return sz > rest ? sz : rest; } } // namespace detail // terminate the recursion template C4_ALWAYS_INLINE size_t format_dump(SinkFn &&sinkfn, substr, csubstr fmt) { // we can dump without using buf, so no need to check it std::forward(sinkfn)(fmt); return 0u; } // terminate the recursion /** take the function pointer as a template argument */ template C4_ALWAYS_INLINE size_t format_dump(substr, csubstr fmt) { // we can dump without using buf, so no need to check it sinkfn(fmt); return 0u; } /// @endcond /** take the function pointer as a function argument */ template C4_NO_INLINE size_t format_dump(SinkFn &&sinkfn, substr buf, csubstr fmt, Arg const& a, Args const& ...more) { // we can dump without using buf // but we'll only dump if the buffer is ok size_t pos = fmt.find("{}"); // @todo use _find_fmt() if C4_UNLIKELY(pos == csubstr::npos) { std::forward(sinkfn)(fmt); return 0u; } std::forward(sinkfn)(fmt.first(pos)); // we can dump without using buf fmt = fmt.sub(pos + 2); // skip {} do this before assigning to pos again pos = dump(std::forward(sinkfn), buf, a); // reuse pos to get needed_size // dump no more if the buffer was exhausted size_t size_for_more; if C4_LIKELY(pos <= buf.len) size_for_more = format_dump(std::forward(sinkfn), buf, fmt, more...); else size_for_more = detail::_format_dump_compute_size(more...); return size_for_more > pos ? size_for_more : pos; } /** take the function pointer as a template argument */ template C4_NO_INLINE size_t format_dump(substr buf, csubstr fmt, Arg const& C4_RESTRICT a, Args const& ...more) { // we can dump without using buf // but we'll only dump if the buffer is ok size_t pos = fmt.find("{}"); // @todo use _find_fmt() if C4_UNLIKELY(pos == csubstr::npos) { sinkfn(fmt); return 0u; } sinkfn(fmt.first(pos)); // we can dump without using buf fmt = fmt.sub(pos + 2); // skip {} do this before assigning to pos again pos = dump(buf, a); // reuse pos to get needed_size // dump no more if the buffer was exhausted size_t size_for_more; if C4_LIKELY(pos <= buf.len) size_for_more = format_dump(buf, fmt, more...); else size_for_more = detail::_format_dump_compute_size(more...); return size_for_more > pos ? size_for_more : pos; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /// @cond dev namespace detail { // terminate the recursion template DumpResults format_dump_resume(size_t currarg, DumpResults results, substr, csubstr fmt) { if C4_LIKELY(results.write_arg(currarg)) { // we can dump without using buf sinkfn(fmt); results.lastok = currarg; } return results; } // terminate the recursion template DumpResults format_dump_resume(size_t currarg, SinkFn &&sinkfn, DumpResults results, substr, csubstr fmt) { if C4_LIKELY(results.write_arg(currarg)) { // we can dump without using buf std::forward(sinkfn)(fmt); results.lastok = currarg; } return results; } template DumpResults format_dump_resume(size_t currarg, DumpResults results, substr buf, csubstr fmt, Arg const& a, Args const& ...more) { // we need to process the format even if we're not // going to print the first arguments because we're resuming const size_t pos = fmt.find("{}"); // @todo use _find_fmt() if C4_LIKELY(pos != csubstr::npos) { if C4_LIKELY(results.write_arg(currarg)) { sinkfn(fmt.first(pos)); results.lastok = currarg; } if C4_LIKELY(results.write_arg(currarg + 1u)) { const size_t len = dump(buf, a); results.bufsize = len > results.bufsize ? len : results.bufsize; if C4_LIKELY(len <= buf.len) { results.lastok = currarg + 1u; } else { const size_t rest = _format_dump_compute_size(more...); results.bufsize = rest > results.bufsize ? rest : results.bufsize; return results; } } } else { if C4_LIKELY(results.write_arg(currarg)) { sinkfn(fmt); results.lastok = currarg; } return results; } // NOTE: sparc64 had trouble with reassignment to fmt, and // was passing the original fmt to the recursion: //fmt = fmt.sub(pos + 2); // DONT! return detail::format_dump_resume(currarg + 2u, results, buf, fmt.sub(pos + 2), more...); } template DumpResults format_dump_resume(size_t currarg, SinkFn &&sinkfn, DumpResults results, substr buf, csubstr fmt, Arg const& a, Args const& ...more) { // we need to process the format even if we're not // going to print the first arguments because we're resuming const size_t pos = fmt.find("{}"); // @todo use _find_fmt() if C4_LIKELY(pos != csubstr::npos) { if C4_LIKELY(results.write_arg(currarg)) { std::forward(sinkfn)(fmt.first(pos)); results.lastok = currarg; } if C4_LIKELY(results.write_arg(currarg + 1u)) { const size_t len = dump(std::forward(sinkfn), buf, a); results.bufsize = len > results.bufsize ? len : results.bufsize; if C4_LIKELY(len <= buf.len) { results.lastok = currarg + 1u; } else { const size_t rest = _format_dump_compute_size(more...); results.bufsize = rest > results.bufsize ? rest : results.bufsize; return results; } } } else { if C4_LIKELY(results.write_arg(currarg)) { std::forward(sinkfn)(fmt); results.lastok = currarg; } return results; } // NOTE: sparc64 had trouble with reassignment to fmt, and // was passing the original fmt to the recursion: //fmt = fmt.sub(pos + 2); // DONT! return detail::format_dump_resume(currarg + 2u, std::forward(sinkfn), results, buf, fmt.sub(pos + 2), more...); } } // namespace detail /// @endcond template C4_ALWAYS_INLINE DumpResults format_dump_resume(substr buf, csubstr fmt, Args const& ...args) { return detail::format_dump_resume(0u, DumpResults{}, buf, fmt, args...); } template C4_ALWAYS_INLINE DumpResults format_dump_resume(SinkFn &&sinkfn, substr buf, csubstr fmt, Args const& ...args) { return detail::format_dump_resume(0u, std::forward(sinkfn), DumpResults{}, buf, fmt, args...); } template C4_ALWAYS_INLINE DumpResults format_dump_resume(DumpResults results, substr buf, csubstr fmt, Args const& ...args) { return detail::format_dump_resume(0u, results, buf, fmt, args...); } template C4_ALWAYS_INLINE DumpResults format_dump_resume(SinkFn &&sinkfn, DumpResults results, substr buf, csubstr fmt, Args const& ...args) { return detail::format_dump_resume(0u, std::forward(sinkfn), results, buf, fmt, args...); } C4_SUPPRESS_WARNING_GCC_CLANG_POP } // namespace c4 #endif /* C4_DUMP_HPP_ */ // (end ext/c4core.src/c4/dump.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/base64.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_BASE64_HPP_ #define C4_BASE64_HPP_ /** @file base64.hpp encoding/decoding for base64. * @see https://en.wikipedia.org/wiki/Base64 * @see https://www.base64encode.org/ * */ #ifndef C4_EXPORT_HPP_ //#include "c4/export.hpp" // amalgamate: remove include #error "amalgamate: c4/export.hpp must have been amalgamated before this point" #endif //#include // amalgamate: included above namespace c4 { /** @defgroup doc_base64 Base64 encoding/decoding * @see https://en.wikipedia.org/wiki/Base64 * @see https://www.base64encode.org/ * @{ */ /** check that the given buffer is a valid base64 encoding * @see https://en.wikipedia.org/wiki/Base64 */ C4CORE_EXPORT bool base64_valid(const char* encoded, size_t encoded_sz); /** base64-encode binary data. This is a plain implementation with a * focus on simplicity and small footprint, such that it runs * reasonably well in constrained platforms. On larger platforms it is * reasonably fast (reaching 3GB/s and over), but it is not the * fastest. If ultimate base64 speed in x64 platforms is your * objective, there are faster implementations available. One * recommendation is https://github.com/aklomp/base64, which uses a * larger Look-Up Table (4096B as compared with 64B in c4core), making * it between 1.5x~2x faster than c4core for larger payloads (but also * slower for small payloads), and much faster when using AVX2 or * AVX512 processing. But this speed comes at a cost in constrained * platforms: eg c4core encodes ~2.5x faster in armv4 and armv5. * * @param encoded [out] output buffer for encoded data * * @param encoded_sz [in] size of the output buffer for encoded data * * @param data [in] the input buffer with the binary data * * @param data_sz [in] size of the input buffer with the binary data * * @return the number of bytes required for the output buffer. No * writes occur beyond the end of the output buffer, so it is * safe to do a speculative call where the encoded buffer is * empty, or maybe too small. The caller should ensure that * the returned size is smaller than the size of the encoded * buffer. * * @note the result depends on endianness. If transfer between * little/big endian systems is desired, the caller should * normalize @p data before encoding. * * @see https://en.wikipedia.org/wiki/Base64 */ C4CORE_EXPORT size_t base64_encode(char *encoded, size_t encoded_sz, void const* data, size_t data_sz); /** decode the base64 encoding in the given buffer. This is a plain * implementation with a focus on simplicity and small footprint, such * that it runs reasonably well in constrained platforms. On larger * platforms it is reasonably fast, but it is not the fastest. If * ultimate base64 speed in x64 platforms is your objective, there are * faster implementations available. One recommendation is * https://github.com/aklomp/base64, which uses up to 16x larger * Look-Up Tables, making it between 1.5x~2x faster than c4core (but * also slower for small payloads), and much faster when using AVX2 or * AVX512 processing. But this x64 speed comes at a cost in * constrained platforms: eg c4core decodes ~4x faster in armv4 and * armv5. * * @param encoded [in] the encoded base64 * * @param encoded_sz [in] the size of the encoded buffer * * @param data [out] the output decoded buffer * * @param data_sz [in] the size of the output decoded buffer * * @param data_sz_required [out] the size required for the output * decoded buffer, ie, the number of bytes needed to return the * output (ie the required size for @p data). No writes occur * beyond the end of the output buffer, so it is safe to do a * speculative call where the data buffer is empty, or maybe * too small. The caller should ensure that this value * is smaller than data_sz. * * @return false if the encoding was invalid or the data size was * too small, and true otherwise. * * @note the result depends on endianness. If transfer between * little/big endian systems is desired, the caller should * normalize @p data after decoding. * * @see https://en.wikipedia.org/wiki/Base64 */ C4CORE_EXPORT bool base64_decode(char const* encoded, size_t encoded_sz, void * data, size_t data_sz, size_t *data_sz_required); /** @} */ // base64 } // namespace c4 #endif /* C4_BASE64_HPP_ */ // (end ext/c4core.src/c4/base64.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/format_base64.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_FORMAT_BASE64_HPP_ #define C4_FORMAT_BASE64_HPP_ /** @file format_base64.hpp Utilities for formatting data as base64 */ #ifndef C4_SUBSTR_HPP_ //#include "c4/substr.hpp" // amalgamate: remove include #error "amalgamate: c4/substr.hpp must have been amalgamated before this point" #endif #ifndef C4_BLOB_HPP_ //#include "c4/blob.hpp" // amalgamate: remove include #error "amalgamate: c4/blob.hpp must have been amalgamated before this point" #endif #ifndef C4_BASE64_HPP_ //#include "c4/base64.hpp" // amalgamate: remove include #error "amalgamate: c4/base64.hpp must have been amalgamated before this point" #endif namespace c4 { namespace fmt { /** @defgroup doc_base64_fmt Base64 format specifiers * * ```c++ * // given these variables: * T var = {}; * T &ref = var; * std::vector vec = ...; * substr buf = ...; * * // there are different approaches to encode/decode base64: * size_t numchars = to_chars(buf, base64(var)); // encode var as base64 * size_t numchars = to_chars(buf, base64(ref)); // same as above * size_t numchars = to_chars(buf, base64(&var, 1)); // same as above * size_t numchars = to_chars(buf, base64(vec.data(), vec.size())); // for the container, but same call form as above * size_t numchars = to_chars(buf, base64(vec)); // same effect as prev call * * // using cbase64() (the `c` prefix is for const) is equivalent * // for encoding, but quicker to compile: * size_t numchars = to_chars(buf, cbase64(var)); // encode var as base64 * size_t numchars = to_chars(buf, cbase64(ref)); // same as above * size_t numchars = to_chars(buf, cbase64(&var, 1)); // same as above * size_t numchars = to_chars(buf, cbase64(vec.data(), vec.size())); // for the container, but same call as above * size_t numchars = to_chars(buf, cbase64(vec)); // same effect as prev call * * // to decode: * csubstr buf = ...; * size_t reqbytes = 0; // number of bytes of decoded data * bool ok = from_chars(buf, base64(var)); // decode base64 to var * bool ok = from_chars(buf, base64(var, &reqbytes)); // same. reqbytes will be sizeof(var) * bool ok = from_chars(buf, base64(ref)); // same as above * bool ok = from_chars(buf, base64(ref, &reqbytes)); // same. reqbytes will be sizeof(var) * bool ok = from_chars(buf, base64(&var, 1, &reqbytes)); // same * bool ok = from_chars(buf, base64(vec.data(), vec.size(), &reqbytes)); // for the container, but same call as above * bool ok = from_chars(buf, base64(vec, &reqbytes)); // same effect as prev call * ``` * @ingroup doc_format_specifiers * @ingroup doc_base64 * @{ */ /** @cond dev */ namespace detail { template struct sfinae_true : std::true_type{}; template static auto test_resize(int) -> sfinae_true().resize(std::declval()))>; template static auto test_resize(int64_t) -> std::false_type; /// a traits class to report when a type as a member method named resize /// @see https://stackoverflow.com/a/9154394 template struct has_resize : decltype(detail::test_resize::type>::type>::type, Arg>(0)){}; template struct base64_wrapper_ { blob_ data; size_t *required_size; base64_wrapper_(blob_ blob, size_t *len_=nullptr) noexcept : data(blob) , required_size(len_) {} }; template struct base64_container_wrapper_ { using value_type = typename Container::value_type; Container *container; size_t *required_size; base64_container_wrapper_(Container *c, size_t *len_=nullptr) noexcept : container(c) , required_size(len_) {} blob_ data() const noexcept { size_t sz = container->size(); CharOrConstChar *first = sz ? reinterpret_cast(&(*container)[0]) : nullptr; // NOLINT return blob_(first, sizeof(value_type) * sz); } }; } // namespace detail /** @endcond */ /** a tag type to mark a payload to be encoded as base64 */ using const_base64_wrapper = detail::base64_wrapper_; /** a tag type to mark a payload to be decoded as base64 */ using base64_wrapper = detail::base64_wrapper_; /** a tag type to mark a payload as base64-encoded */ template using const_base64_container_wrapper = detail::base64_container_wrapper_; /** a tag type to mark a payload to be encoded as base64 */ template using base64_container_wrapper = detail::base64_container_wrapper_; /** a tag function to mark a csubstr payload to be encoded in base64 format */ C4_ALWAYS_INLINE const_base64_wrapper cbase64(csubstr s, size_t *reqsize=nullptr) { return const_base64_wrapper(cblob(s.str, s.len), reqsize); } /** a tag function to mark a csubstr payload to be encoded in base64 format */ C4_ALWAYS_INLINE const_base64_wrapper base64(csubstr s, size_t *reqsize=nullptr) { return const_base64_wrapper(cblob(s.str, s.len), reqsize); } /** a tag function to mark a variable to be decoded from base64 */ C4_ALWAYS_INLINE base64_wrapper base64(substr s, size_t *reqsize=nullptr) { return base64_wrapper(blob(s.str, s.len), reqsize); } /** a tag function to mark a payload to be encoded in base64 format */ template C4_ALWAYS_INLINE const_base64_wrapper cbase64(T const* arg, size_t sz, size_t *reqsize=nullptr) // NOLINT { return const_base64_wrapper(cblob(arg, sz), reqsize); } /** a tag function to mark a payload to be encoded in base64 format */ template C4_ALWAYS_INLINE auto base64(T * arg, size_t sz, size_t *reqsize=nullptr) // NOLINT -> typename std::conditional::type>::type>::value, const_base64_wrapper, base64_wrapper>::type { using U = typename std::remove_reference::type>::type; using ret_type = typename std::conditional::value, const_base64_wrapper, base64_wrapper>::type; using blob_type = typename std::conditional::value, cblob, blob>::type; return ret_type(blob_type(arg, sz), reqsize); } /** a tag function to mark a payload to be encoded in base64 format */ template C4_ALWAYS_INLINE auto cbase64(T const& arg, size_t *reqsize=nullptr) // NOLINT -> typename std::enable_if< ! detail::has_resize::value, const_base64_wrapper>::type { return const_base64_wrapper(cblob(arg), reqsize); } /** a tag function to mark a payload to be encoded or decoded in base64 format */ template C4_ALWAYS_INLINE auto base64(T & arg, size_t *reqsize=nullptr) // NOLINT -> typename std::enable_if< ! detail::has_resize::value, typename std::conditional::type>::type>::value, const_base64_wrapper, base64_wrapper>::type>::type { using U = typename std::remove_reference::type>::type; using ret_type = typename std::conditional::value, const_base64_wrapper, base64_wrapper>::type; using blob_type = typename std::conditional::value, cblob, blob>::type; return ret_type(blob_type(arg), reqsize); } /** a tag function to mark a container (payload with a .resize() * method) to be encoded in base64 format. */ template C4_ALWAYS_INLINE auto cbase64(T const& arg, size_t *reqsize=nullptr) // NOLINT -> typename std::enable_if::value, const_base64_container_wrapper>::type { return const_base64_container_wrapper(&arg, reqsize); } /** a tag function to mark a container (payload with a .resize() * method) to be encoded or decoded in base64 format. Subsequently * when decoding, from_chars() will resize the container to fit the * decoded data. */ template C4_ALWAYS_INLINE auto base64(T & arg, size_t *reqsize=nullptr) // NOLINT -> typename std::enable_if::value, typename std::conditional::type>::type>::value, const_base64_container_wrapper, base64_container_wrapper>::type>::type { using ret_type = typename std::conditional::type>::type>::value, const_base64_container_wrapper, base64_container_wrapper>::type; return ret_type(&arg, reqsize); } /** @} */ // base64_fmt } // namespace fmt //----------------------------------------------------------------------------- /** @addtogroup doc_base64 * @{ */ /** (1) read a variable in base64 format * @ingroup doc_from_chars */ inline bool from_chars(csubstr buf, fmt::base64_wrapper const& b) { size_t reqsize = 0; bool ok = base64_decode(buf.str, buf.len, b.data.buf, b.data.len, &reqsize); if(b.required_size) *b.required_size = reqsize; return ok; } /** (2) read a variable in base64 format * @ingroup doc_from_chars */ inline bool from_chars(csubstr buf, fmt::base64_wrapper *b) { return from_chars(buf, *b); } /** write a variable or buffer in base64 format * @ingroup doc_to_chars */ template inline size_t to_chars(substr buf, fmt::detail::base64_wrapper_ const& b) { size_t reqsize = base64_encode(buf.str, buf.len, b.data.buf, b.data.len); if(b.required_size) *b.required_size = reqsize; return reqsize; } /** write a container in base64 format * @ingroup doc_to_chars */ template size_t to_chars(substr buf, fmt::detail::base64_container_wrapper_ const& b) { cblob data = b.data(); size_t reqsize = base64_encode(buf.str, buf.len, data.buf, data.len); if(b.required_size) *b.required_size = reqsize; return reqsize; } /** read a container in base64 format, resizing it as needed to * accomodate the result * @ingroup doc_from_chars */ template bool from_chars(csubstr buf, fmt::base64_container_wrapper const& b) { enum : size_t { elm_sz = sizeof(typename fmt::base64_container_wrapper::value_type) }; // NOLINT blob data = b.data(); size_t required_size = 0; bool ok = base64_decode(buf.str, buf.len, data.buf, data.len, &required_size); if(b.required_size) *b.required_size = required_size; if(!required_size) return ok; else if(!ok && ((required_size < data.len) || (required_size % elm_sz))) return false; size_t num_elms = required_size / elm_sz; b.container->resize(num_elms); if(required_size > data.len) { data = b.data(); ok = base64_decode(buf.str, buf.len, data.buf, data.len, &required_size); if(b.required_size) *b.required_size = required_size; } return ok; } /** read a container in base64 format, resizing it as needed to * accomodate the result * @ingroup doc_from_chars */ template bool from_chars(csubstr buf, fmt::base64_container_wrapper const* b) { return from_chars(buf, *b); } /** @} */ // base64 } // namespace c4 #endif /* C4_FORMAT_BASE64_HPP_ */ // (end ext/c4core.src/c4/format_base64.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/std/span.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_STD_SPAN_HPP_ #define C4_STD_SPAN_HPP_ /** @file span.hpp */ #ifndef C4CORE_SINGLE_HEADER #ifndef C4_LANGUAGE_HPP_ //#include "c4/language.hpp" // amalgamate: remove include #error "amalgamate: c4/language.hpp must have been amalgamated before this point" #endif /* C4_LANGUAGE_HPP_ */ #endif #if (C4_CPP >= 20) || defined(__DOXYGEN__) #ifndef C4CORE_SINGLE_HEADER #ifndef C4_SUBSTR_HPP_ //#include "c4/substr.hpp" // amalgamate: remove include #error "amalgamate: c4/substr.hpp must have been amalgamated before this point" #endif /* C4_SUBSTR_HPP_ */ #endif //#include // amalgamate: included above namespace c4 { template struct is_string; template struct is_writeable_string; // mark std::span as a string type template<> struct is_string> : public std::true_type {}; template<> struct is_string> : public std::true_type {}; // mark std::span as a string type template<> struct is_string> : public std::true_type {}; template<> struct is_string> : public std::true_type {}; template<> struct is_writeable_string> : public std::true_type {}; template<> struct is_writeable_string> : public std::true_type {}; //----------------------------------------------------------------------------- /** create a csubstr from an existing std::span */ C4_ALWAYS_INLINE c4::csubstr to_csubstr(std::span s) noexcept { return c4::csubstr(s.data(), s.size()); } /** create a csubstr from an existing std::span */ C4_ALWAYS_INLINE c4::csubstr to_csubstr(std::span s) noexcept { return c4::csubstr(s.data(), s.size()); } /** create a substr from an existing std::span */ C4_ALWAYS_INLINE c4::substr to_substr(std::span s) noexcept { return c4::substr(s.data(), s.size()); } //----------------------------------------------------------------------------- C4_ALWAYS_INLINE bool operator== (c4::csubstr ss, std::span s) { return ss.compare(s.data(), s.size()) == 0; } C4_ALWAYS_INLINE bool operator!= (c4::csubstr ss, std::span s) { return ss.compare(s.data(), s.size()) != 0; } C4_ALWAYS_INLINE bool operator>= (c4::csubstr ss, std::span s) { return ss.compare(s.data(), s.size()) >= 0; } C4_ALWAYS_INLINE bool operator> (c4::csubstr ss, std::span s) { return ss.compare(s.data(), s.size()) > 0; } C4_ALWAYS_INLINE bool operator<= (c4::csubstr ss, std::span s) { return ss.compare(s.data(), s.size()) <= 0; } C4_ALWAYS_INLINE bool operator< (c4::csubstr ss, std::span s) { return ss.compare(s.data(), s.size()) < 0; } C4_ALWAYS_INLINE bool operator== (std::span s, c4::csubstr ss) { return ss.compare(s.data(), s.size()) == 0; } C4_ALWAYS_INLINE bool operator!= (std::span s, c4::csubstr ss) { return ss.compare(s.data(), s.size()) != 0; } C4_ALWAYS_INLINE bool operator<= (std::span s, c4::csubstr ss) { return ss.compare(s.data(), s.size()) >= 0; } C4_ALWAYS_INLINE bool operator< (std::span s, c4::csubstr ss) { return ss.compare(s.data(), s.size()) > 0; } C4_ALWAYS_INLINE bool operator>= (std::span s, c4::csubstr ss) { return ss.compare(s.data(), s.size()) <= 0; } C4_ALWAYS_INLINE bool operator> (std::span s, c4::csubstr ss) { return ss.compare(s.data(), s.size()) < 0; } C4_ALWAYS_INLINE bool operator== (c4::csubstr ss, std::span s) { return ss.compare(s.data(), s.size()) == 0; } C4_ALWAYS_INLINE bool operator!= (c4::csubstr ss, std::span s) { return ss.compare(s.data(), s.size()) != 0; } C4_ALWAYS_INLINE bool operator>= (c4::csubstr ss, std::span s) { return ss.compare(s.data(), s.size()) >= 0; } C4_ALWAYS_INLINE bool operator> (c4::csubstr ss, std::span s) { return ss.compare(s.data(), s.size()) > 0; } C4_ALWAYS_INLINE bool operator<= (c4::csubstr ss, std::span s) { return ss.compare(s.data(), s.size()) <= 0; } C4_ALWAYS_INLINE bool operator< (c4::csubstr ss, std::span s) { return ss.compare(s.data(), s.size()) < 0; } C4_ALWAYS_INLINE bool operator== (std::span s, c4::csubstr ss) { return ss.compare(s.data(), s.size()) == 0; } C4_ALWAYS_INLINE bool operator!= (std::span s, c4::csubstr ss) { return ss.compare(s.data(), s.size()) != 0; } C4_ALWAYS_INLINE bool operator<= (std::span s, c4::csubstr ss) { return ss.compare(s.data(), s.size()) >= 0; } C4_ALWAYS_INLINE bool operator< (std::span s, c4::csubstr ss) { return ss.compare(s.data(), s.size()) > 0; } C4_ALWAYS_INLINE bool operator>= (std::span s, c4::csubstr ss) { return ss.compare(s.data(), s.size()) <= 0; } C4_ALWAYS_INLINE bool operator> (std::span s, c4::csubstr ss) { return ss.compare(s.data(), s.size()) < 0; } //----------------------------------------------------------------------------- /** copy a std::span to a writeable substr */ C4_ALWAYS_INLINE size_t to_chars(c4::substr buf, std::span s) { size_t sz = s.size(); size_t len = buf.len < sz ? buf.len : sz; buf.copy_from(csubstr(s.data(), len)); // copy only available chars return sz; // return the number of needed chars } /** copy a std::span to a writeable substr */ inline size_t to_chars(c4::substr buf, std::span s) { size_t sz = s.size(); size_t len = buf.len < sz ? buf.len : sz; buf.copy_from(csubstr(s.data(), len)); // copy only available chars return sz; // return the number of needed chars } /** copy a csubstr to an existing std::span */ inline bool from_chars(c4::csubstr buf, std::span * s) { if(buf.len <= s->size()) { substr(s->data(), buf.len).copy_from(buf); *s = s->first(buf.len); return true; } return false; } } // namespace c4 #endif // SPAN_AVAILABLE #endif // C4_STD_SPAN_HPP_ // (end ext/c4core.src/c4/std/span.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/std/string.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_STD_STRING_HPP_ #define C4_STD_STRING_HPP_ /** @file string.hpp */ #ifndef C4CORE_SINGLE_HEADER #ifndef C4_SUBSTR_HPP_ //#include "c4/substr.hpp" // amalgamate: remove include #error "amalgamate: c4/substr.hpp must have been amalgamated before this point" #endif /* C4_SUBSTR_HPP_ */ #endif #include namespace c4 { // mark std::string as a string type template struct is_string; template<> struct is_string : public std::true_type {}; template<> struct is_string : public std::true_type {}; // mark std::string as a writeable string type template struct is_writeable_string; template<> struct is_writeable_string : public std::true_type {}; //----------------------------------------------------------------------------- /** get a writeable view to an existing std::string. * When the string is empty, the returned view will be pointing * at the character with value '\0', but the size will be zero. * @see https://en.cppreference.com/w/cpp/string/basic_string/operator_at */ C4_ALWAYS_INLINE c4::substr to_substr(std::string &s) noexcept { #if C4_CPP < 11 #error this function requires c++11 #endif // since c++11 it is legal to call s[s.size()]. return c4::substr(&s[0], s.size()); // NOLINT } /** get a readonly view to an existing std::string. * When the string is empty, the returned view will be pointing * at the character with value '\0', but the size will be zero. * @see https://en.cppreference.com/w/cpp/string/basic_string/operator_at */ C4_ALWAYS_INLINE c4::csubstr to_csubstr(std::string const& s) noexcept { #if C4_CPP < 11 #error this function requires c++11 #endif // since c++11 it is legal to call s[s.size()]. return c4::csubstr(&s[0], s.size()); // NOLINT } //----------------------------------------------------------------------------- C4_ALWAYS_INLINE bool operator== (c4::csubstr ss, std::string const& s) { return ss.compare(to_csubstr(s)) == 0; } C4_ALWAYS_INLINE bool operator!= (c4::csubstr ss, std::string const& s) { return ss.compare(to_csubstr(s)) != 0; } C4_ALWAYS_INLINE bool operator>= (c4::csubstr ss, std::string const& s) { return ss.compare(to_csubstr(s)) >= 0; } C4_ALWAYS_INLINE bool operator> (c4::csubstr ss, std::string const& s) { return ss.compare(to_csubstr(s)) > 0; } C4_ALWAYS_INLINE bool operator<= (c4::csubstr ss, std::string const& s) { return ss.compare(to_csubstr(s)) <= 0; } C4_ALWAYS_INLINE bool operator< (c4::csubstr ss, std::string const& s) { return ss.compare(to_csubstr(s)) < 0; } C4_ALWAYS_INLINE bool operator== (std::string const& s, c4::csubstr ss) { return ss.compare(to_csubstr(s)) == 0; } C4_ALWAYS_INLINE bool operator!= (std::string const& s, c4::csubstr ss) { return ss.compare(to_csubstr(s)) != 0; } C4_ALWAYS_INLINE bool operator>= (std::string const& s, c4::csubstr ss) { return ss.compare(to_csubstr(s)) <= 0; } C4_ALWAYS_INLINE bool operator> (std::string const& s, c4::csubstr ss) { return ss.compare(to_csubstr(s)) < 0; } C4_ALWAYS_INLINE bool operator<= (std::string const& s, c4::csubstr ss) { return ss.compare(to_csubstr(s)) >= 0; } C4_ALWAYS_INLINE bool operator< (std::string const& s, c4::csubstr ss) { return ss.compare(to_csubstr(s)) > 0; } //----------------------------------------------------------------------------- /** copy a std::string to a writeable substr */ inline size_t to_chars(c4::substr buf, std::string const& s) { size_t sz = s.size(); size_t len = buf.len < sz ? buf.len : sz; buf.copy_from(csubstr(s.data(), len)); // copy only available chars return sz; // return the number of needed chars } /** copy a csubstr to an existing std::string */ inline bool from_chars(c4::csubstr buf, std::string * s) { s->resize(buf.len); substr(&(*s)[0], buf.len).copy_from(buf); // NOLINT return true; } } // namespace c4 #endif // C4_STD_STRING_HPP_ // (end ext/c4core.src/c4/std/string.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/std/string_view.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_STD_STRING_VIEW_HPP_ #define C4_STD_STRING_VIEW_HPP_ /** @file string_view.hpp */ #ifndef C4CORE_SINGLE_HEADER #ifndef C4_LANGUAGE_HPP_ //#include "c4/language.hpp" // amalgamate: remove include #error "amalgamate: c4/language.hpp must have been amalgamated before this point" #endif #endif #if (C4_CPP >= 17 && defined(__cpp_lib_string_view)) || defined(__DOXYGEN__) #ifndef C4CORE_SINGLE_HEADER #ifndef C4_SUBSTR_HPP_ //#include "c4/substr.hpp" // amalgamate: remove include #error "amalgamate: c4/substr.hpp must have been amalgamated before this point" #endif #endif //#include // amalgamate: included above namespace c4 { // mark std::string_view as a string type template struct is_string; template<> struct is_string : public std::true_type {}; template<> struct is_string : public std::true_type {}; //----------------------------------------------------------------------------- /** create a csubstr from an existing std::string_view. */ C4_ALWAYS_INLINE c4::csubstr to_csubstr(std::string_view s) noexcept { return c4::csubstr(s.data(), s.size()); } //----------------------------------------------------------------------------- C4_ALWAYS_INLINE bool operator== (c4::csubstr ss, std::string_view s) { return ss.compare(s.data(), s.size()) == 0; } C4_ALWAYS_INLINE bool operator!= (c4::csubstr ss, std::string_view s) { return ss.compare(s.data(), s.size()) != 0; } C4_ALWAYS_INLINE bool operator>= (c4::csubstr ss, std::string_view s) { return ss.compare(s.data(), s.size()) >= 0; } C4_ALWAYS_INLINE bool operator> (c4::csubstr ss, std::string_view s) { return ss.compare(s.data(), s.size()) > 0; } C4_ALWAYS_INLINE bool operator<= (c4::csubstr ss, std::string_view s) { return ss.compare(s.data(), s.size()) <= 0; } C4_ALWAYS_INLINE bool operator< (c4::csubstr ss, std::string_view s) { return ss.compare(s.data(), s.size()) < 0; } C4_ALWAYS_INLINE bool operator== (std::string_view s, c4::csubstr ss) { return ss.compare(s.data(), s.size()) == 0; } C4_ALWAYS_INLINE bool operator!= (std::string_view s, c4::csubstr ss) { return ss.compare(s.data(), s.size()) != 0; } C4_ALWAYS_INLINE bool operator<= (std::string_view s, c4::csubstr ss) { return ss.compare(s.data(), s.size()) >= 0; } C4_ALWAYS_INLINE bool operator< (std::string_view s, c4::csubstr ss) { return ss.compare(s.data(), s.size()) > 0; } C4_ALWAYS_INLINE bool operator>= (std::string_view s, c4::csubstr ss) { return ss.compare(s.data(), s.size()) <= 0; } C4_ALWAYS_INLINE bool operator> (std::string_view s, c4::csubstr ss) { return ss.compare(s.data(), s.size()) < 0; } //----------------------------------------------------------------------------- /** copy an std::string_view to a writeable substr */ inline size_t to_chars(c4::substr buf, std::string_view s) { size_t sz = s.size(); size_t len = buf.len < sz ? buf.len : sz; buf.copy_from(csubstr(s.data(), len)); // copy only available chars return sz; // return the number of needed chars } } // namespace c4 #endif // STRING_VIEW_AVAILABLE #endif // C4_STD_STRING_VIEW_HPP_ // (end ext/c4core.src/c4/std/string_view.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/std/vector.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_STD_VECTOR_HPP_ #define C4_STD_VECTOR_HPP_ /** @file vector.hpp provides conversion and comparison facilities * from/between std::vector to c4::substr and c4::csubstr. * @todo add to_span() and friends */ #ifndef C4CORE_SINGLE_HEADER #ifndef C4_SUBSTR_HPP_ //#include "c4/substr.hpp" // amalgamate: remove include #error "amalgamate: c4/substr.hpp must have been amalgamated before this point" #endif /* C4_SUBSTR_HPP_ */ #endif #if defined(__GNUC__) && (__GNUC__ >= 6) C4_SUPPRESS_WARNING_GCC_WITH_PUSH("-Wnull-dereference") #endif #include #if defined(__GNUC__) && (__GNUC__ >= 6) C4_SUPPRESS_WARNING_GCC_POP #endif namespace c4 { // mark std::string as a string type template struct is_string; template struct is_string> : public std::true_type {}; template struct is_string> : public std::true_type {}; // mark std::string as a writeable string type template struct is_writeable_string; template struct is_writeable_string> : public std::true_type {}; //----------------------------------------------------------------------------- /** get a substr (writeable string view) of an existing std::vector */ template c4::substr to_substr(std::vector &vec) { char *data = vec.empty() ? nullptr : vec.data(); // data() may or may not return a null pointer. return c4::substr(data, vec.size()); } /** get a csubstr (read-only string) view of an existing std::vector */ template c4::csubstr to_csubstr(std::vector const& vec) { const char *data = vec.empty() ? nullptr : vec.data(); // data() may or may not return a null pointer. return c4::csubstr(data, vec.size()); } //----------------------------------------------------------------------------- // comparisons between substrings and std::vector template C4_ALWAYS_INLINE bool operator!= (c4::csubstr ss, std::vector const& s) { return ss != to_csubstr(s); } template C4_ALWAYS_INLINE bool operator== (c4::csubstr ss, std::vector const& s) { return ss == to_csubstr(s); } template C4_ALWAYS_INLINE bool operator>= (c4::csubstr ss, std::vector const& s) { return ss >= to_csubstr(s); } template C4_ALWAYS_INLINE bool operator> (c4::csubstr ss, std::vector const& s) { return ss > to_csubstr(s); } template C4_ALWAYS_INLINE bool operator<= (c4::csubstr ss, std::vector const& s) { return ss <= to_csubstr(s); } template C4_ALWAYS_INLINE bool operator< (c4::csubstr ss, std::vector const& s) { return ss < to_csubstr(s); } template C4_ALWAYS_INLINE bool operator!= (std::vector const& s, c4::csubstr ss) { return ss != to_csubstr(s); } template C4_ALWAYS_INLINE bool operator== (std::vector const& s, c4::csubstr ss) { return ss == to_csubstr(s); } template C4_ALWAYS_INLINE bool operator>= (std::vector const& s, c4::csubstr ss) { return ss <= to_csubstr(s); } template C4_ALWAYS_INLINE bool operator> (std::vector const& s, c4::csubstr ss) { return ss < to_csubstr(s); } template C4_ALWAYS_INLINE bool operator<= (std::vector const& s, c4::csubstr ss) { return ss >= to_csubstr(s); } template C4_ALWAYS_INLINE bool operator< (std::vector const& s, c4::csubstr ss) { return ss > to_csubstr(s); } //----------------------------------------------------------------------------- /** copy a std::vector to a substr */ template inline size_t to_chars(c4::substr buf, std::vector const& s) { size_t sz = s.size(); size_t len = buf.len < sz ? buf.len : sz; buf.copy_from(csubstr(s.data(), len)); // copy only available chars return sz; // return the number of needed chars } /** copy a csubstr to an existing std::vector */ template inline bool from_chars(c4::csubstr buf, std::vector * s) { s->resize(buf.len); substr(s->data(), buf.len).copy_from(buf); return true; } } // namespace c4 #endif // C4_STD_VECTOR_HPP_ // (end ext/c4core.src/c4/std/vector.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/std/std.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_STD_STD_HPP_ #define C4_STD_STD_HPP_ /** @file std.hpp includes all c4-std interop files */ #ifndef C4_STD_VECTOR_HPP_ //#include "c4/std/vector.hpp" // amalgamate: remove include #error "amalgamate: c4/std/vector.hpp must have been amalgamated before this point" #endif /* C4_STD_VECTOR_HPP_ */ #ifndef C4_STD_STRING_HPP_ //#include "c4/std/string.hpp" // amalgamate: remove include #error "amalgamate: c4/std/string.hpp must have been amalgamated before this point" #endif /* C4_STD_STRING_HPP_ */ #ifndef C4_STD_SPAN_HPP_ //#include "c4/std/span.hpp" // amalgamate: remove include #error "amalgamate: c4/std/span.hpp must have been amalgamated before this point" #endif /* C4_STD_SPAN_HPP_ */ #ifndef C4_STD_STRING_VIEW_HPP_ //#include "c4/std/string_view.hpp" // amalgamate: remove include #error "amalgamate: c4/std/string_view.hpp must have been amalgamated before this point" #endif /* C4_STD_STRING_VIEW_HPP_ */ #endif // C4_STD_STD_HPP_ // (end ext/c4core.src/c4/std/std.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/export.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_EXPORT_HPP_ #define C4_YML_EXPORT_HPP_ #ifdef _WIN32 #ifdef RYML_SHARED #ifdef RYML_EXPORTS #define RYML_EXPORT __declspec(dllexport) #define RYML_EXPORT_EXTERN #else #define RYML_EXPORT __declspec(dllimport) #define RYML_EXPORT_EXTERN extern #endif #else #define RYML_EXPORT #define RYML_EXPORT_EXTERN #endif #else #define RYML_EXPORT #define RYML_EXPORT_EXTERN #endif #endif /* C4_YML_EXPORT_HPP_ */ // (end src/c4/yml/export.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/fwd.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_FWD_HPP_ #define C4_YML_FWD_HPP_ /** @file fwd.hpp forward declarations */ namespace c4 { namespace yml { struct NodeScalar; struct NodeInit; struct NodeData; struct NodeType; class NodeRef; class ConstNodeRef; class Tree; struct ReferenceResolver; template class ParseEngine; struct EventHandlerTree; using Parser = ParseEngine; } // namespace c4 } // namespace yml #endif /* C4_YML_FWD_HPP_ */ // (end src/c4/yml/fwd.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/version.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_VERSION_HPP_ #define C4_YML_VERSION_HPP_ /** @file version.hpp */ #define RYML_VERSION "0.16.0" #define RYML_VERSION_MAJOR 0 #define RYML_VERSION_MINOR 16 #define RYML_VERSION_PATCH 0 #ifndef C4_SUBSTR_HPP_ //#include // amalgamate: remove include #error "amalgamate: c4/substr.hpp must have been amalgamated before this point" #endif /* C4_SUBSTR_HPP_ */ #ifndef C4_YML_EXPORT_HPP_ //#include // amalgamate: remove include #error "amalgamate: c4/yml/export.hpp must have been amalgamated before this point" #endif /* C4_YML_EXPORT_HPP_ */ namespace c4 { namespace yml { RYML_EXPORT csubstr version(); RYML_EXPORT int version_major(); RYML_EXPORT int version_minor(); RYML_EXPORT int version_patch(); } // namespace yml } // namespace c4 #endif /* C4_YML_VERSION_HPP_ */ // (end src/c4/yml/version.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/common.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_COMMON_HPP_ #define C4_YML_COMMON_HPP_ /** @file common.hpp Common utilities and infrastructure used by ryml. */ //#include // amalgamate: included above //#include // for std::forward // amalgamate: included above #ifndef C4_SUBSTR_HPP_ //#include // amalgamate: remove include #error "amalgamate: c4/substr.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_EXPORT_HPP_ //#include // amalgamate: remove include #error "amalgamate: c4/yml/export.hpp must have been amalgamated before this point" #endif //----------------------------------------------------------------------------- #ifndef RYML_DEFAULT_TREE_CAPACITY /// default capacity for the tree when not set explicitly #define RYML_DEFAULT_TREE_CAPACITY (16) #endif #ifndef RYML_DEFAULT_TREE_ARENA_CAPACITY /// default capacity for the tree's arena when not set explicitly #define RYML_DEFAULT_TREE_ARENA_CAPACITY (0) #endif #ifndef RYML_DEFAULT_TREE_ARENA_CAPACITY_START /// default starting capacity for the tree's arena when it is first /// allocated. should be larger than @ref RYML_DEFAULT_TREE_ARENA_CAPACITY #define RYML_DEFAULT_TREE_ARENA_CAPACITY_START (256) #endif #ifndef RYML_LOCATIONS_SMALL_THRESHOLD /// threshold at which a location search will revert from linear to /// binary search. #define RYML_LOCATIONS_SMALL_THRESHOLD (30) #endif #ifndef RYML_ERRMSG_SIZE /// size for the error message buffer #define RYML_ERRMSG_SIZE (1024) #endif #ifndef RYML_LOGBUF_SIZE /// size for the buffer used to format individual values to string /// while preparing an error message. This is only used for formatting /// individual values in the message; final messages will be larger /// than this value (see @ref RYML_ERRMSG_SIZE). This is also used for /// the detailed debug log messages when RYML_DBG is defined. #define RYML_LOGBUF_SIZE (256) #endif static_assert(RYML_LOGBUF_SIZE < RYML_ERRMSG_SIZE, "invalid size"); #ifndef RYML_LOGBUF_SIZE_MAX /// size for the fallback larger log buffer. When @ref /// RYML_LOGBUF_SIZE is not large enough to convert a value to string, /// then temporary stack memory is allocated up to /// RYML_LOGBUF_SIZE_MAX. This limit is in place to prevent a stack /// overflow. If the printed value requires more than /// RYML_LOGBUF_SIZE_MAX, the value is silently skipped. #define RYML_LOGBUF_SIZE_MAX (1024) #endif //----------------------------------------------------------------------------- /** @cond dev */ #ifndef RYML_USE_ASSERT # define RYML_USE_ASSERT C4_USE_ASSERT #endif #if RYML_USE_ASSERT # define RYML_NOEXCEPT #else # define RYML_NOEXCEPT noexcept #endif #define RYML_DEPRECATED(msg) C4_DEPRECATED(msg) #ifdef RYML_WITH_LEGACY_OPERATORS # define RYML_LEGACY_OPERATOR(txt) #else # define RYML_LEGACY_OPERATOR(txt) RYML_DEPRECATED(txt ". To avoid this warning, define the symbol RYML_WITH_LEGACY_OPERATORS while compiling") #endif #define RYML_CHECK_TYPE_IS_WRAPPER_LIKE_(type) \ static_assert(!std::is_fundamental::value, \ "did you forget to use '&'? " \ "This overload is for wrapper types such as c4::fmt::base64()"); /** @endcond */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- namespace c4 { namespace yml { C4_SUPPRESS_WARNING_GCC_CLANG_WITH_PUSH("-Wold-style-cast") class Tree; #ifndef RYML_ID_TYPE /** The type of a node id in the YAML tree. In the future, the default * will likely change to int32_t, which was observed to be faster. * @see id_type */ #define RYML_ID_TYPE size_t #endif /** The type of a node id in the YAML tree; to override the default * type, define the macro @ref RYML_ID_TYPE to a suitable integer * type. */ using id_type = RYML_ID_TYPE; static_assert(std::is_integral::value, "id_type must be an integer type"); C4_SUPPRESS_WARNING_GCC_WITH_PUSH("-Wuseless-cast") enum : id_type { // NOLINT /** an index to none */ NONE = id_type(-1), // NOLINT }; C4_SUPPRESS_WARNING_GCC_CLANG_POP enum : size_t { // NOLINT /** a null string position */ npos = size_t(-1) // NOLINT }; typedef enum Encoding_ { // NOLINT NOBOM, //!< No Byte Order Mark was found UTF8, //!< UTF8 UTF16LE, //!< UTF16, Little-Endian UTF16BE, //!< UTF16, Big-Endian UTF32LE, //!< UTF32, Little-Endian UTF32BE, //!< UTF32, Big-Endian } Encoding_e; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** A lightweight truthy type, used to enable reporting the offending * node when a deserializing error happens in nested reads. It reports * the innermost node causing the error, or true (empty-initialized) * when there is no error. */ struct RYML_EXPORT ReadResult { id_type node; enum : id_type { VALID = NONE - 1 }; // NOLINT public: /** convert to boolean to signify success/error */ operator bool() const noexcept { return node == VALID; } public: /** construct as success */ C4_ALWAYS_INLINE ReadResult() noexcept : node(VALID) {} /** construct as failure on the given node id */ C4_ALWAYS_INLINE explicit ReadResult(id_type node_) noexcept : node(node_) {} /** construct as failure on the given parent_, IF node_ is NONE */ C4_ALWAYS_INLINE explicit ReadResult(id_type parent_, id_type node_) noexcept : node(node_ != NONE ? VALID : parent_) {} public: // These adapter ctors are used by rapidyaml in the functions // calling read(), and enable working both with legacy and // up-to-date user implementations of read(). See for example // Tree::deserialize(). /** adapter: will match legacy user code (`%read()` * implementations returning bool). On error, this will report * node_ as the offending node. * * This is an adapter ctor used by rapidyaml in the functions * calling `%read()`, and enables rapidyaml to work both with * legacy and up-to-date user implementations of `%read()`. See * for example @ref Tree::deserialize(). */ C4_ALWAYS_INLINE explicit ReadResult(bool ok, id_type node_) noexcept : node(ok ? VALID : node_) {} /** adapter: will match up-to-date user code (`%read()` * implementations returning @ref ReadResult). On error, this will * report the node in the original @ref ReadResult. * * This is an adapter ctor used by rapidyaml in the functions * calling `%read()`, and enables rapidyaml to work both with * legacy and up-to-date user implementations of `%read()`. See * for example @ref Tree::deserialize(). */ C4_ALWAYS_INLINE explicit ReadResult(ReadResult result, id_type) noexcept : node(result.node) {} }; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- C4_SUPPRESS_WARNING_MSVC_WITH_PUSH(4251) // csubstr needs to have dll-interface to be used by clients of Location /** holds a source or yaml file position, for example when an error is * detected; See also @ref location_format() and @ref * location_format_with_context(). * * @ingroup doc_error_handling */ struct RYML_EXPORT Location { size_t offset; ///< number of bytes from the beginning of the source buffer size_t line; ///< line size_t col; ///< column csubstr name; ///< name of the file operator bool () const noexcept { return !name.empty() || line != npos || offset != npos || col != npos; } C4_NO_INLINE Location() noexcept : offset(npos), line(npos), col(npos), name() {} C4_NO_INLINE Location( size_t l ) noexcept : offset(npos), line(l), col(npos), name() {} C4_NO_INLINE Location( size_t l, size_t c) noexcept : offset(npos), line(l), col(c ), name() {} C4_NO_INLINE Location( size_t b, size_t l, size_t c) noexcept : offset(b ), line(l), col(c ), name() {} C4_NO_INLINE Location( csubstr n, size_t l ) noexcept : offset(npos), line(l), col(npos), name(n) {} C4_NO_INLINE Location( csubstr n, size_t l, size_t c) noexcept : offset(npos), line(l), col(c ), name(n) {} C4_NO_INLINE Location( csubstr n, size_t b, size_t l, size_t c) noexcept : offset(b ), line(l), col(c ), name(n) {} C4_NO_INLINE Location(const char *n, size_t l ) noexcept : offset(npos), line(l), col(npos), name(to_csubstr(n)) {} C4_NO_INLINE Location(const char *n, size_t l, size_t c) noexcept : offset(npos), line(l), col(c ), name(to_csubstr(n)) {} C4_NO_INLINE Location(const char *n, size_t b, size_t l, size_t c) noexcept : offset(b ), line(l), col(c ), name(to_csubstr(n)) {} }; static_assert(std::is_standard_layout::value, "Location not trivial"); C4_SUPPRESS_WARNING_MSVC_POP /// @cond dev #define RYML_LOC_HERE() (::c4::yml::Location(__FILE__, static_cast(__LINE__))) /// @endcond /** Data for a basic error. * @ingroup doc_error_handling */ struct RYML_EXPORT ErrorDataBasic { Location location; ///< location where the error was detected (may be from YAML or C++ source code) ErrorDataBasic() noexcept = default; ErrorDataBasic(Location const& cpploc_) noexcept : location(cpploc_) {} }; /** Data for a parse error. * @ingroup doc_error_handling */ struct RYML_EXPORT ErrorDataParse { Location cpploc; ///< location in the C++ source file where the error was detected. Location ymlloc; ///< location in the YAML source buffer where the error was detected. ErrorDataParse() noexcept = default; ErrorDataParse(Location const& cpploc_, Location const& ymlloc_) noexcept : cpploc(cpploc_), ymlloc(ymlloc_) {} }; /** Data for a visit error. * @ingroup doc_error_handling */ struct RYML_EXPORT ErrorDataVisit { Location cpploc; ///< location in the C++ source file where the error was detected. Tree const* tree; ///< tree where the error was detected id_type node; ///< node where the error was detected ErrorDataVisit() noexcept = default; ErrorDataVisit(Location const& cpploc_, Tree const *tree_ , id_type node_) noexcept : cpploc(cpploc_), tree(tree_), node(node_) {} }; //----------------------------------------------------------------------------- /** @addtogroup doc_callbacks * * @{ */ struct Callbacks; /** set the global callbacks for the library; after a call to this * function, these callbacks will be used by newly created objects * (unless they are copying older objects with different * callbacks). If @ref RYML_NO_DEFAULT_CALLBACKS is defined, it is * mandatory to call this function prior to using any other library * facility. * * @warning This function is NOT thread-safe, because it sets global static data * */ RYML_EXPORT void set_callbacks(Callbacks const& c); /** get the global callbacks * * @warning This function is NOT thread-safe, because it reads global static data * */ RYML_EXPORT Callbacks const& get_callbacks(); /** set the global callbacks back to their defaults. * * @warning This function is NOT thread-safe, because it sets global static data * */ RYML_EXPORT void reset_callbacks(); /** the type of the function used to allocate memory; ryml will only * allocate memory through this callback. */ using pfn_allocate = void* (*)(size_t len, void* hint, void *user_data); /** the type of the function used to free memory; ryml will only free * memory through this callback. */ using pfn_free = void (*)(void* mem, size_t size, void *user_data); /** the type of the function used to report basic errors. * * @warning Must not return. When implemented by the user, this * function MUST interrupt execution (and ideally be marked with * `[[noreturn]]`). If the function returned, the caller could enter * into an infinite loop, or the program may crash. It is up to the * user to choose the interruption mechanism; typically by either * throwing an exception, or using `std::longjmp()` ([see * documentation](https://en.cppreference.com/w/cpp/utility/program/setjmp)) * or ultimately by calling `std::abort()`. */ using pfn_error_basic = void (*) (csubstr msg, ErrorDataBasic const& errdata, void *user_data); /** the type of the function used to report parse errors. * * @warning Must not return. When implemented by the user, this * function MUST interrupt execution (and ideally be marked with * `[[noreturn]]`). If the function returned, the caller could enter * into an infinite loop, or the program may crash. It is up to the * user to choose the interruption mechanism; typically by either * throwing an exception, or using `std::longjmp()` ([see * documentation](https://en.cppreference.com/w/cpp/utility/program/setjmp)) * or ultimately by calling `std::abort()`. */ using pfn_error_parse = void (*) (csubstr msg, ErrorDataParse const& errdata, void *user_data); /** the type of the function used to report visit errors. * * @warning Must not return. When implemented by the user, this * function MUST interrupt execution (and ideally be marked with * `[[noreturn]]`). If the function returned, the caller could enter * into an infinite loop, or the program may crash. It is up to the * user to choose the interruption mechanism; typically by either * throwing an exception, or using `std::longjmp()` ([see * documentation](https://en.cppreference.com/w/cpp/utility/program/setjmp)) * or ultimately by calling `std::abort()`. */ using pfn_error_visit = void (*) (csubstr msg, ErrorDataVisit const& errdata, void *user_data); /// @cond dev using pfn_error RYML_DEPRECATED("use a more specific error type: `basic`, `parse` or `visit`") = void (*) (const char* msg, size_t msg_len, Location const& cpploc, void *user_data); /// @endcond /** A c-style callbacks class to customize behavior on errors or * allocation. Can be used globally by the library and/or locally by * @ref Tree and @ref Parser objects. */ struct RYML_EXPORT Callbacks { void * m_user_data; ///< data to be forwarded in every call to a callback pfn_allocate m_allocate; ///< a pointer to an allocate handler function pfn_free m_free; ///< a pointer to a free handler function pfn_error_basic m_error_basic; ///< a pointer to a basic error handler function pfn_error_parse m_error_parse; ///< a pointer to a parse error handler function pfn_error_visit m_error_visit; ///< a pointer to a visit error handler function public: /** Construct an object with the default callbacks. If * @ref RYML_NO_DEFAULT_CALLBACKS is defined, the object will be set with null * members.*/ Callbacks() noexcept; RYML_DEPRECATED("use the default constructor, followed by the appropriate setters") Callbacks(void *user_data, pfn_allocate alloc, pfn_free free, pfn_error_basic error_basic); public: /** Set the user data. */ Callbacks& set_user_data(void* user_data); /** Set or reset the allocate callback. When the parameter is * null, m_allocate will fall back to ryml's default allocate * implementation, unless @ref RYML_NO_DEFAULT_CALLBACKS is * defined. */ Callbacks& set_allocate(pfn_allocate allocate=nullptr); /** Set or reset the free callback. When the parameter is null, * m_free will fall back to ryml's default free implementation, * unless @ref RYML_NO_DEFAULT_CALLBACKS is defined. */ Callbacks& set_free(pfn_free free=nullptr); /** Set or reset the error_basic callback. When the parameter is null, * m_error_basic will fall back to ryml's default error_basic implementation, * unless @ref RYML_NO_DEFAULT_CALLBACKS is defined. */ Callbacks& set_error_basic(pfn_error_basic error_basic=nullptr); /** Set or reset the error_parse callback. When the parameter is null, * m_error_parse will fall back to ryml's default error_parse implementation, * unless @ref RYML_NO_DEFAULT_CALLBACKS is defined. */ Callbacks& set_error_parse(pfn_error_parse error_parse=nullptr); /** Set or reset the error_visit callback. When the parameter is null, * m_error_visit will fall back to ryml's default error_visit implementation, * unless @ref RYML_NO_DEFAULT_CALLBACKS is defined. */ Callbacks& set_error_visit(pfn_error_visit error_visit=nullptr); public: bool operator!= (Callbacks const& that) const { return !operator==(that); } bool operator== (Callbacks const& that) const { return (m_user_data == that.m_user_data && m_allocate == that.m_allocate && m_free == that.m_free && m_error_basic == that.m_error_basic && m_error_parse == that.m_error_parse && m_error_visit == that.m_error_visit); } }; /** @} */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @cond dev */ C4_SUPPRESS_WARNING_PUSH C4_SUPPRESS_WARNING_GCC_CLANG("-Wdeprecated") C4_SUPPRESS_WARNING_GCC_CLANG("-Wdeprecated-declarations") C4_SUPPRESS_WARNING_MSVC(4996) // deprecated /** A tag type to select the key when building the tree, or when * (de)serializing with operator<< or operator>> */ template struct RYML_LEGACY_OPERATOR("prefer .set_key() methods in the Tree and node") Key { K &&k; // NOLINT }; /** A tag function to select the key when building the tree, or when * (de)serializing with operator<< or operator>> */ template RYML_LEGACY_OPERATOR("prefer .set_key() methods in the Tree and node") C4_ALWAYS_INLINE Key key(K && k) { return Key{std::forward(k)}; } C4_SUPPRESS_WARNING_POP /** @endcond */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /// @cond dev #define RYML_CB_ALLOC_HINT_(cb, T, num, hint) (T*) (cb).m_allocate((num) * sizeof(T), (hint), (cb).m_user_data) #define RYML_CB_ALLOC_(cb, T, num) RYML_CB_ALLOC_HINT_((cb), T, (num), nullptr) #define RYML_CB_FREE_(cb, buf, T, num) \ do { \ (cb).m_free((buf), (num) * sizeof(T), (cb).m_user_data); \ (buf) = nullptr; \ } while(false) namespace detail { template struct _charconstant_t // is there a better way to do this? : public std::conditional::value, std::integral_constant(unsignedval)>, std::integral_constant>::type {}; #define RYML_CHCONST_(signedval, unsignedval) ::c4::yml::detail::_charconstant_t::value } // namespace detail inline csubstr _c4prc(const char &C4_RESTRICT c) // pass by reference! { switch(c) { case '\n': return csubstr("\\n"); case '\t': return csubstr("\\t"); case '\0': return csubstr("\\0"); case '\r': return csubstr("\\r"); case '\f': return csubstr("\\f"); case '\b': return csubstr("\\b"); case '\v': return csubstr("\\v"); case '\a': return csubstr("\\a"); default: return csubstr(&c, 1); } } #if C4_CPP >= 17 \ || (defined(__GNUC__) && __GNUC__ >= 6) \ || (defined(_MSC_VER) && !defined(__clang__)) #define RYML_HAS_DEPRECATED_ENUMS_ #endif /// @endcond C4_SUPPRESS_WARNING_GCC_POP } // namespace yml } // namespace c4 #endif /* C4_YML_COMMON_HPP_ */ // (end src/c4/yml/common.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/error.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_ERROR_HPP_ #define C4_YML_ERROR_HPP_ /** @file error.hpp Error utilities used by ryml. */ #ifndef C4_YML_COMMON_HPP_ //#include // amalgamate: remove include #error "amalgamate: c4/yml/common.hpp must have been amalgamated before this point" #endif #ifndef C4_CHARCONV_HPP_ //#include // amalgamate: remove include #error "amalgamate: c4/charconv.hpp must have been amalgamated before this point" #endif //#include // amalgamate: included above /// @cond dev #if (defined(C4_EXCEPTIONS) && (!defined(RYML_NO_DEFAULT_CALLBACKS) && defined(RYML_DEFAULT_CALLBACK_USES_EXCEPTIONS))) || defined(__DOXYGEN__) #define RYML_WITH_EXCEPTIONS_ #endif #if defined(RYML_DBG) && !defined(NDEBUG) && !defined(C4_NO_DEBUG_BREAK) # define RYML_DEBUG_BREAK() \ do { \ if(c4::get_error_flags() & c4::ON_ERROR_DEBUGBREAK) \ { \ C4_DEBUG_BREAK(); \ } \ } while(false) #else # define RYML_DEBUG_BREAK() #endif /// @endcond #ifdef RYML_WITH_EXCEPTIONS_ #include #endif namespace c4 { namespace yml { /// @cond dev namespace detail { struct SubstrWriter_ { substr buf; size_t pos; SubstrWriter_(substr buf_, size_t pos_=0) noexcept : buf(buf_), pos(pos_) { C4_ASSERT(buf.str || !buf.len); } void append(csubstr s) RYML_NOEXCEPT { C4_ASSERT(!s.overlaps(buf)); if(s.len && pos + s.len <= buf.len) memcpy(buf.str + pos, s.str, s.len); pos += s.len; } void append(char c) noexcept { if(pos < buf.len) buf.str[pos] = c; ++pos; } void append_n(char c, size_t numtimes) noexcept { if(numtimes && pos + numtimes < buf.len) memset(buf.str + pos, c, numtimes); pos += numtimes; } size_t slack() const noexcept { return pos <= buf.len ? buf.len - pos : 0; } size_t excess() const noexcept { return pos > buf.len ? pos - buf.len : 0; } //! get the part written so far csubstr curr() const noexcept { return pos <= buf.len ? buf.first(pos) : buf; } //! get the part that is still free to write to (the remainder) substr rem() const noexcept { return pos < buf.len ? buf.sub(pos) : buf.last(0); } size_t advance(size_t more) noexcept { pos += more; return pos; } }; // truncate the result to the buffer, adding ellipsis if it // doesn't fit inline C4_NO_INLINE csubstr _maybe_add_ellipsis(substr buf, size_t len) { if C4_UNLIKELY(len > buf.len) { const size_t numdots = (buf.len > 3) ? 3 : buf.len; buf.last(numdots).fill('.'); len = buf.len; } return buf.first(len); } // std::remove_cvref appeared in c++20 template struct _remove_cvref { using type = typename std::remove_cv::type>::type; }; template struct _dump_directly : public c4::is_string::type> { }; #if C4_CPP >= 17 template using _remove_cvref_t = typename _remove_cvref::type; template using _dump_directly_v = typename _dump_directly::value; template C4_NO_INLINE csubstr _to_chars_limited(substr buf, T &&var) { if constexpr (_dump_directly::value) { (void)buf; return to_csubstr(std::forward(var)); // no need to convert to buf } else { size_t len = to_chars(buf, std::forward(var)); return _maybe_add_ellipsis(buf, len); } } #else template C4_NO_INLINE auto _to_chars_limited(substr, T &&var) -> typename std::enable_if<_dump_directly::value, csubstr>::type { return to_csubstr(std::forward(var)); // no need to convert to buf } template C4_NO_INLINE auto _to_chars_limited(substr buf, T &&var) -> typename std::enable_if< ! _dump_directly::value, csubstr>::type { size_t len = to_chars(buf, std::forward(var)); return _maybe_add_ellipsis(buf, len); } #endif // dumpfn is a function abstracting prints to terminal (or to string). template C4_NO_INLINE void _dump(DumpFn &&dumpfn, substr, csubstr fmt) { std::forward(dumpfn)(fmt); } template C4_NO_INLINE void _dump(DumpFn &&dumpfn, substr argbuf, csubstr fmt, Arg const& arg, Args const& ...more) { size_t pos = fmt.find("{}"); if(pos == csubstr::npos) return std::forward(dumpfn)(fmt); // NOLINT // LCOV_EXCL_LINE std::forward(dumpfn)(fmt.first(pos)); // NOLINT std::forward(dumpfn)(_to_chars_limited(argbuf, arg)); // NOLINT _dump(std::forward(dumpfn), argbuf, fmt.sub(pos + 2), more...); // NOLINT } template C4_NO_INLINE csubstr _mk_err_msg(substr buf, csubstr fmt, Args const& ...args) { detail::SubstrWriter_ writer(buf); auto dumpfn = [&writer](csubstr s){ writer.append(s); }; char writebuf[RYML_LOGBUF_SIZE]; _dump(dumpfn, writebuf, fmt, args...); return _maybe_add_ellipsis(buf, writer.pos); } RYML_EXPORT csubstr _get_text_region(csubstr text, size_t pos, size_t num_lines_before, size_t num_lines_after); } // namespace detail /// @endcond //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @addtogroup doc_error_handling * * @{ */ /** generic formatting of a location * * @param dumpfn function taking a csubstr and abstracting a string * concatenation operation, such as appending to a std::string or * printing to terminal. * @param loc the location to be formatted * * For example: * * ```c++ * /// to output to std::cerr: * location_format([&s](csubstr s){ * std::cerr.write(s.str, s.len); * }, loc); * * /// to build a string: * std::string msg; * location_format([&s](csubstr s){ * msg.append(s.str, s.len); * }, loc); * ``` */ template C4_NO_INLINE size_t location_format(DumpFn &&dumpfn, Location const& loc); /** Generic formatting of a location, printing the source code buffer * region around the location. * * @param dumpfn function taking a csubstr and abstracting a string * concatenation operation, such as appending to a std::string or * printing to terminal. * @param location the location * @param source_buffer the source buffer * @param call a string with a call of attention to print in the * message (see examples below) * @param num_lines_before how many source buffer lines to print * before the location line * @param num_lines_after how many source buffer lines to print * after the location line * @param first_col_highlight the first column to highlight * around the location line * @param last_col_highlight the last column to highlight * around the location line * @param maxlen the maximum number of columns to show in the error * message; source buffer lines will have at most this number * of columns shown; if the line is longer than this, the line * will be trimmed as needed at the end and/or beginning, and * only the relevant columns *around* the location are shown * * For example: * * ```c++ * std::string out; * auto dumpfn = [&out](csubstr s){ out.append(s.str, s.len); }; * format_location_with_context(dumpfn, location, source, "error"); * ``` * * will result in this string: * * ``` * file.yaml:3: col=3 (11B): error: * error: * error: ccc * error: | * error: (here) * error: * error: see region: * error: * error: aaa * error: bbb * error: ccc * error: | * error: (here) * ``` * * If an empty string is passed for the call of attention, * * ```c++ * format_location_with_context(dumpfn, location, source); * ``` * * the returned string becomes: * * ``` * file.yaml:3: col=3 (11B): ccc * | * (here) * file.yaml:3: col=3 (11B): see region: * aaa * bbb * ccc * | * (here) * ``` */ template C4_NO_INLINE void location_format_with_context(DumpFn &&dumpfn, Location const &location, csubstr source_buffer, csubstr call = "", size_t num_lines_before = 3, size_t num_lines_after = 0, size_t first_col_highlight = 0, size_t last_col_highlight = 0, size_t maxlen = 80u); //----------------------------------------------------------------------------- /** Given an error message and associated basic error data, format it fully as a basic error message. * * @param dumpfn function taking a csubstr and abstracting a string * concatenation operation, such as appending to a std::string or * printing to terminal. * @param msg the error message * @param errdata the error data * * For example: * * ```c++ * /// to output to cerr: * err_basic_format([](csubstr s){ * std::cerr.write(s.str, s.len); * }, errmsg, errdata); * * /// to build a string: * std::string msg; * error_basic_format([&msg](csubstr s){ * msg.append(s.str, s.len); * }, errmsg, errdata); * ``` */ template C4_NO_INLINE void err_basic_format(DumpFn &&dumpfn, csubstr msg, ErrorDataBasic const& errdata); /** trigger a basic error to its respective handler, with a non-formatted error message. */ C4_NORETURN RYML_EXPORT C4_NO_INLINE void err_basic(Callbacks const& callbacks, ErrorDataBasic const& errdata, const char* msg_); /** trigger a basic error to its respective handler, with a non-formatted error message. Like (1), but use the current global callbacks. */ C4_NORETURN RYML_EXPORT C4_NO_INLINE void err_basic(ErrorDataBasic const& errdata, const char* msg); /** trigger a basic error to its respective handler, with a formatted error message. */ template C4_NORETURN C4_NO_INLINE void err_basic(Callbacks const& callbacks, ErrorDataBasic const& errdata, const char *fmt, Args const& ...args) { char errbuf[RYML_ERRMSG_SIZE]; csubstr msg = detail::_mk_err_msg(errbuf, to_csubstr(fmt), args...); callbacks.m_error_basic(msg, errdata, callbacks.m_user_data); std::abort(); // the call above should not return, but force it here in case it does // LCOV_EXCL_LINE C4_UNREACHABLE_AFTER_ERR(); } /** trigger a basic error to its respective handler, with a formatted error message. Like (1), but use the current global callbacks. */ template C4_NORETURN C4_NO_INLINE void err_basic(ErrorDataBasic const& errdata, const char *fmt, Args const& ...args) { err_basic(get_callbacks(), errdata, fmt, args...); C4_UNREACHABLE_AFTER_ERR(); } /** Given an error message and associated parse error data, format it fully as a parse error message. * * @param dumpfn function taking a csubstr and abstracting a string * concatenation operation, such as appending to a std::string or * printing to terminal. * @param msg the error message * @param errdata the error data * * For example: * * ```c++ * /// to output to cerr: * /// this is what err_parse_print() does * err_parse_format([](csubstr s){ * std::cerr.write(s.str, s.len); * }, errmsg, errdata); * * /// to build a string: * std::string msg; * err_parse_format([](csubstr s){ * s.append(s.str, s.len); * }, errmsg, errdata); * ``` * * @note if the (preferably original) source buffer is kept, @ref * location_format_with_context() can be used to also an additional * rich error message showing the YAML source buffer region around * that location. */ template C4_NO_INLINE void err_parse_format(DumpFn &&dumpfn, csubstr msg, ErrorDataParse const& errdata); /** trigger a parse error to its respective handler, with a non-formatted error message */ C4_NORETURN RYML_EXPORT C4_NO_INLINE void err_parse(Callbacks const& callbacks, ErrorDataParse const& errdata, const char *msg); /** trigger a parse error to its respective handler, with a non-formatted error message. Like (1), but use the current global callbacks. */ C4_NORETURN RYML_EXPORT C4_NO_INLINE void err_parse(ErrorDataParse const& errdata, const char *msg); /** trigger a parse error to its respective handler, with a formatted error message */ template C4_NORETURN C4_NO_INLINE void err_parse(Callbacks const& callbacks, ErrorDataParse const& errdata, const char *fmt, Args const& ...args) { char errbuf[RYML_ERRMSG_SIZE]; csubstr msg = detail::_mk_err_msg(errbuf, to_csubstr(fmt), args...); if(callbacks.m_error_parse) callbacks.m_error_parse(msg, errdata, callbacks.m_user_data); // fall to basic error if there is no parse handler set, but use errdata.ymlloc instead of errdata.cpploc else if(callbacks.m_error_basic) callbacks.m_error_basic(msg, errdata.ymlloc, callbacks.m_user_data); std::abort(); // the call above should not return, so force it here in case it does // LCOV_EXCL_LINE C4_UNREACHABLE_AFTER_ERR(); } /** trigger a parse error to its respective handler, with a formatted error message. Like (1), but use the current global callbacks. */ template C4_NORETURN C4_NO_INLINE void err_parse(ErrorDataParse const& errdata, const char *fmt, Args const& ...args) { err_parse(get_callbacks(), errdata, fmt, args...); C4_UNREACHABLE_AFTER_ERR(); } /** Given an error message and associated visit error data, format it * fully as a visit error message. * * @param dumpfn function taking a csubstr and abstracting a string * concatenation operation, such as appending to a std::string or * printing to terminal. * @param msg the error message * @param errdata the error data * * For example: * * ```c++ * /// to output to cerr: * err_visit_format([](csubstr s){ * std::cerr.write(s.str, s.len); * }, errmsg, errdata); * * /// to build a string: * std::string msg; * err_visit_format([&msg](csubstr s){ * msg.append(s.str, s.len); * }, errmsg, errdata); * * @note under certain conditions, it is possible to obtain an * associated location, and subsequently use @ref * location_format_with_context() to also create a rich error message * showing the YAML source buffer region around that location. This is * possible if the (preferably original) source buffer is kept, and * the node location can be retrieved from the parser. * ``` */ template C4_NO_INLINE void err_visit_format(DumpFn &&dumpfn, csubstr msg, ErrorDataVisit const& errdata); /** trigger a visit error to its respective handler, with a non-formatted error message */ C4_NORETURN RYML_EXPORT C4_NO_INLINE void err_visit(Callbacks const& callbacks, ErrorDataVisit const& errdata, const char *msg); /** trigger a visit error to its respective handler, with a non-formatted error message. Like (1), but uses the current global callbacks. */ C4_NORETURN RYML_EXPORT C4_NO_INLINE void err_visit(ErrorDataVisit const& errdata, const char *msg); /** trigger a visit error to its respective handler, with a formatted error message */ template C4_NORETURN C4_NO_INLINE void err_visit(Callbacks const& callbacks, ErrorDataVisit const& errdata, const char *fmt, Args const& ...args) { char errbuf[RYML_ERRMSG_SIZE]; csubstr msg = detail::_mk_err_msg(errbuf, to_csubstr(fmt), args...); if(callbacks.m_error_visit) callbacks.m_error_visit(msg, errdata, callbacks.m_user_data); // fall to basic error if there is no visit handler set else if(callbacks.m_error_basic) callbacks.m_error_basic(msg, errdata.cpploc, callbacks.m_user_data); std::abort(); // the call above should not return, so force it here in case it does // LCOV_EXCL_LINE C4_UNREACHABLE_AFTER_ERR(); } /** trigger a visit error to its respective handler, with a formatted error message. Like (1), but use the current global callbacks. */ template C4_NORETURN C4_NO_INLINE void err_visit(ErrorDataVisit const& errdata, const char *fmt, Args const& ...args) { err_visit(get_callbacks(), errdata, fmt, args...); C4_UNREACHABLE_AFTER_ERR(); } //----------------------------------------------------------------------------- #if defined(RYML_WITH_EXCEPTIONS_) || defined(__DOXYGEN__) /** Exception thrown by the default basic error implementation. To * obtain the full error message, use @ref err_basic_format(), or the * helper @ref format_exc(). * * @note Available only if @ref * RYML_DEFAULT_CALLBACK_USES_EXCEPTIONS is defined, and @ref * RYML_NO_DEFAULT_CALLBACKS is NOT defined. */ struct RYML_EXPORT ExceptionBasic : public std::exception { ExceptionBasic(csubstr msg, ErrorDataBasic const& errdata_) noexcept; const char* what() const noexcept override { return msg; } ErrorDataBasic errdata_basic; ///< error data char msg[RYML_ERRMSG_SIZE]; ///< the reported error message, without location indication. }; /** Exception thrown by the default parse error implementation. To * obtain the full error message containing context, use @ref * err_parse_format(), or the helper @ref format_exc(). * * @note This exception derives from @ref ExceptionBasic and can be * catched using either type. * * @note Available only if @ref * RYML_DEFAULT_CALLBACK_USES_EXCEPTIONS is defined, and @ref * RYML_NO_DEFAULT_CALLBACKS is NOT defined. */ struct RYML_EXPORT ExceptionParse : public ExceptionBasic { ExceptionParse(csubstr msg, ErrorDataParse const& errdata_) noexcept; ErrorDataParse errdata_parse; }; /** Exception thrown by the default visit error implementation. To * obtain the full error message containing context, use @ref * err_visit_format(), or the helper @ref format_exc(). * * @note This exception derives from @ref ExceptionBasic and can be * catched using either type. * * @note Available only if @ref * RYML_DEFAULT_CALLBACK_USES_EXCEPTIONS is defined, and @ref * RYML_NO_DEFAULT_CALLBACKS is NOT defined. */ struct RYML_EXPORT ExceptionVisit : public ExceptionBasic { ExceptionVisit(csubstr msg, ErrorDataVisit const& errdata_) noexcept; ErrorDataVisit errdata_visit; }; /** Format a basic exception to an existing char container * * @note Available only if @ref * RYML_DEFAULT_CALLBACK_USES_EXCEPTIONS is defined, and @ref * RYML_NO_DEFAULT_CALLBACKS is NOT defined. */ template void format_exc(CharContainer *out, ExceptionBasic const& exc) { out->clear(); err_basic_format([out](csubstr s){ out->append(s.str, s.len); }, csubstr{exc.msg, strlen(exc.msg)}, exc.errdata_basic); } /** Format a parse exception to an existing char container * * @note Available only if @ref * RYML_DEFAULT_CALLBACK_USES_EXCEPTIONS is defined, and @ref * RYML_NO_DEFAULT_CALLBACKS is NOT defined. */ template void format_exc(CharContainer *out, ExceptionParse const& exc) { out->clear(); err_parse_format([out](csubstr s){ out->append(s.str, s.len); }, csubstr{exc.msg, strlen(exc.msg)}, exc.errdata_parse); } /** Format a visit exception to an existing char container * * @note Available only if @ref * RYML_DEFAULT_CALLBACK_USES_EXCEPTIONS is defined, and @ref * RYML_NO_DEFAULT_CALLBACKS is NOT defined. */ template void format_exc(CharContainer *out, ExceptionVisit const& exc) { out->clear(); err_visit_format([out](csubstr s){ out->append(s.str, s.len); }, csubstr{exc.msg, strlen(exc.msg)}, exc.errdata_visit); } /** Format a parse exception, and return a newly-created char * container * * @note Available only if @ref * RYML_DEFAULT_CALLBACK_USES_EXCEPTIONS is defined, and @ref * RYML_NO_DEFAULT_CALLBACKS is NOT defined. */ template CharContainer format_exc(ExceptionT const& exc) { CharContainer str; format_exc(&str, exc); return str; } #endif // RYML_WITH_EXCEPTIONS_ /** @} */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /// @cond dev #if RYML_USE_ASSERT # define RYML_ASSERT_BASIC_(cond) RYML_CHECK_BASIC_(cond) # define RYML_ASSERT_BASIC_CB_(cb, cond) RYML_CHECK_BASIC_CB_((cb), cond) # define RYML_ASSERT_BASIC_MSG_(cond, ...) RYML_CHECK_BASIC_CB_MSG_(cond, __VA_ARGS__) # define RYML_ASSERT_BASIC_MSG_CB_(cb, cond, ...) RYML_CHECK_BASIC_MSG_CB_((cb), cond, __VA_ARGS__) # define RYML_ASSERT_PARSE_(cond, ymlloc) RYML_CHECK_PARSE_(cond, (ymlloc)) # define RYML_ASSERT_PARSE_CB_(cb, cond, ymlloc) RYML_CHECK_PARSE_CB_((cb), cond, (ymlloc)) # define RYML_ASSERT_PARSE_MSG_(cond, ymlloc, ...) RYML_CHECK_PARSE_CB_MSG_(cond, (ymlloc), __VA_ARGS__) # define RYML_ASSERT_PARSE_MSG_CB_(cb, cond, ymlloc, ...) RYML_CHECK_PARSE_MSG_CB_((cb), cond, (ymlloc), __VA_ARGS__) # define RYML_ASSERT_VISIT_(cond, tree, node) RYML_CHECK_VISIT_(cond, (tree), (node)) # define RYML_ASSERT_VISIT_CB_(cb, cond, tree, node) RYML_CHECK_VISIT_CB_((cb), cond, (tree), (node)) # define RYML_ASSERT_VISIT_MSG_(cond, tree, node, ...) RYML_CHECK_VISIT_CB_MSG_(cond, (tree), (node), __VA_ARGS__) # define RYML_ASSERT_VISIT_MSG_CB_(cb, cond, tree, node, ...) RYML_CHECK_VISIT_MSG_CB_((cb), cond, (tree), (node), __VA_ARGS__) #else # define RYML_ASSERT_BASIC_(cond) # define RYML_ASSERT_BASIC_CB_(cb, cond) # define RYML_ASSERT_BASIC_MSG_(cond, ...) # define RYML_ASSERT_BASIC_MSG_CB_(cb, cond, ...) # define RYML_ASSERT_PARSE_(cond, ymlloc) # define RYML_ASSERT_PARSE_CB_(cb, cond, ymlloc) # define RYML_ASSERT_PARSE_MSG_(cond, ymlloc, ...) # define RYML_ASSERT_PARSE_MSG_CB_(cb, cond, ymlloc, ...) # define RYML_ASSERT_VISIT_(cont, tree, node) # define RYML_ASSERT_VISIT_CB_(cb, cont, tree, node) # define RYML_ASSERT_VISIT_MSG_(cont, tree, node, ...) # define RYML_ASSERT_VISIT_MSG_CB_(cb, cont, tree, node, ...) #endif #define RYML_ERR_BASIC_(...) \ do \ { \ RYML_DEBUG_BREAK(); \ ::c4::yml::err_basic((::c4::yml::ErrorDataBasic{RYML_LOC_HERE()}), __VA_ARGS__); \ C4_UNREACHABLE_AFTER_ERR(); \ } while(false) #define RYML_ERR_PARSE_(ymlloc, ...) \ do \ { \ RYML_DEBUG_BREAK(); \ ::c4::yml::err_parse((::c4::yml::ErrorDataParse{RYML_LOC_HERE(), ymlloc}), __VA_ARGS__); \ C4_UNREACHABLE_AFTER_ERR(); \ } while(false) #define RYML_ERR_VISIT_(tree, node, ...) \ do \ { \ RYML_DEBUG_BREAK(); \ ::c4::yml::err_visit((::c4::yml::ErrorDataVisit{RYML_LOC_HERE(), tree, node}), __VA_ARGS__); \ C4_UNREACHABLE_AFTER_ERR(); \ } while(false) #define RYML_ERR_BASIC_CB_(cb, ...) \ do \ { \ RYML_DEBUG_BREAK(); \ ::c4::yml::err_basic((cb), (::c4::yml::ErrorDataBasic{RYML_LOC_HERE()}), __VA_ARGS__); \ C4_UNREACHABLE_AFTER_ERR(); \ } while(false) #define RYML_ERR_PARSE_CB_(cb, ymlloc, ...) \ do \ { \ RYML_DEBUG_BREAK(); \ ::c4::yml::err_parse((cb), (::c4::yml::ErrorDataParse{RYML_LOC_HERE(), ymlloc}), __VA_ARGS__); \ C4_UNREACHABLE_AFTER_ERR(); \ } while(false) #define RYML_ERR_VISIT_CB_(cb, tree, node, ...) \ do \ { \ RYML_DEBUG_BREAK(); \ ::c4::yml::err_visit((cb), (::c4::yml::ErrorDataVisit{RYML_LOC_HERE(), tree, node}), __VA_ARGS__); \ C4_UNREACHABLE_AFTER_ERR(); \ } while(false) #ifndef RYML_SHORT_CHECK_MSG #define RYML_MAYBE_MSG_(cond) ": " #cond #define RYML_MAYBE_MSG_CB_(cond) ": " #cond ": " #else #define RYML_MAYBE_MSG_(cond) #define RYML_MAYBE_MSG_CB_(cond) ": " #endif #define RYML_CHECK_BASIC_(cond) \ do { \ if C4_UNLIKELY(!(cond)) \ { \ RYML_DEBUG_BREAK(); \ ::c4::yml::err_basic((::c4::yml::ErrorDataBasic{RYML_LOC_HERE()}), "check failed" RYML_MAYBE_MSG_(cond)); \ C4_UNREACHABLE_AFTER_ERR(); \ } \ } while(false) #define RYML_CHECK_PARSE_(cond, ymlloc) \ do { \ if C4_UNLIKELY(!(cond)) \ { \ RYML_DEBUG_BREAK(); \ ::c4::yml::err_parse((::c4::yml::ErrorDataParse{RYML_LOC_HERE(), ymlloc}), "check failed" RYML_MAYBE_MSG_(cond)); \ C4_UNREACHABLE_AFTER_ERR(); \ } \ } while(false) #define RYML_CHECK_VISIT_(cond, tree, node) \ do { \ if C4_UNLIKELY(!(cond)) \ { \ RYML_DEBUG_BREAK(); \ ::c4::yml::err_visit((::c4::yml::ErrorDataVisit{RYML_LOC_HERE(), tree, node}), "check failed" RYML_MAYBE_MSG_(cond)); \ C4_UNREACHABLE_AFTER_ERR(); \ } \ } while(false) #define RYML_CHECK_BASIC_CB_(cb, cond) \ do { \ if C4_UNLIKELY(!(cond)) \ { \ RYML_DEBUG_BREAK(); \ ::c4::yml::err_basic((cb), (::c4::yml::ErrorDataBasic{RYML_LOC_HERE()}), "check failed" RYML_MAYBE_MSG_(cond)); \ C4_UNREACHABLE_AFTER_ERR(); \ } \ } while(false) #define RYML_CHECK_PARSE_CB_(cb, cond, ymlloc) \ do { \ if C4_UNLIKELY(!(cond)) \ { \ RYML_DEBUG_BREAK(); \ ::c4::yml::err_parse((cb), (::c4::yml::ErrorDataParse{RYML_LOC_HERE(), ymlloc}), "check failed" RYML_MAYBE_MSG_(cond)); \ C4_UNREACHABLE_AFTER_ERR(); \ } \ } while(false) #define RYML_CHECK_VISIT_CB_(cb, cond, tree, node) \ do { \ if C4_UNLIKELY(!(cond)) \ { \ RYML_DEBUG_BREAK(); \ ::c4::yml::err_visit((cb), (::c4::yml::ErrorDataVisit{RYML_LOC_HERE(), tree, node}), "check failed" RYML_MAYBE_MSG_(cond)); \ C4_UNREACHABLE_AFTER_ERR(); \ } \ } while(false) #define RYML_CHECK_BASIC_CB_MSG_(cond, ...) \ do { \ if C4_UNLIKELY(!(cond)) \ { \ RYML_DEBUG_BREAK(); \ ::c4::yml::err_basic((::c4::yml::ErrorDataBasic{RYML_LOC_HERE()}), "check failed" RYML_MAYBE_MSG_CB_(cond) __VA_ARGS__); \ C4_UNREACHABLE_AFTER_ERR(); \ } \ } while(false) #define RYML_CHECK_PARSE_CB_MSG_(cond, ymlloc, ...) \ do { \ if C4_UNLIKELY(!(cond)) \ { \ RYML_DEBUG_BREAK(); \ ::c4::yml::err_parse((::c4::yml::ErrorDataParse{RYML_LOC_HERE(), ymlloc}), "check failed" RYML_MAYBE_MSG_CB_(cond) __VA_ARGS__); \ C4_UNREACHABLE_AFTER_ERR(); \ } \ } while(false) #define RYML_CHECK_VISIT_CB_MSG_(cond, tree, node, ...) \ do { \ if C4_UNLIKELY(!(cond)) \ { \ RYML_DEBUG_BREAK(); \ ::c4::yml::err_visit((::c4::yml::ErrorDataVisit{RYML_LOC_HERE(), tree, node}), "check failed" RYML_MAYBE_MSG_CB_(cond) __VA_ARGS__); \ C4_UNREACHABLE_AFTER_ERR(); \ } \ } while(false) #define RYML_CHECK_BASIC_MSG_CB_(cb, cond, ...) \ do { \ if C4_UNLIKELY(!(cond)) \ { \ RYML_DEBUG_BREAK(); \ ::c4::yml::err_basic((cb), (::c4::yml::ErrorDataBasic{RYML_LOC_HERE()}), "check failed" RYML_MAYBE_MSG_CB_(cond) __VA_ARGS__); \ C4_UNREACHABLE_AFTER_ERR(); \ } \ } while(false) #define RYML_CHECK_PARSE_MSG_CB_(cb, cond, ymlloc, ...) \ do { \ if C4_UNLIKELY(!(cond)) \ { \ RYML_DEBUG_BREAK(); \ ::c4::yml::err_parse((cb), (::c4::yml::ErrorDataParse{RYML_LOC_HERE(), ymlloc}), "check failed" RYML_MAYBE_MSG_CB_(cond) __VA_ARGS__); \ C4_UNREACHABLE_AFTER_ERR(); \ } \ } while(false) #define RYML_CHECK_VISIT_MSG_CB_(cb, cond, tree, node, ...) \ do { \ if C4_UNLIKELY(!(cond)) \ { \ RYML_DEBUG_BREAK(); \ ::c4::yml::err_visit((cb), (::c4::yml::ErrorDataVisit{RYML_LOC_HERE(), tree, node}), "check failed" RYML_MAYBE_MSG_CB_(cond) __VA_ARGS__); \ C4_UNREACHABLE_AFTER_ERR(); \ } \ } while(false) /// @endcond } // namespace yml } // namespace c4 #endif /* C4_YML_ERROR_HPP_ */ // (end src/c4/yml/error.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/error.def.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_ERROR_DEF_HPP_ #define C4_YML_ERROR_DEF_HPP_ /** @file error.def.hpp Definitions of error utilities used by ryml. */ #ifndef C4_YML_ERROR_HPP_ //#include // amalgamate: remove include #error "amalgamate: c4/yml/error.hpp must have been amalgamated before this point" #endif //#include // amalgamate: included above // NOLINTBEGIN(bugprone-use-after-move,hicpp-invalid-access-moved) namespace c4 { namespace yml { template C4_NO_INLINE size_t location_format(DumpFn &&dumpfn, Location const& loc) { if(!loc) return 0; char buf_[32]; substr buf(buf_); size_t count = 0; if(!loc.name.empty()) { std::forward(dumpfn)(loc.name); std::forward(dumpfn)(":"); count += loc.name.len + 1; } if(loc.line != npos) { csubstr val = detail::_to_chars_limited(buf, loc.line); if(loc.name.empty()) { std::forward(dumpfn)("line="); std::forward(dumpfn)(val); if(loc.col == npos) { std::forward(dumpfn)(":"); ++count; } count += val.len + 5; } else { std::forward(dumpfn)(val); std::forward(dumpfn)(":"); count += val.len + 1; } } if(loc.col != npos) { csubstr val = detail::_to_chars_limited(buf, loc.col); if(loc.line != npos || !loc.name.empty()) { std::forward(dumpfn)(" "); ++count; } std::forward(dumpfn)("col="); std::forward(dumpfn)(val); count += val.len + 4; if(loc.offset == npos) { std::forward(dumpfn)(":"); ++count; } } if(loc.offset != npos) { csubstr val = detail::_to_chars_limited(buf, loc.offset); if(loc.line != npos || loc.col != npos || !loc.name.empty()) { std::forward(dumpfn)(" "); ++count; } std::forward(dumpfn)("("); std::forward(dumpfn)(val); std::forward(dumpfn)("B):"); count += val.len + 5; } return count; } template C4_NO_INLINE void location_format_with_context(DumpFn &&dumpfn, Location const &location, csubstr source_buffer, csubstr call, size_t num_lines_before, size_t num_lines_after, size_t first_col_highlight, size_t last_col_highlight, size_t maxlen) { if(!location) return; char buf_[32]; substr buf(buf_); auto pr = [&](csubstr s){ std::forward(dumpfn)(s); }; auto prn = [&](csubstr s, size_t num_times){ for(size_t i = 0; i < num_times; ++i) std::forward(dumpfn)(s); }; csubstr line = detail::_get_text_region(source_buffer, location.offset, 0, 0); size_t target_col = location.col != npos ? location.col : (last_col_highlight > first_col_highlight ? first_col_highlight : npos); size_t first_col_to_show = 0; if(target_col != npos && target_col > maxlen) first_col_to_show = target_col - maxlen + 1; auto print_line_maybe_truncated = [&](csubstr contents){ if(contents.len <= maxlen) { if(first_col_to_show == 0) { pr(contents); } else if(first_col_to_show < contents.len) { csubstr show = contents.sub(first_col_to_show); pr("[...]"); pr(show); if(maxlen > show.len) prn(" ", maxlen - show.len + 5); pr(" (showing columns "); pr(detail::_to_chars_limited(buf, first_col_to_show)); pr("-"); pr(detail::_to_chars_limited(buf, contents.len)); pr("/"); pr(detail::_to_chars_limited(buf, contents.len)); pr(")"); } else { pr("[...]"); prn(" ", maxlen + 5); pr(" (not showing, columns="); pr(detail::_to_chars_limited(buf, contents.len)); pr(")"); } } else { if(first_col_to_show == 0) { csubstr show = contents.first(maxlen); pr(show); pr("[...] (showing columns 0-"); pr(detail::_to_chars_limited(buf, show.len)); pr("/"); pr(detail::_to_chars_limited(buf, contents.len)); pr(")"); } else if(first_col_to_show < contents.len && first_col_to_show + maxlen <= contents.len) { csubstr show = contents.sub(first_col_to_show, maxlen); pr("[...]"); pr(show); pr("[...] (showing columns "); pr(detail::_to_chars_limited(buf, first_col_to_show)); pr("-"); pr(detail::_to_chars_limited(buf, first_col_to_show + maxlen)); pr("/"); pr(detail::_to_chars_limited(buf, contents.len)); pr(")"); } else if(first_col_to_show < contents.len) { csubstr show = contents.sub(first_col_to_show); pr("[...]"); pr(show); if(maxlen > show.len) prn(" ", maxlen - show.len + 5); pr(" (showing columns "); pr(detail::_to_chars_limited(buf, first_col_to_show)); pr("-"); pr(detail::_to_chars_limited(buf, contents.len)); pr("/"); pr(detail::_to_chars_limited(buf, contents.len)); pr(")"); } else { pr("[...]"); prn(" ", maxlen + 5); pr(" (not showing, columns="); pr(detail::_to_chars_limited(buf, contents.len)); pr(")"); } } }; // print the location, and compute how many cols it took size_t locsize = location_format(pr, location); // print line if(locsize) { pr(" "); //++locsize; } auto print_call = [&](csubstr after){ pr(call); pr(":"); if(after.len) pr(after); }; size_t jump; if(call.empty()) { print_line_maybe_truncated(line); pr("\n"); jump = locsize + location.col - first_col_to_show; } else { print_call("\n"); print_call("\n"); print_call(" "); pr(" "); print_line_maybe_truncated(line); pr("\n"); jump = call.len + 2; } // when skipping to the first col, add 5 to adjust for the [...] // leading the line as shown const size_t first_col_jump = first_col_to_show == 0 ? 0 : 5; // print a cursor pointing at the column on the previous printed line auto print_cursor = [&](size_t nocall_jump){ if(location.offset == npos) return; if(call.empty()) { if(nocall_jump != npos) { prn(" ", nocall_jump + first_col_jump); pr("|\n"); prn(" ", nocall_jump + first_col_jump); pr("(here)\n"); } } else if(location.col != npos) { print_call(" "); pr(" "); prn(" ", location.col - first_col_to_show + first_col_jump); pr("|\n"); print_call(" "); pr(" "); prn(" ", location.col - first_col_to_show + first_col_jump); pr("(here)\n"); } }; // maybe highlighted zone size_t firstcol = first_col_highlight < line.len ? first_col_highlight : line.len; size_t lastcol = last_col_highlight < line.len ? last_col_highlight : line.len; firstcol = firstcol < maxlen ? firstcol : maxlen; lastcol = lastcol < maxlen ? lastcol : maxlen; if(firstcol < lastcol) { if(!call.empty()) { print_call(" "); pr(" "); } else { for(size_t i = 0; i < locsize + firstcol; ++i) pr(" "); } for(size_t i = locsize + firstcol; i < locsize + lastcol; ++i) pr("~"); pr(" (cols "); pr(detail::_to_chars_limited(buf, firstcol)); pr("-"); pr(detail::_to_chars_limited(buf, lastcol)); pr("/"); pr(detail::_to_chars_limited(buf, line.len)); pr(")\n"); } if(location.col != npos) { print_cursor(jump); } // maybe print the region if(num_lines_before || num_lines_after) { if(!call.empty()) { print_call("\n"); print_call(" "); pr("see region:\n"); print_call("\n"); } else { if(location) { location_format(pr, location); pr(" "); } pr("see region:\n"); } csubstr region = detail::_get_text_region(source_buffer, location.offset, num_lines_before, num_lines_after); for(csubstr contents : region.split('\n')) { if(!call.empty()) { print_call(" "); } print_line_maybe_truncated(contents); pr("\n"); } assert(location.col == npos || location.col >= first_col_to_show); print_cursor(location.col - first_col_to_show); } } template C4_NO_INLINE void err_basic_format(DumpFn &&dumpfn, csubstr msg, ErrorDataBasic const& errdata) { if(errdata.location) { location_format(dumpfn, errdata.location); std::forward(dumpfn)(" "); } std::forward(dumpfn)("ERROR: [basic] "); std::forward(dumpfn)(msg); } template C4_NO_INLINE void err_parse_format(DumpFn &&dumpfn, csubstr msg, ErrorDataParse const& errdata) { if(errdata.ymlloc) { location_format(std::forward(dumpfn), errdata.ymlloc); std::forward(dumpfn)(" "); } std::forward(dumpfn)("ERROR: [parse] "); std::forward(dumpfn)(msg); if(errdata.cpploc) { std::forward(dumpfn)("\n"); location_format(std::forward(dumpfn), errdata.cpploc); std::forward(dumpfn)(" (detected here)"); } } template C4_NO_INLINE void err_visit_format(DumpFn &&dumpfn, csubstr msg, ErrorDataVisit const& errdata) { char buf_[32]; substr buf(buf_); if(errdata.cpploc) { location_format(dumpfn, errdata.cpploc); std::forward(dumpfn)(" "); } std::forward(dumpfn)("ERROR: [visit] "); std::forward(dumpfn)(msg); if(errdata.node != NONE && errdata.tree != nullptr) { if(errdata.cpploc) { std::forward(dumpfn)("\n"); location_format(dumpfn, errdata.cpploc); std::forward(dumpfn)(" "); } std::forward(dumpfn)("ERROR: ("); if(errdata.node != NONE) { std::forward(dumpfn)("node="); std::forward(dumpfn)(detail::_to_chars_limited(buf, errdata.node)); if(errdata.tree != nullptr) std::forward(dumpfn)(" "); } if(errdata.tree != nullptr) { std::forward(dumpfn)("tree="); std::forward(dumpfn)(detail::_to_chars_limited(buf, static_cast(errdata.tree))); } std::forward(dumpfn)(")"); } } } // namespace yml } // namespace c4 // NOLINTEND(bugprone-use-after-move,hicpp-invalid-access-moved) #endif /* C4_YML_ERROR_HPP_ */ // (end src/c4/yml/error.def.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/escape_scalar.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_ESCAPE_SCALAR_HPP_ #define C4_YML_ESCAPE_SCALAR_HPP_ #ifndef C4_YML_COMMON_HPP_ //#include "c4/yml/common.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/common.hpp must have been amalgamated before this point" #endif namespace c4 { namespace yml { /** Iterate through a scalar and escape special characters in it. This * function takes a callback (which accepts a single parameter of * csubstr type) and, while processing, calls this callback as * appropriate, passing ranges of the scalar and/or escaped * characters. * * @param fn a sink function receiving a csubstr * @param scalar the scalar to be escaped * @param keep_newlines when true, `\n` will be escaped as `\\n\n` instead of just `\\n` * * Example usage: * * ```c++ * // escape to stdout * void escape_scalar(FILE *file, csubstr scalar) * { * auto print_ = [](csubstr repl){ * fwrite(repl.len, 1, repl.str, file); * }; * escape_scalar_fn(std::ref(print_), scalar); * } * * // escape to a different buffer and return the required buffer size * size_t escape_scalar(substr buffer, csubstr scalar) * { * C4_ASSERT(!buffer.overlaps(scalar)); * size_t pos = 0; * auto _append = [&](csubstr repl){ * if(repl.len && (pos + repl.len <= buffer.len)) * memcpy(buffer.str + pos, repl.str, repl.len); * pos += repl.len; * }; * escape_scalar_fn(std::ref(_append), scalar); * return pos; * } * ``` */ template C4_NO_INLINE void escape_scalar_fn(Fn &&fn, csubstr scalar, bool keep_newlines=false) { size_t prev = 0; // the last position that was flushed size_t skip = 0; // how much to add to prev csubstr repl; // replacement string bool newl = false; // to add a newline // cast to u8 to avoid having to deal with negative // signed chars (which are present in some platforms) uint8_t const* C4_RESTRICT s = reinterpret_cast(scalar.str); // NOLINT(*-reinterpret-cast) // NOLINTBEGIN(*-goto,bugprone-use-after-move,hicpp-invalid-access-moved) for(size_t i = 0; i < scalar.len; ++i) { switch(s[i]) { case UINT8_C(0x0a): // \n repl = "\\n"; skip = 1; if(keep_newlines) newl = true; goto flush_now; case UINT8_C(0x5c): // '\\' repl = "\\\\"; skip = 1; goto flush_now; case UINT8_C(0x09): // \t repl = "\\t"; skip = 1; goto flush_now; case UINT8_C(0x0d): // \r repl = "\\r"; skip = 1; goto flush_now; case UINT8_C(0x00): // \0 repl = "\\0"; skip = 1; goto flush_now; case UINT8_C(0x0c): // \f (form feed) repl = "\\f"; skip = 1; goto flush_now; case UINT8_C(0x08): // \b (backspace) repl = "\\b"; skip = 1; goto flush_now; case UINT8_C(0x07): // \a (bell) repl = "\\a"; skip = 1; goto flush_now; case UINT8_C(0x0b): // \v (vertical tab) repl = "\\v"; skip = 1; goto flush_now; case UINT8_C(0x1b): // \e (escape) repl = "\\e"; skip = 1; goto flush_now; case UINT8_C(0xc2): // AKA -0x3e if(i+1 < scalar.len) { if(s[i+1] == UINT8_C(0xa0)) // AKA -0x60 { repl = "\\_"; skip = 2; goto flush_now; } else if(s[i+1] == UINT8_C(0x85)) // AKA -0x7b { repl = "\\N"; skip = 2; goto flush_now; } } continue; case UINT8_C(0xe2): // AKA -0x1e if(i+2 < scalar.len) { if(s[i+1] == UINT8_C(0x80)) // AKA -0x80 { if(s[i+2] == UINT8_C(0xa8)) // AKA -0x58 { repl = "\\L"; skip = 3; goto flush_now; } else if(s[i+2] == UINT8_C(0xa9)) // AKA -0x57 { repl = "\\P"; skip = 3; goto flush_now; } } } continue; default: continue; } flush_now: std::forward(fn)(scalar.range(prev, i)); std::forward(fn)(repl); if(newl) { std::forward(fn)("\n"); newl = false; } prev = i + skip; } // flush the rest if(scalar.len > prev) std::forward(fn)(scalar.sub(prev)); // NOLINTEND(*-goto,bugprone-use-after-move,hicpp-invalid-access-moved) } C4_SUPPRESS_WARNING_GCC_WITH_PUSH("-Wattributes") /** Adjust a position in a scalar, increasing it to account for any * escaped characters. * * @note This is a utility/debugging function, so it is provided in * this optional header. For this reason, we inline it to obey to the * One Definition Rule. But then we set the noinline attribute to * ensure they are not inlined in calling code. */ inline C4_NO_INLINE size_t adjust_pos_with_escapes(csubstr scalar, size_t pos, bool keep_newlines=false) { // cast to u8 to avoid having to deal with negative // signed chars (which are present in some platforms) uint8_t const* C4_RESTRICT s = reinterpret_cast(scalar.str); // NOLINT(*-reinterpret-cast) const size_t newbump = keep_newlines ? 2 : 1; size_t ret = 0; size_t excess = pos > scalar.len ? pos - scalar.len : 0; pos = pos < scalar.len ? pos : scalar.len; for(size_t i = 0; i < pos; ++i) { ++ret; switch(s[i]) { case UINT8_C(0x5c): // '\\' case UINT8_C(0x09): // \t case UINT8_C(0x0d): // \r case UINT8_C(0x00): // \0 case UINT8_C(0x0c): // \f (form feed) case UINT8_C(0x08): // \b (backspace) case UINT8_C(0x07): // \a (bell) case UINT8_C(0x0b): // \v (vertical tab) case UINT8_C(0x1b): // \e (escape) ++ret; // add the backslash break; case UINT8_C(0x0a): // \n ret += newbump; break; case UINT8_C(0xc2): // AKA -0x3e if(i+1 < scalar.len) { if(s[i+1] == UINT8_C(0xa0) // AKA -0x60 -> \_ || s[i+1] == UINT8_C(0x85)) // AKA -0x7b -> \N { ++ret; ++i; // skip the next entry } } break; case UINT8_C(0xe2): // AKA -0x1e if(i+2 < scalar.len) { if(s[i+1] == UINT8_C(0x80)) // AKA -0x80 { if(s[i+2] == UINT8_C(0xa8) // AKA -0x58 -> \L || s[i+2] == UINT8_C(0xa9)) // AKA -0x57 -> \P { ++ret; i += 2; // skip the next two entries } } } break; default: break; } } return ret + excess; } /** Escape a scalar to an existing buffer, using @ref escape_scalar_fn * * @note This is a utility/debugging function, so it is provided in * this optional header. For this reason, we inline it to obey to the * One Definition Rule. But then we set the noinline attribute to * ensure they are not inlined in calling code. */ inline C4_NO_INLINE size_t escape_scalar(substr buffer, csubstr scalar, bool keep_newlines=false) { size_t pos = 0; C4_ASSERT(!buffer.overlaps(scalar)); auto append_ = [&pos, &buffer](csubstr repl){ if(repl.len && (pos + repl.len <= buffer.len)) memcpy(buffer.str + pos, repl.str, repl.len); pos += repl.len; }; escape_scalar_fn(append_, scalar, keep_newlines); return pos; } /** formatting helper to escape a scalar with @ref escape_scalar_fn() */ struct escaped_scalar { escaped_scalar(csubstr s, bool keep_newl=false) : scalar(s), keep_newlines(keep_newl) {} csubstr scalar; bool keep_newlines; }; /** formatting implementation to escape a scalar with @ref escape_scalar() */ inline C4_NO_INLINE size_t to_chars(substr buf, escaped_scalar e) { return escape_scalar(buf, e.scalar, e.keep_newlines); } /** dumping implementation to escape a scalar with @ref escape_scalar_fn() */ template C4_NO_INLINE size_t dump(SinkPfn &&sinkfn, substr buf, escaped_scalar const& e) { (void)buf; C4_ASSERT(!buf.overlaps(e.scalar)); escape_scalar_fn(std::forward(sinkfn), e.scalar, e.keep_newlines); return 0; } C4_SUPPRESS_WARNING_GCC_POP } // namespace yml } // namespace c4 #endif /* C4_YML_ESCAPE_SCALAR_HPP_ */ // (end src/c4/yml/escape_scalar.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/node_type.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_NODE_TYPE_HPP_ #define C4_YML_NODE_TYPE_HPP_ #ifndef C4_YML_COMMON_HPP_ //#include "c4/yml/common.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/common.hpp must have been amalgamated before this point" #endif C4_SUPPRESS_WARNING_MSVC_PUSH C4_SUPPRESS_WARNING_GCC_CLANG_PUSH C4_SUPPRESS_WARNING_GCC_CLANG("-Wold-style-cast") #if defined(__GNUC__) && __GNUC__ >= 6 C4_SUPPRESS_WARNING_GCC("-Wnull-dereference") #endif // NOLINTBEGIN(modernize-avoid-c-style-cast) namespace c4 { namespace yml { /** @addtogroup doc_node_type * * @{ */ /** the integral type necessary to cover all the bits for NodeType_e */ using type_bits = uint32_t; /** a bit mask for marking node types and styles */ typedef enum : type_bits { // NOLINT #define b_(v) (type_bits(1) << v) // a convenience define, undefined below // NOLINT NOTYPE = 0, ///< no node type or style is set KEY = b_(0), ///< the scalar to the left of `:` in a map's member VAL = b_(1), ///< a scalar: has a scalar (ie string) value, possibly empty. must be a leaf node, and cannot be MAP or SEQ MAP = b_(2), ///< a map: a parent of KEYVAL/KEYSEQ/KEYMAP nodes SEQ = b_(3), ///< a seq: a parent of VAL/SEQ/MAP nodes DOC = b_(4), ///< a document STREAM = b_(5)|SEQ, ///< a stream: a seq of docs KEYREF = b_(6), ///< a *reference: the key references an &anchor VALREF = b_(7), ///< a *reference: the val references an &anchor KEYANCH = b_(8), ///< the key has an &anchor VALANCH = b_(9), ///< the val has an &anchor KEYTAG = b_(10), ///< the key has a tag VALTAG = b_(11), ///< the val has a tag KEYNIL = b_(12), ///< the key is null (eg `{ : b}` results in a null key) VALNIL = b_(13), ///< the val is null (eg `{a : }` results in a null val) TYMASK_ = b_(14)-1, ///< all the bits up to here // // unfiltered flags: // KEY_UNFILT = b_(14), ///< the key scalar was left unfiltered; the parser was set not to filter. @see @ref ParserOptions::scalar_filtering() VAL_UNFILT = b_(15), ///< the val scalar was left unfiltered; the parser was set not to filter. @see @ref ParserOptions::scalar_filtering() // // style flags: // FLOW_SL = b_(16), ///< mark container with single-line flow style ///< - seqs as ///< @code{yaml} ///< [val1,val2] ///< @endcode ///< when @ref FLOW_SPC is not set, or ///< @code{yaml} ///< [val1, val2] ///< @endcode ///< when @ref FLOW_SPC is set (or @ref EmitOptions::force_flow_spc() is set) ///< - maps as ///< @code{yaml} ///< {key1: val1,key2: val2} ///< @endcode ///< when @ref FLOW_SPC is not set, or ///< @code{yaml} ///< {key1: val1, key2: val2} ///< @endcode ///< when @ref FLOW_SPC is set (or @ref EmitOptions::force_flow_spc() is set) FLOW_ML1 = b_(17), ///< mark container with multi-line flow style, 1 element per line ///< - seqs as ///< @code{yaml} ///< [ ///< val1, ///< val2 ///< ] ///< @endcode ///< - maps as ///< @code{yaml} ///< { ///< key: val, ///< key2: val2 ///< } ///< @endcode FLOW_MLN = b_(18), ///< mark container with multi-line flow style, n elements per line, ///< wrapped (as set by @ref EmitOptions::max_cols()): ///< - seqs as ///< @code{yaml} ///< [ ///< val,val,... ///< val,val,... ///< val,val,... ///< ... ///< val ///< ] ///< @endcode ///< when @ref FLOW_SPC is not set, or ///< @code{yaml} ///< [ ///< val, val,... ///< val, val,... ///< val, val,... ///< ... ///< val ///< ] ///< @endcode ///< when @ref FLOW_SPC is set (or @ref EmitOptions::force_flow_spc() is set) ///< - maps as ///< @code{yaml} ///< { ///< key: val,key: val,... ///< key: val,key: val,... ///< ... ///< key: val ///< } ///< @endcode ///< when @ref FLOW_SPC is not set, or ///< @code{yaml} ///< { ///< key: val, key: val,... ///< key: val, key: val,... ///< ... ///< key: val ///< } ///< @endcode ///< when @ref FLOW_SPC is set (or @ref EmitOptions::force_flow_spc() is set) FLOW_SPC = b_(19), ///< mark container with spaces after comma when in flow mode. ///< Applies to both @ref FLOW_SL and @ref FLOW_MLN (but not ///< to @ref FLOW_ML1), and can be overriden globally by ///< @ref EmitOptions::force_flow_spc(). BLOCK = b_(20), ///< mark container with block style ///< - seqs as ///< @code{yaml} ///< - val1 ///< - val2 ///< @endcode ///< - maps as ///< @code{yaml} ///< key1: val1 ///< key2: val2 ///< @endcode KEY_LITERAL = b_(21), ///< mark key scalar as multiline, block literal | VAL_LITERAL = b_(22), ///< mark val scalar as multiline, block literal | KEY_FOLDED = b_(23), ///< mark key scalar as multiline, block folded > VAL_FOLDED = b_(24), ///< mark val scalar as multiline, block folded > KEY_SQUO = b_(25), ///< mark key scalar as single quoted ' VAL_SQUO = b_(26), ///< mark val scalar as single quoted ' KEY_DQUO = b_(27), ///< mark key scalar as double quoted " VAL_DQUO = b_(28), ///< mark val scalar as double quoted " KEY_PLAIN = b_(29), ///< mark key scalar as plain scalar (unquoted, even when multiline) VAL_PLAIN = b_(30), ///< mark val scalar as plain scalar (unquoted, even when multiline) // // type combination masks: // KEYVAL = KEY|VAL, ///< mask of @ref KEY|@ref VAL KEYSEQ = KEY|SEQ, ///< mask of @ref KEY|@ref SEQ KEYMAP = KEY|MAP, ///< mask of @ref KEY|@ref MAP DOCMAP = DOC|MAP, ///< mask of @ref DOC|@ref MAP DOCSEQ = DOC|SEQ, ///< mask of @ref DOC|@ref SEQ DOCVAL = DOC|VAL, ///< mask of @ref DOC|@ref VAL // // style combination masks: // SCALAR_LITERAL = KEY_LITERAL|VAL_LITERAL, ///< mask of @ref KEY_LITERAL|@ref VAL_LITERAL, SCALAR_FOLDED = KEY_FOLDED|VAL_FOLDED, ///< mask of @ref KEY_FOLDED|@ref VAL_FOLDED, SCALAR_SQUO = KEY_SQUO|VAL_SQUO, ///< mask of @ref KEY_SQUO|@ref VAL_SQUO, SCALAR_DQUO = KEY_DQUO|VAL_DQUO, ///< mask of @ref KEY_DQUO|@ref VAL_DQUO, SCALAR_PLAIN = KEY_PLAIN|VAL_PLAIN, ///< mask of @ref KEY_PLAIN|@ref VAL_PLAIN, KEYQUO = KEY_SQUO|KEY_DQUO|KEY_FOLDED|KEY_LITERAL, ///< key style is one of `'">|`. mask of @ref KEY_SQUO|@ref KEY_DQUO|@ref KEY_FOLDED|@ref KEY_LITERAL VALQUO = VAL_SQUO|VAL_DQUO|VAL_FOLDED|VAL_LITERAL, ///< val style is one of `'">|`. mask of @ref VAL_SQUO|@ref VAL_DQUO|@ref VAL_FOLDED|@ref VAL_LITERAL KEY_STYLE = KEYQUO|KEY_PLAIN, ///< mask of @ref KEYQUO|@ref KEY_PLAIN : all the key scalar styles for key (not container styles!) VAL_STYLE = VALQUO|VAL_PLAIN, ///< mask of @ref VALQUO|@ref VAL_PLAIN : all the val scalar styles for val (not container styles!) SCALAR_STYLE = KEY_STYLE|VAL_STYLE, ///< mask of @ref KEY_STYLE|@ref VAL_STYLE : all the key+val scalar styles FLOW_MLX = FLOW_ML1|FLOW_MLN, ///< mask of @ref FLOW_ML1|@ref FLOW_MLN : all the flow multiline styles CONTAINER_STYLE_FLOW = FLOW_SL|FLOW_MLX|FLOW_SPC, ///< mask of @ref FLOW_SL|@ref FLOW_MLX|@ref FLOW_SPC : all flow flags CONTAINER_STYLE_BLOCK = BLOCK, ///< alias to @ref BLOCK CONTAINER_STYLE = CONTAINER_STYLE_FLOW|CONTAINER_STYLE_BLOCK, ///< mask of @ref CONTAINER_STYLE_FLOW|@ref CONTAINER_STYLE_BLOCK : all container style flags STYLE = SCALAR_STYLE | CONTAINER_STYLE, ///< mask of @ref SCALAR_STYLE | @ref CONTAINER_STYLE : all style flags // // mixed masks /** @cond dev */ KEYMASK_ = KEY | KEYQUO | KEYANCH | KEYREF | KEYTAG, VALMASK_ = VAL | VALQUO | VALANCH | VALREF | VALTAG, #undef b_ #ifdef RYML_HAS_DEPRECATED_ENUMS_ FLOW_ML RYML_DEPRECATED("use one of FLOW_ML{1,N,X}") = FLOW_ML1, #endif /** @endcond */ } NodeTypeBits; /** @cond dev */ using NodeType_e RYML_DEPRECATED("use NodeTypeBits") = NodeTypeBits; #ifndef RYML_HAS_DEPRECATED_ENUMS_ // defined here because the current c++ standard / compiler cannot // handle deprecated enums RYML_DEPRECATED("use one of FLOW_ML{1,N,X}") constexpr const type_bits FLOW_ML = FLOW_ML1; #endif /** @endcond */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** Wraps a @ref type_bits mask of @ref NodeTypeBits flags with some * syntactic sugar and predicates. */ struct RYML_EXPORT NodeType { public: type_bits m_bits; public: /** @name auto convert to type_bits * @{ */ C4_ALWAYS_INLINE operator type_bits & () noexcept { return m_bits; } C4_ALWAYS_INLINE operator type_bits const& () const noexcept { return m_bits; } /** @} */ public: /** @name ctor * @{ */ C4_ALWAYS_INLINE NodeType() noexcept : m_bits(NOTYPE) {} C4_ALWAYS_INLINE NodeType(type_bits t) noexcept : m_bits(t) {} /** @} */ public: /** @name query / set * @{ */ C4_ALWAYS_INLINE bool has_any(type_bits t) const noexcept { return (m_bits & t) != 0u; } C4_ALWAYS_INLINE bool has_all(type_bits t) const noexcept { return (m_bits & t) == t; } C4_ALWAYS_INLINE bool has_none(type_bits t) const noexcept { return (m_bits & t) == 0; } C4_ALWAYS_INLINE void set(type_bits t) noexcept { m_bits = t; } C4_ALWAYS_INLINE void add(type_bits t) noexcept { m_bits |= t; } C4_ALWAYS_INLINE void rem(type_bits t) noexcept { m_bits &= ~t; } C4_ALWAYS_INLINE void addrem(type_bits bits_to_add, type_bits bits_to_remove) noexcept { m_bits |= bits_to_add; m_bits &= ~bits_to_remove; } C4_ALWAYS_INLINE void clear() noexcept { m_bits = NOTYPE; } /** @} */ public: /** @name convert to string * @{ */ /** return a preset string based on the node type */ C4_ALWAYS_INLINE const char *type_str() const noexcept { return type_str(m_bits); } /** return a preset string based on the node type */ static const char* type_str(type_bits t) noexcept; /** fill a string with the node type flags. */ C4_ALWAYS_INLINE size_t type_str(substr buf) const noexcept { return type_str(buf, m_bits); } /** fill a string with the node type flags. */ static size_t type_str(substr buf, type_bits t) noexcept; /** fill a string with the node type flags. If the string is small, returns {null, len} */ C4_ALWAYS_INLINE csubstr type_str_sub(substr buf) const noexcept { return type_str_sub(buf, m_bits); } /** fill a string with the node type flags. If the string is small, returns {null, len} */ static csubstr type_str_sub(substr buf, type_bits t) noexcept { csubstr ret; ret.len = type_str(buf, t); ret.str = ret.len < buf.len ? buf.str : nullptr; return ret; } /** @} */ public: /** @name node type predicates * @{ */ C4_ALWAYS_INLINE bool is_notype() const noexcept { return m_bits == NOTYPE; } C4_ALWAYS_INLINE bool is_stream() const noexcept { return ((m_bits & STREAM) == STREAM) != 0; } C4_ALWAYS_INLINE bool is_doc() const noexcept { return (m_bits & DOC) != 0; } C4_ALWAYS_INLINE bool is_container() const noexcept { return (m_bits & (MAP|SEQ|STREAM)) != 0; } C4_ALWAYS_INLINE bool is_map() const noexcept { return (m_bits & MAP) != 0; } C4_ALWAYS_INLINE bool is_seq() const noexcept { return (m_bits & SEQ) != 0; } C4_ALWAYS_INLINE bool has_key() const noexcept { return (m_bits & KEY) != 0; } C4_ALWAYS_INLINE bool has_val() const noexcept { return (m_bits & VAL) != 0; } C4_ALWAYS_INLINE bool is_val() const noexcept { return (m_bits & KEYVAL) == VAL; } C4_ALWAYS_INLINE bool is_keyval() const noexcept { return (m_bits & KEYVAL) == KEYVAL; } C4_ALWAYS_INLINE bool key_is_null() const noexcept { return (m_bits & KEYNIL) != 0; } C4_ALWAYS_INLINE bool val_is_null() const noexcept { return (m_bits & VALNIL) != 0; } C4_ALWAYS_INLINE bool has_key_tag() const noexcept { return (m_bits & KEYTAG) != 0; } C4_ALWAYS_INLINE bool has_val_tag() const noexcept { return (m_bits & VALTAG) != 0; } C4_ALWAYS_INLINE bool has_key_anchor() const noexcept { return (m_bits & KEYANCH) != 0; } C4_ALWAYS_INLINE bool has_val_anchor() const noexcept { return (m_bits & VALANCH) != 0; } C4_ALWAYS_INLINE bool has_anchor() const noexcept { return (m_bits & (KEYANCH|VALANCH)) != 0; } C4_ALWAYS_INLINE bool is_key_ref() const noexcept { return (m_bits & KEYREF) != 0; } C4_ALWAYS_INLINE bool is_val_ref() const noexcept { return (m_bits & VALREF) != 0; } C4_ALWAYS_INLINE bool is_ref() const noexcept { return (m_bits & (KEYREF|VALREF)) != 0; } C4_ALWAYS_INLINE bool is_key_unfiltered() const noexcept { return (m_bits & (KEY_UNFILT)) != 0; } C4_ALWAYS_INLINE bool is_val_unfiltered() const noexcept { return (m_bits & (VAL_UNFILT)) != 0; } /** @} */ public: /** @name node style predicates * @{ */ C4_ALWAYS_INLINE bool is_container_styled() const noexcept { return (m_bits & (CONTAINER_STYLE)) != 0; } C4_ALWAYS_INLINE bool is_block() const noexcept { return (m_bits & (BLOCK)) != 0; } C4_ALWAYS_INLINE bool is_flow_sl() const noexcept { return (m_bits & (FLOW_SL)) != 0; } C4_ALWAYS_INLINE bool is_flow_ml1() const noexcept { return (m_bits & (FLOW_ML1)) != 0; } C4_ALWAYS_INLINE bool is_flow_mln() const noexcept { return (m_bits & (FLOW_MLN)) != 0; } C4_ALWAYS_INLINE bool is_flow_mlx() const noexcept { return (m_bits & (FLOW_ML1|FLOW_MLN)) != 0; } C4_ALWAYS_INLINE bool is_flow() const noexcept { return (m_bits & (FLOW_ML1|FLOW_MLN|FLOW_SL)) != 0; } C4_ALWAYS_INLINE bool has_flow_space() const noexcept { return (m_bits & (FLOW_SPC)) != 0; } C4_ALWAYS_INLINE bool is_key_styled() const noexcept { return (m_bits & (KEY_STYLE)) != 0; } C4_ALWAYS_INLINE bool is_val_styled() const noexcept { return (m_bits & (VAL_STYLE)) != 0; } C4_ALWAYS_INLINE bool is_key_literal() const noexcept { return (m_bits & (KEY_LITERAL)) != 0; } C4_ALWAYS_INLINE bool is_val_literal() const noexcept { return (m_bits & (VAL_LITERAL)) != 0; } C4_ALWAYS_INLINE bool is_key_folded() const noexcept { return (m_bits & (KEY_FOLDED)) != 0; } C4_ALWAYS_INLINE bool is_val_folded() const noexcept { return (m_bits & (VAL_FOLDED)) != 0; } C4_ALWAYS_INLINE bool is_key_squo() const noexcept { return (m_bits & (KEY_SQUO)) != 0; } C4_ALWAYS_INLINE bool is_val_squo() const noexcept { return (m_bits & (VAL_SQUO)) != 0; } C4_ALWAYS_INLINE bool is_key_dquo() const noexcept { return (m_bits & (KEY_DQUO)) != 0; } C4_ALWAYS_INLINE bool is_val_dquo() const noexcept { return (m_bits & (VAL_DQUO)) != 0; } C4_ALWAYS_INLINE bool is_key_plain() const noexcept { return (m_bits & (KEY_PLAIN)) != 0; } C4_ALWAYS_INLINE bool is_val_plain() const noexcept { return (m_bits & (VAL_PLAIN)) != 0; } C4_ALWAYS_INLINE bool is_key_quoted() const noexcept { return (m_bits & KEYQUO) != 0; } C4_ALWAYS_INLINE bool is_val_quoted() const noexcept { return (m_bits & VALQUO) != 0; } C4_ALWAYS_INLINE bool is_quoted() const noexcept { return (m_bits & (KEYQUO|VALQUO)) != 0; } C4_ALWAYS_INLINE NodeType key_style() const noexcept { return (m_bits & (KEY_STYLE)); } C4_ALWAYS_INLINE NodeType val_style() const noexcept { return (m_bits & (VAL_STYLE)); } C4_ALWAYS_INLINE void set_container_style(type_bits style) noexcept { m_bits = ((style & CONTAINER_STYLE) | (m_bits & ~CONTAINER_STYLE)); } C4_ALWAYS_INLINE void set_key_style(type_bits style) noexcept { m_bits = ((style & KEY_STYLE) | (m_bits & ~KEY_STYLE)); } C4_ALWAYS_INLINE void set_val_style(type_bits style) noexcept { m_bits = ((style & VAL_STYLE) | (m_bits & ~VAL_STYLE)); } C4_ALWAYS_INLINE void clear_style() noexcept { m_bits &= ~STYLE; } /** @} */ public: // deprecated methods /** @cond dev */ // LCOV_EXCL_START RYML_DEPRECATED("use has_key_anchor()") bool is_key_anchor() const noexcept { return has_key_anchor(); } RYML_DEPRECATED("use has_val_anchor()") bool is_val_anchor() const noexcept { return has_val_anchor(); } RYML_DEPRECATED("use has_anchor()") bool is_anchor() const noexcept { return has_anchor(); } RYML_DEPRECATED("use has_anchor() || is_ref()") bool is_anchor_or_ref() const noexcept { return has_anchor() || is_ref(); } RYML_DEPRECATED("use one of .is_flow_ml{1,n,x}()") bool is_flow_ml() const noexcept { return (m_bits & (FLOW_ML1)) != 0; } /** @endcond */ // LCOV_EXCL_STOP }; /** @} */ } // namespace yml } // namespace c4 // NOLINTEND(modernize-avoid-c-style-cast) C4_SUPPRESS_WARNING_MSVC_POP C4_SUPPRESS_WARNING_GCC_CLANG_POP #endif /* C4_YML_NODE_TYPE_HPP_ */ // (end src/c4/yml/node_type.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/parse_options.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_PARSE_OPTIONS_HPP_ #define C4_YML_PARSE_OPTIONS_HPP_ /** @file parse_options.hpp */ #ifndef C4_YML_COMMON_HPP_ //#include // amalgamate: remove include #error "amalgamate: c4/yml/common.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_NODE_TYPE_HPP_ //#include // amalgamate: remove include #error "amalgamate: c4/yml/node_type.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_ERROR_HPP_ //#include // amalgamate: remove include #error "amalgamate: c4/yml/error.hpp must have been amalgamated before this point" #endif namespace c4 { namespace yml { /** Options to give to the @ref ParseEngine to control its behavior. */ struct RYML_EXPORT ParserOptions { private: typedef enum : uint32_t { // NOLINT DETECT_FLOW_ML = (1u << 0u), RESOLVE_TAGS = (1u << 1u), RESOLVE_TAGS_ALL = (1u << 2u), SCALAR_FILTERING = (1u << 3u), LOCATIONS = (1u << 4u), DEFAULTS = SCALAR_FILTERING|DETECT_FLOW_ML, } Flags_e; uint32_t m_flags = DEFAULTS; type_bits m_flow_ml_style = FLOW_ML1; ParserOptions& set_flags_(bool enabled, Flags_e f) { if(enabled) m_flags |= f; else m_flags &= ~f; return *this; } public: ParserOptions() noexcept = default; public: /** @name detection of @ref FLOW_ML container style * @{ */ /** enable/disable detection of flow multiline container * style. When enabled, the parser will set either @ref FLOW_ML1 * or @ref FLOW_MLN flow multiline style as the style of flow * containers which have the terminating bracket on a line * different from that of the opening bracket. Default is to * detect flow multiline. Use @ref ParserOptions::flow_ml_style() * to choose between the @ref FLOW_ML1 or @ref FLOW_MLN styles. */ ParserOptions& detect_flow_ml(bool enabled) noexcept { return set_flags_(enabled, DETECT_FLOW_ML); } /** query status of detection of flow multiline container style. */ C4_ALWAYS_INLINE bool detect_flow_ml() const noexcept { return (m_flags & DETECT_FLOW_ML); } /** choose the default style of multiline flow containers, when a * container is detected as flow multiline. Input should be @ref * FLOW_ML1 or @ref FLOW_MLN . Default is @ref FLOW_ML1 (the old * behavior). */ ParserOptions& flow_ml_style(NodeType style) noexcept { RYML_ASSERT_BASIC_(style & (FLOW_ML1|FLOW_MLN)); m_flow_ml_style = style & (FLOW_ML1|FLOW_MLN); return *this; } C4_ALWAYS_INLINE NodeType flow_ml_style() const noexcept { return m_flow_ml_style; } /** @} */ public: /** @name resolution of tags */ /** @{ */ /** enable/disable resolution of YAML tags during parsing. When * enabled, tags are resolved according to existing tag * directives. Disabled by default. See also @ref * ParserOptions::resolve_tags_all(). */ ParserOptions& resolve_tags(bool enabled) noexcept { return set_flags_(enabled, RESOLVE_TAGS); } /** query status of tag resolution setting. */ C4_ALWAYS_INLINE bool resolve_tags() const noexcept { return (m_flags & RESOLVE_TAGS); } /** When resolve_tags() is enabled, resolve not just prefixed tags * of the form
!handle!tag
, but also non-prefixed tags * (
!!tag
and
!tag!
). Disabled by default. */ ParserOptions& resolve_tags_all(bool enabled) noexcept { return set_flags_(enabled, RESOLVE_TAGS_ALL); } /** query status of non-prefixed tag resolution setting. */ C4_ALWAYS_INLINE bool resolve_tags_all() const noexcept { return (m_flags & RESOLVE_TAGS_ALL); } /** @} */ public: /** @name source location tracking */ /** @{ */ /** enable/disable source location tracking. Disabled by default. */ ParserOptions& locations(bool enabled) noexcept { return set_flags_(enabled, LOCATIONS); } /** query source location tracking status */ C4_ALWAYS_INLINE bool locations() const noexcept { return (m_flags & LOCATIONS); } /** @} */ public: /** @name scalar filtering status (experimental; disable at your discretion) */ /** @{ */ /** enable/disable scalar filtering while parsing. Enabled by default. */ ParserOptions& scalar_filtering(bool enabled) noexcept { return set_flags_(enabled, SCALAR_FILTERING); } /** query scalar filtering status */ C4_ALWAYS_INLINE bool scalar_filtering() const noexcept { return (m_flags & SCALAR_FILTERING); } /** @} */ }; } // namespace yml } // namespace c4 #endif /* C4_YML_PARSE_OPTIONS_HPP_ */ // (end src/c4/yml/parse_options.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/detail/stack.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_DETAIL_STACK_HPP_ #define C4_YML_DETAIL_STACK_HPP_ #ifndef C4_YML_COMMON_HPP_ //#include "c4/yml/common.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/common.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_ERROR_HPP_ //#include "c4/yml/error.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/error.hpp must have been amalgamated before this point" #endif #ifdef RYML_DBG //# include // amalgamate: included above #endif //#include // amalgamate: included above namespace c4 { namespace yml { C4_SUPPRESS_WARNING_GCC_CLANG_WITH_PUSH("-Wold-style-cast") // NOLINTBEGIN(modernize-avoid-c-style-cast) namespace detail { /** A lightweight contiguous stack with Small Storage * Optimization. This is required because std::vector can throw * exceptions, and we don't want to enforce any particular error * mechanism. */ template class stack { static_assert(std::is_trivially_copyable::value, "T must be trivially copyable"); static_assert(std::is_trivially_destructible::value, "T must be trivially destructible"); public: enum : id_type { sso_size = N }; // NOLINT public: T m_buf[size_t(N)]; T *C4_RESTRICT m_stack; id_type m_size; id_type m_capacity; Callbacks m_callbacks; public: constexpr static bool is_contiguous() noexcept { return true; } stack(Callbacks const& cb) : m_buf() , m_stack(m_buf) , m_size(0) , m_capacity(N) , m_callbacks(cb) {} stack() : stack(get_callbacks()) {} ~stack() { _free(); } stack(stack const& that) RYML_NOEXCEPT : stack(that.m_callbacks) { resize(that.m_size); _cp(&that); } stack(stack &&that) noexcept : stack(that.m_callbacks) { _mv(&that); } stack& operator= (stack const& that) RYML_NOEXCEPT { if(&that != this) { _cb(that.m_callbacks); resize(that.m_size); _cp(&that); } return *this; } stack& operator= (stack &&that) noexcept { _cb(that.m_callbacks); _mv(&that); return *this; } public: id_type size() const { return m_size; } id_type empty() const { return m_size == 0; } id_type capacity() const { return m_capacity; } void clear() { _free(); } void resize(id_type sz) { reserve(sz); m_size = sz; } void reserve(id_type sz); void push(T const& C4_RESTRICT n) { RYML_ASSERT_BASIC_CB_(m_callbacks, !csubstr((const char*)&n, sizeof(T)).overlaps(csubstr((const char*)m_stack, m_capacity * sizeof(T)))); if(m_size == m_capacity) reserve(m_capacity + 1); m_stack[m_size] = n; ++m_size; } void push_top() { RYML_ASSERT_BASIC_CB_(m_callbacks, m_size > 0); if(m_size == m_capacity) reserve(m_capacity + 1); m_stack[m_size] = m_stack[m_size - 1]; ++m_size; } T const& C4_RESTRICT pop() { RYML_ASSERT_BASIC_CB_(m_callbacks, m_size > 0); --m_size; return m_stack[m_size]; } C4_ALWAYS_INLINE T const& C4_RESTRICT top() const { RYML_ASSERT_BASIC_CB_(m_callbacks, m_size > 0); return m_stack[m_size - 1]; } C4_ALWAYS_INLINE T & C4_RESTRICT top() { RYML_ASSERT_BASIC_CB_(m_callbacks, m_size > 0); return m_stack[m_size - 1]; } C4_ALWAYS_INLINE T const& C4_RESTRICT bottom() const { RYML_ASSERT_BASIC_CB_(m_callbacks, m_size > 0); return m_stack[0]; } C4_ALWAYS_INLINE T & C4_RESTRICT bottom() { RYML_ASSERT_BASIC_CB_(m_callbacks, m_size > 0); return m_stack[0]; } C4_ALWAYS_INLINE T const& C4_RESTRICT top(id_type i) const { RYML_ASSERT_BASIC_CB_(m_callbacks, i < m_size); return m_stack[m_size - 1 - i]; } C4_ALWAYS_INLINE T & C4_RESTRICT top(id_type i) { RYML_ASSERT_BASIC_CB_(m_callbacks, i < m_size); return m_stack[m_size - 1 - i]; } C4_ALWAYS_INLINE T const& C4_RESTRICT bottom(id_type i) const { RYML_ASSERT_BASIC_CB_(m_callbacks, i < m_size); return m_stack[i]; } C4_ALWAYS_INLINE T & C4_RESTRICT bottom(id_type i) { RYML_ASSERT_BASIC_CB_(m_callbacks, i < m_size); return m_stack[i]; } C4_ALWAYS_INLINE T const& C4_RESTRICT operator[](id_type i) const { RYML_ASSERT_BASIC_CB_(m_callbacks, i < m_size); return m_stack[i]; } C4_ALWAYS_INLINE T & C4_RESTRICT operator[](id_type i) { RYML_ASSERT_BASIC_CB_(m_callbacks, i < m_size); return m_stack[i]; } public: using iterator = T *; using const_iterator = T const *; iterator begin() noexcept { return m_stack; } iterator end () noexcept { return m_stack + m_size; } const_iterator begin() const noexcept { return (const_iterator)m_stack; } const_iterator end () const noexcept { return (const_iterator)m_stack + m_size; } public: void _free(); void _cp(stack const* C4_RESTRICT that); void _mv(stack * that); void _cb(Callbacks const& cb); }; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- template void stack::reserve(id_type cap) { RYML_ASSERT_BASIC_CB_(m_callbacks, m_size <= m_capacity); RYML_ASSERT_BASIC_CB_(m_callbacks, m_capacity); if(cap <= m_capacity || (cap <= N && m_stack == m_buf)) return; id_type next = 2 * m_capacity; cap = cap > next ? cap : next; T *ptr = (T*) m_callbacks.m_allocate((size_t)cap * sizeof(T), m_stack, m_callbacks.m_user_data); RYML_ASSERT_BASIC_CB_(m_callbacks, ((uintptr_t)ptr % alignof(T)) == 0u); if(m_size) memcpy(ptr, m_stack, (size_t)m_size * sizeof(T)); if(m_stack != m_buf) m_callbacks.m_free(m_stack, (size_t)m_capacity * sizeof(T), m_callbacks.m_user_data); m_stack = ptr; m_capacity = cap; } //----------------------------------------------------------------------------- template void stack::_free() { RYML_ASSERT_BASIC_CB_(m_callbacks, m_stack != nullptr); // this structure cannot be memset() to zero if(m_stack != m_buf) { m_callbacks.m_free(m_stack, (size_t)m_capacity * sizeof(T), m_callbacks.m_user_data); m_stack = m_buf; m_capacity = N; } else { RYML_ASSERT_BASIC_CB_(m_callbacks, m_capacity == N); } m_size = 0; } //----------------------------------------------------------------------------- template void stack::_cp(stack const* C4_RESTRICT that) { if(that->m_stack != that->m_buf) { RYML_ASSERT_BASIC_CB_(m_callbacks, that->m_capacity > N); RYML_ASSERT_BASIC_CB_(m_callbacks, that->m_size <= that->m_capacity); } else { RYML_ASSERT_BASIC_CB_(m_callbacks, that->m_capacity <= N); RYML_ASSERT_BASIC_CB_(m_callbacks, that->m_size <= that->m_capacity); } memcpy(m_stack, that->m_stack, that->m_size * sizeof(T)); m_size = that->m_size; m_capacity = that->m_size < N ? N : that->m_size; m_callbacks = that->m_callbacks; } //----------------------------------------------------------------------------- template void stack::_mv(stack * that) { if(that->m_stack != that->m_buf) { RYML_ASSERT_BASIC_CB_(m_callbacks, that->m_capacity > N); RYML_ASSERT_BASIC_CB_(m_callbacks, that->m_size <= that->m_capacity); m_stack = that->m_stack; } else { RYML_ASSERT_BASIC_CB_(m_callbacks, that->m_capacity <= N); RYML_ASSERT_BASIC_CB_(m_callbacks, that->m_size <= that->m_capacity); memcpy(m_buf, that->m_buf, that->m_size * sizeof(T)); m_stack = m_buf; } m_size = that->m_size; m_capacity = that->m_capacity; m_callbacks = that->m_callbacks; // make sure no deallocation happens on destruction RYML_ASSERT_BASIC_CB_(m_callbacks, that->m_stack != m_buf); that->m_stack = that->m_buf; that->m_capacity = N; that->m_size = 0; } //----------------------------------------------------------------------------- template void stack::_cb(Callbacks const& cb) { if(cb != m_callbacks) { _free(); m_callbacks = cb; } } } // namespace detail // NOLINTEND(modernize-avoid-c-style-cast) C4_SUPPRESS_WARNING_GCC_CLANG_POP } // namespace yml } // namespace c4 #endif /* C4_YML_DETAIL_STACK_HPP_ */ // (end src/c4/yml/detail/stack.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/file.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_FILE_HPP_ #define C4_YML_FILE_HPP_ /** @name file.hpp Helpers to read/write files from disk */ #ifndef C4_YML_ERROR_HPP_ //#include // amalgamate: remove include #error "amalgamate: c4/yml/error.hpp must have been amalgamated before this point" #endif //#include // amalgamate: included above //#include // amalgamate: included above namespace c4 { namespace yml { C4_SUPPRESS_WARNING_MSVC_WITH_PUSH(4996) // fopen: this function may be unsafe C4_SUPPRESS_WARNING_CLANG_WITH_PUSH("-Wdeprecated-declarations") // fopen is deprecated /** @cond dev */ namespace detail { struct ScopedFILE { FILE *file; inline ScopedFILE(const char *filename, const char *access) // NOLINT { file = std::fopen(filename, access); // NOLINT if(file == nullptr) RYML_ERR_BASIC_("{}: could not open file", filename); } inline ~ScopedFILE() noexcept // NOLINT { std::fclose(file); // NOLINT } ScopedFILE(const ScopedFILE&) = delete; ScopedFILE( ScopedFILE&&) = delete; ScopedFILE& operator=(const ScopedFILE&) = delete; ScopedFILE& operator=( ScopedFILE&&) = delete; }; } // detail /** @endcond */ //----------------------------------------------------------------------------- /** @defgroup doc_file_put_contents file_put_contents() * * Save a buffer to disk * * @ingroup doc_file_utils * * @addtogroup doc_file_put_contents * @{ */ /** save a contiguous buffer into a file */ inline void file_put_contents(void const* buf, size_t sz, FILE *file, const char* filename=nullptr) { size_t written = std::fwrite(buf, 1, sz, file); // NOLINT if C4_UNLIKELY(written != sz) RYML_ERR_BASIC_("{}: failed file write: expected={}B actual={}B", filename ? filename : "file", sz, written); // LCOV_EXCL_LINE } /** save a contiguous buffer into a file */ template void file_put_contents(ContiguousContainer const& v, FILE *file, const char *filename=nullptr) { size_t vsz = static_cast(v.size()) * sizeof(typename ContiguousContainer::value_type); void const* vbuf = v.empty() ? nullptr : &v[0]; file_put_contents(vbuf, vsz, file, filename); } /** save a contiguous buffer into a file */ inline void file_put_contents(void const* buf, size_t sz, const char *filename, const char* access="wb") { detail::ScopedFILE f(filename, access); file_put_contents(buf, sz, f.file, filename); } /** save a contiguous buffer into a file */ template void file_put_contents(ContiguousContainer const& v, const char *filename, const char* access="wb") { size_t vsz = static_cast(v.size()) * sizeof(typename ContiguousContainer::value_type); void const* vbuf = v.empty() ? nullptr : &v[0]; file_put_contents(vbuf, vsz, filename, access); } /** @} */ //----------------------------------------------------------------------------- /** @defgroup doc_file_get_contents file_get_contents() * * Load a file from disk into a buffer. * * @ingroup doc_file_utils * * @addtogroup doc_file_get_contents * @{ */ /** load a file of specified size from disk into an existing contiguous buffer. */ inline void file_get_contents(const char *filename, FILE *fp, size_t filesz, void *buf, size_t bufsz) { RYML_ASSERT_BASIC_(filesz <= bufsz);(void)bufsz; size_t read = std::fread(buf, 1, filesz, fp); // NOLINT(clang-analyzer-unix.Errno) if C4_UNLIKELY(read != filesz) RYML_ERR_BASIC_("{}: failed file read: expected={}B actual={}B", filename, filesz, read); // LCOV_EXCL_LINE } /** load a file from disk into an existing contiguous buffer. * * @return true if the file was successfully read and the buffer was * large enough to fit the file size */ C4_NODISCARD inline size_t file_get_contents(const char *filename, FILE *fp, void *buf, size_t bufsz) { std::fseek(fp, 0, SEEK_END); // NOLINT size_t filesz = static_cast(std::ftell(fp)); // NOLINT std::rewind(fp); // NOLINT if(filesz <= bufsz) file_get_contents(filename, fp, filesz, buf, bufsz); return filesz; } /** load a file from disk into an existing contiguous buffer. * * @return the size required for the buffer. It is up to the caller to * check that the returned size is smaller than the buffer's size. */ C4_NODISCARD inline size_t file_get_contents(const char *filename, void *buf, size_t bufsz, const char *access="rb") { detail::ScopedFILE f(filename, access); return file_get_contents(filename, f.file, buf, bufsz); } /** load a file from disk into an existing ContiguousContainer, * resizing it to fit the file's contents */ template void file_get_contents(ContiguousContainer *v, const char *filename, const char *access="rb") { using value_type = typename ContiguousContainer::value_type; using size_type = typename ContiguousContainer::size_type; detail::ScopedFILE f(filename, access); void * dat = !v->empty() ? &(*v)[0] : nullptr; size_t vsz = static_cast(v->size()); size_t fsz = file_get_contents(filename, f.file, dat, vsz); size_t num_elms = fsz / sizeof(value_type); if C4_UNLIKELY(fsz != num_elms * sizeof(value_type)) RYML_ERR_BASIC_("{}: file size ({}B) not a multiple of element size ({}B)", filename, fsz, sizeof(value_type)); v->resize(static_cast(num_elms)); if(fsz > vsz * sizeof(value_type)) file_get_contents(filename, f.file, fsz, &(*v)[0], fsz); } /** load a file from disk and return a newly created * ContiguousContainer with the file contents */ template ContiguousContainer file_get_contents(const char *filename, const char *access="rb") { ContiguousContainer cc; file_get_contents(&cc, filename, access); return cc; } /** @} */ //----------------------------------------------------------------------------- /** @defgroup doc_stdin_get_contents stdin_get_contents() * * Load a file from stdin (or similar stream-like file) into a buffer. * * @ingroup doc_file_utils * * @addtogroup doc_stdin_get_contents * @{ */ /** load a file from stdin (or similar stream-like file) and * return a newly created ContiguousContainer with the file * contents */ template void stdin_get_contents(ContiguousContainer *cont, FILE *f=stdin) { using I = typename ContiguousContainer::size_type; using T = typename ContiguousContainer::value_type; int c; I pos = 0; I num_bytes = 128; I elmsz = static_cast(sizeof(T)); I sz = (num_bytes + elmsz - 1) / elmsz; // round up to next multiple of elmsz num_bytes = sz * elmsz; cont->resize(sz); unsigned char *buf = reinterpret_cast(&(*cont)[0]); // NOLINT while((c = fgetc(f)) != EOF) { if(pos == num_bytes) { num_bytes = 2 * num_bytes; if(num_bytes % sizeof(T)) goto errsize; // NOLINT // LCOV_EXCL_LINE cont->resize(num_bytes / sizeof(T)); buf = reinterpret_cast(&(*cont)[0]); // NOLINT } buf[pos++] = static_cast(c); } if(pos % sizeof(T)) goto errsize; // NOLINT cont->resize(pos / sizeof(T)); return; errsize: RYML_ERR_BASIC_("file size is not multiple of element size"); } /** load a file from stdin and return a newly created * ContiguousContainer with the file contents */ template ContiguousContainer stdin_get_contents(FILE *f=stdin) { ContiguousContainer cc; stdin_get_contents(&cc, f); return cc; } /** @} */ C4_SUPPRESS_WARNING_CLANG_POP C4_SUPPRESS_WARNING_MSVC_POP } // namespace yml } // namespace c4 #endif /* C4_YML_FILE_HPP_ */ // (end src/c4/yml/file.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/tag.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_TAG_HPP_ #define C4_YML_TAG_HPP_ #ifndef C4_YML_COMMON_HPP_ //#include // amalgamate: remove include #error "amalgamate: c4/yml/common.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_DETAIL_STACK_HPP_ //#include // amalgamate: remove include #error "amalgamate: c4/yml/detail/stack.hpp must have been amalgamated before this point" #endif namespace c4 { namespace yml { C4_SUPPRESS_WARNING_MSVC_WITH_PUSH(4251) // csubstr needs to have dll-interface to be used by clients of LookupResult class Tree; /** @addtogroup doc_tag_utils * * @{ */ #ifndef RYML_MAX_TAG_DIRECTIVES /** the maximum number of tag directives in a Tree */ #define RYML_MAX_TAG_DIRECTIVES 4 #endif /** the integral type necessary to cover all the bits marking node tags */ using tag_bits = uint16_t; /** a bit mask for marking tags for types */ typedef enum : tag_bits { // NOLINT TAG_NONE = 0, // container types TAG_MAP = 1, /**< !!map Unordered set of key: value pairs without duplicates. @see https://yaml.org/type/map.html */ TAG_OMAP = 2, /**< !!omap Ordered sequence of key: value pairs without duplicates. @see https://yaml.org/type/omap.html */ TAG_PAIRS = 3, /**< !!pairs Ordered sequence of key: value pairs allowing duplicates. @see https://yaml.org/type/pairs.html */ TAG_SET = 4, /**< !!set Unordered set of non-equal values. @see https://yaml.org/type/set.html */ TAG_SEQ = 5, /**< !!seq Sequence of arbitrary values. @see https://yaml.org/type/seq.html */ // scalar types TAG_BINARY = 6, /**< !!binary A sequence of zero or more octets (8 bit values). @see https://yaml.org/type/binary.html */ TAG_BOOL = 7, /**< !!bool Mathematical Booleans. @see https://yaml.org/type/bool.html */ TAG_FLOAT = 8, /**< !!float Floating-point approximation to real numbers. https://yaml.org/type/float.html */ TAG_INT = 9, /**< !!float Mathematical integers. https://yaml.org/type/int.html */ TAG_MERGE = 10, /**< !!merge Specify one or more mapping to be merged with the current one. https://yaml.org/type/merge.html */ TAG_NULL = 11, /**< !!null Devoid of value. https://yaml.org/type/null.html */ TAG_STR = 12, /**< !!str A sequence of zero or more Unicode characters. https://yaml.org/type/str.html */ TAG_TIMESTAMP = 13, /**< !!timestamp A point in time https://yaml.org/type/timestamp.html */ TAG_VALUE = 14, /**< !!value Specify the default value of a mapping https://yaml.org/type/value.html */ TAG_YAML = 15, /**< !!yaml Specify the default value of a mapping https://yaml.org/type/yaml.html */ } YamlTag_e; RYML_EXPORT YamlTag_e to_tag(csubstr tag); RYML_EXPORT csubstr from_tag(YamlTag_e tag); RYML_EXPORT csubstr from_tag_long(YamlTag_e tag); RYML_EXPORT csubstr normalize_tag(csubstr tag); RYML_EXPORT csubstr normalize_tag_long(csubstr tag); RYML_EXPORT csubstr normalize_tag_long(csubstr tag, substr output); /** is a tag of the form `!handle!tag`? */ RYML_EXPORT bool is_custom_tag(csubstr tag); RYML_EXPORT bool is_valid_tag_handle(csubstr handle); //----------------------------------------------------------------------------- /** Accelerator structure to reduce memory requirements by enabling * reuse of resolved tags. */ struct TagCache { struct Entry { csubstr tag; csubstr resolved; id_type doc_id; }; using Entries = detail::stack; using const_iterator = id_type; struct RYML_EXPORT LookupResult { csubstr resolved; const_iterator pos; operator bool() const noexcept { return resolved.len > 0; } }; public: TagCache() noexcept : m_entries() {} RYML_EXPORT LookupResult find(csubstr tag, id_type doc_id, id_type linear_threshold=Entries::sso_size) const noexcept; RYML_EXPORT void add(csubstr tag, csubstr resolved, id_type doc_id, const_iterator pos) RYML_NOEXCEPT; void clear() noexcept { m_entries.clear(); } public: /** @cond dev */ Entries m_entries; /** @endcond */ }; //----------------------------------------------------------------------------- struct RYML_EXPORT TagDirective { /** Eg
!e!
in
%TAG !e! tag:example.com,2000:app/
*/ csubstr handle; /** Eg
tag:example.com,2000:app/
in
%TAG !e! tag:example.com,2000:app/
*/ csubstr prefix; /** ID of the target document */ id_type doc_id; }; struct RYML_EXPORT TagDirectiveRange { TagDirective const* C4_RESTRICT b; TagDirective const* C4_RESTRICT e; C4_ALWAYS_INLINE TagDirective const* begin() const noexcept { return b; } C4_ALWAYS_INLINE TagDirective const* end() const noexcept { return e; } id_type size() const noexcept { return static_cast(e - b); } }; struct RYML_EXPORT TagDirectives { TagDirective m_directives[RYML_MAX_TAG_DIRECTIVES]; bool redefines_qmrk() const noexcept; TagDirective const* add(csubstr handle, csubstr prefix, id_type doc_id) noexcept; void clear() noexcept; id_type size() const noexcept; TagDirective const* lookup(csubstr tag, id_type id) const noexcept; TagDirective * begin() noexcept { return m_directives; } TagDirective * end() noexcept { return m_directives + size(); } TagDirective const* begin() const noexcept { return m_directives; } TagDirective const* end() const noexcept { return m_directives + size(); } TagDirectiveRange directives() const noexcept { return TagDirectiveRange{m_directives, m_directives + size()}; } TagDirectiveRange lookup_range(id_type doc_id) const noexcept; /** @note the str member of the return value may be null, meaning * that the buffer was not enough to fit the transformed tag. * * @note the return value may actually be not a substring of the * input buffer. */ csubstr resolve(substr buf, size_t *bufsz, csubstr tag, id_type doc_id, Location const& ymlloc, Callbacks const& callbacks, bool with_brackets=true) const; }; /** returns the length of the transformed tag, or 0 to signal that the * tag is local and cannot be resolved */ RYML_EXPORT size_t transform_tag(substr output, csubstr handle, csubstr prefix, csubstr tag, Callbacks const& callbacks, Location const& ymlloc={}, bool with_brackets=true); /** @} */ C4_SUPPRESS_WARNING_MSVC_POP } // namespace yml } // namespace c4 #endif /* C4_YML_TAG_HPP_ */ // (end src/c4/yml/tag.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/scalar_charconv.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_SCALAR_CHARCONV_HPP_ #define C4_YML_SCALAR_CHARCONV_HPP_ /** @file scalar_charconv.hpp */ #ifndef C4_YML_COMMON_HPP_ //#include "c4/yml/common.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/common.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_ERROR_HPP_ //#include "c4/yml/error.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/error.hpp must have been amalgamated before this point" #endif #ifndef C4_CHARCONV_HPP_ //#include // amalgamate: remove include #error "amalgamate: c4/charconv.hpp must have been amalgamated before this point" #endif namespace c4 { namespace yml { /** @addtogroup doc_scalar_charconv * * @{ */ /** YAML-sense query of nullity. returns true if the scalar points * to `nullptr` or is otherwise equal to one of the strings * `"~"`,`"null"`,`"Null"`,`"NULL"` */ inline bool scalar_is_null(csubstr s) noexcept { return s.str == nullptr || (s.len == 1 && (s.str[0] == '~')) || (s.len == 4 && ((0 == memcmp("null", s.str, 4)) || (0 == memcmp("Null", s.str, 4)) || (0 == memcmp("NULL", s.str, 4)))); } /** JSON-sense query of plain number */ inline bool scalar_is_plain_number_json(csubstr s) noexcept { return s.is_number() && ( // quote integral numbers if they have a leading 0 // https://github.com/biojppm/rapidyaml/issues/291 (!(s.len > 1 && s.begins_with('0'))) // do not quote reals with leading 0 // https://github.com/biojppm/rapidyaml/issues/313 || (s.find('.') != csubstr::npos) ); } /** Query if a scalar is inf (inf, Inf, INF) * @warning length must be 3 */ inline bool scalar_is_inf3(const char *C4_RESTRICT s) noexcept { switch(s[0]) { case 'i': return ((s[1] == 'n') && (s[2] == 'f')); case 'I': return ((s[1] == 'n') && (s[2] == 'f')) || ((s[1] == 'N') && (s[2] == 'F')); } return false; } /** Query if a scalar is nan (nan, NaN, Nan, NAN) * @warning length must be 3 */ inline bool scalar_is_nan3(const char *C4_RESTRICT s) noexcept { switch(s[0]) { case 'n': return ((s[1] == 'a') && (s[2] == 'n')); case 'N': return ((s[1] == 'a') && (s[2] == 'N')) || ((s[1] == 'a') && (s[2] == 'n')) || ((s[1] == 'A') && (s[2] == 'N')); } return false; } /** Same as scalar_is_inf3() || scalar_is_nan3() * @warning length must be 3 */ inline bool scalar_is_inf_or_nan3(const char *C4_RESTRICT s) noexcept { switch(s[0]) { case 'i': return ((s[1] == 'n') && (s[2] == 'f')); case 'I': return ((s[1] == 'n') && (s[2] == 'f')) || ((s[1] == 'N') && (s[2] == 'F')); case 'n': return ((s[1] == 'a') && (s[2] == 'n')); case 'N': return ((s[1] == 'a') && (s[2] == 'N')) || ((s[1] == 'a') && (s[2] == 'n')) || ((s[1] == 'A') && (s[2] == 'N')); } return false; } /** Query if a scalar is plain, eg, true, false, null, +-.inf or .nan */ inline bool scalar_is_special_json(csubstr s) noexcept { if(s.len == 4) return 0 == memcmp("true", s.str, 4) || 0 == memcmp("null", s.str, 4) || ((s[0] == '.') && scalar_is_inf_or_nan3(s.str + 1)) || ((s[0] == '-' || s[0] == '+') && scalar_is_inf3(s.str + 1)); else if(s.len == 5) return 0 == memcmp("false", s.str, 5) || ((s[0] == '-' || s[0] == '+') && s[1] == '.' && scalar_is_inf3(s.str + 2)); else if(s.len == 3) return scalar_is_inf_or_nan3(s.str); return false; } //----------------------------------------------------------------------------- /** @cond dev */ namespace detail { template C4_NODISCARD C4_NO_INLINE bool from_chars_float_yaml_special(csubstr buf, T *C4_RESTRICT val) RYML_NOEXCEPT { static_assert(std::is_floating_point::value, "must be floating point"); RYML_ASSERT_BASIC_(buf.len); RYML_ASSERT_BASIC_(!buf.begins_with('+')); switch(buf.str[0]) { case '.': if(buf.len == 4) { if(scalar_is_nan3(buf.str + 1)) { *val = std::numeric_limits::quiet_NaN(); goto ok; // NOLINT } else if(scalar_is_inf3(buf.str + 1)) { *val = std::numeric_limits::infinity(); goto ok; // NOLINT } } break; case '-': if(buf.len == 5 && buf.str[1] == '.' && scalar_is_inf3(buf.str + 2)) { *val = -std::numeric_limits::infinity(); goto ok; // NOLINT } } return false; ok: return true; } } // namespace detail /** @endcond */ /** Deserialize a floating point from string. Accepts special values: * .nan, .inf, -.inf, with upper-case variations. * * Unlike non-floating types, only the leading part of the string that * may constitute a number is processed. This happens because the * float parsing is delegated to fast_float, which is implemented that * way. Consequently, for example, all of `"34"`, `"34 "` `"34hg"` * `"34 gh"` will be read as 34. If you are not sure about the * contents of the data, you can use @ref csubstr::first_real_span() to * check before deserializing, for example like this: * * @code{c++} * csubstr val = node.val(); * if(val.first_real_span() == val) * node >> v; // or call from_chars_float(val, &v); * else * ERROR("not a real") * @endcode */ template C4_NODISCARD bool from_chars_float(csubstr scalar, T *C4_RESTRICT val) RYML_NOEXCEPT { static_assert(std::is_floating_point::value, "must be floating point"); if C4_LIKELY(scalar.len > 0) { if(scalar.str[0] == '+') scalar = scalar.sub(1); if C4_LIKELY(from_chars(scalar, val)) return true; else if(scalar.len == 4 || scalar.len == 5) return detail::from_chars_float_yaml_special(scalar, val); } return false; } /** Serialize a floating point value to a string. */ template size_t to_chars_float(substr buf, T val) RYML_NOEXCEPT { static_assert(std::is_floating_point::value, "must be floating point"); C4_SUPPRESS_WARNING_GCC_CLANG_WITH_PUSH("-Wfloat-equal"); if C4_UNLIKELY(std::isnan(val)) return to_chars(buf, csubstr(".nan")); else if C4_UNLIKELY(val == std::numeric_limits::infinity()) return to_chars(buf, csubstr(".inf")); else if C4_UNLIKELY(val == -std::numeric_limits::infinity()) return to_chars(buf, csubstr("-.inf")); return to_chars(buf, val); C4_SUPPRESS_WARNING_GCC_CLANG_POP } //----------------------------------------------------------------------------- /** Deserialize an integral scalar. Trims leading `+`, and then * dispatches to @ref from_chars(). The full string is used. * * @note Unlike with the floating case (see @ref to_chars_float()), * there is no need for an analogous `to_chars_integral()`, because * the lower-level @ref atoi() and @ref atou() functions used by @ref * to_chars() do not produce leading `+` characters. */ template C4_NODISCARD C4_ALWAYS_INLINE bool from_chars_integral(csubstr scalar, T *val) RYML_NOEXCEPT { if C4_LIKELY(scalar.len > 0) { if(scalar.str[0] == '+') scalar = scalar.sub(1); return from_chars(scalar, val); } return false; } //----------------------------------------------------------------------------- // scalar_deserialize #if (C4_CPP >= 17) || defined(__DOXYGEN__) /** Deserialize a scalar from its string representation, dispatching * to one of @ref from_chars(), @ref from_chars_float() or @ref * from_chars_integral() as appropriate. * * @note When using a standard older than C++17, `if constexpr` is not * available, and the implementation reverts to SFINAE to achieve the * compile-time dispatch. * * @return true if the deserialization succeeded */ template C4_NODISCARD C4_ALWAYS_INLINE bool scalar_deserialize(csubstr str, T *val) { if constexpr (std::is_floating_point::value) return from_chars_float(str, val); else if constexpr (std::is_arithmetic::value) return from_chars_integral(str, val); else return from_chars(str, val); } #else // pre-C++17 implementation: need to use SFINAE // float template C4_NODISCARD C4_ALWAYS_INLINE auto scalar_deserialize(csubstr str, T *val) RYML_NOEXCEPT -> typename std::enable_if::value, bool>::type { return from_chars_float(str, val); } // integral template C4_NODISCARD C4_ALWAYS_INLINE auto scalar_deserialize(csubstr str, T *val) RYML_NOEXCEPT -> typename std::enable_if::value && !std::is_floating_point::value, bool>::type { return from_chars_integral(str, val); } // other types template C4_NODISCARD C4_ALWAYS_INLINE auto scalar_deserialize(csubstr str, T *val) -> typename std::enable_if::value && !std::is_floating_point::value, bool>::type { return from_chars(str, val); } #endif // pre-C++17 implementation //----------------------------------------------------------------------------- // scalar_serialize #if (C4_CPP >= 17) || defined(__DOXYGEN__) /** Serialize a scalar to the buffer, dispatching to @ref to_chars() or * @ref to_chars_float() as appropriate. * * @note When using a standard older than C++17, `if constexpr` is not * available, and the implementation reverts to SFINAE to achieve the * compile-time dispatch. * * @return the size of the serialization, (the buffer size is strictly * respected and never overflowed) */ template C4_ALWAYS_INLINE size_t scalar_serialize(substr buf, T const& C4_RESTRICT a) { if constexpr (std::is_floating_point::value) return to_chars_float(buf, a); else return to_chars(buf, a); } #else // pre-C++17 implementation: need to use SFINAE // float template C4_ALWAYS_INLINE auto scalar_serialize(substr buf, T const& C4_RESTRICT a) RYML_NOEXCEPT -> typename std::enable_if::value, size_t>::type { return to_chars_float(buf, a); } // other scalar types template C4_ALWAYS_INLINE auto scalar_serialize(substr buf, T const& C4_RESTRICT a) -> typename std::enable_if< ! std::is_floating_point::value, size_t>::type { return to_chars(buf, a); } #endif // pre-C++17 implementation /** @} */ } // namespace yml } // namespace c4 #endif /* C4_YML_SCALAR_CHARCONV_HPP_ */ // (end src/c4/yml/scalar_charconv.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/tree.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_TREE_HPP_ #define C4_YML_TREE_HPP_ /** @file tree.hpp */ #ifndef C4_ERROR_HPP_ //#include "c4/error.hpp" // amalgamate: remove include #error "amalgamate: c4/error.hpp must have been amalgamated before this point" #endif #ifndef C4_LANGUAGE_HPP_ //#include "c4/language.hpp" // amalgamate: remove include #error "amalgamate: c4/language.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_FWD_HPP_ //#include "c4/yml/fwd.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/fwd.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_COMMON_HPP_ //#include "c4/yml/common.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/common.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_NODE_TYPE_HPP_ //#include "c4/yml/node_type.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/node_type.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_TAG_HPP_ //#include "c4/yml/tag.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/tag.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_ERROR_HPP_ //#include "c4/yml/error.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/error.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_SCALAR_CHARCONV_HPP_ //#include "c4/yml/scalar_charconv.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/scalar_charconv.hpp must have been amalgamated before this point" #endif //#include // amalgamate: included above //#include // amalgamate: included above C4_SUPPRESS_WARNING_PUSH C4_SUPPRESS_WARNING_GCC("-Wtype-limits") C4_SUPPRESS_WARNING_GCC("-Wuseless-cast") C4_SUPPRESS_WARNING_GCC_CLANG("-Wold-style-cast") #if defined(__GNUC__) && (__GNUC__ >= 6) C4_SUPPRESS_WARNING_GCC("-Wnull-dereference") #endif C4_SUPPRESS_WARNING_CLANG("-Wnull-dereference") C4_SUPPRESS_WARNING_CLANG("-Wtautological-compare") C4_SUPPRESS_WARNING_MSVC(4127) // conditional expression is constant C4_SUPPRESS_WARNING_MSVC(4296) // expression is always 'boolean_value' C4_SUPPRESS_WARNING_MSVC(4251) // needs to have dll-interface // NOLINTBEGIN(modernize-avoid-c-style-cast) namespace c4 { namespace yml { /** @cond dev */ template using _is_string_nocvref = is_string::type>; /** @endcond */ /** @addtogroup doc_serialization_tree_write_arena * * @{ */ /** Serialize a scalar to the tree's arena. This is an implementation * helper for @ref serialize_to_arena(), serializing through * @ref scalar_serialize(). */ template csubstr serialize_to_arena_scalar(Tree * tree, T const& scalar); /** Serialize a string type (as specified by @ref c4::is_string) to a * tree's arena, ensuring that there is an entry for the string in the * arena even if the string is empty. This is an implementation helper * for @ref serialize_to_arena(), serializing through @ref * scalar_serialize() and then ensuring that the serialized string * will be placed in the arena, even if the string is zero-length. */ RYML_EXPORT csubstr serialize_to_arena_str(Tree * tree, csubstr scalar); #if (C4_CPP >= 17) || defined(__DOXYGEN__) /** Serialize a scalar to a tree's arena, dispatching to either @ref * serialize_to_arena_scalar() or @ref serialize_to_arena_str() when * the type is a string according to @ref c4::is_string. This is the * entry point for customizing how a scalar is serialized to a tree's * arena. It is never needed for the user to call this function, and * generally there is no reason for overriding this function for user * types, unless it has specific requirements for the tree's arena, as * happens for example with string types. For user string types, * defining @ref c4::is_string is enough. For example: * * @note When using a standard older than C++17, `if constexpr` is not * available, and the implementation reverts to SFINAE to achieve the * compile-time dispatch. * * @code{c++} * namespace foo { * class MyStringType {...}; // an example of a user-defined string type * // define conversion to/from substrings * c4::yml::csubstr to_csubstr(MyStringType const& s) { return ...; } * c4::yml::substr to_substr(MyStringType & s) { return ...; } * } // namespace foo * // tell ryml to treat this type as a string * template<> struct c4::is_string : std::true_type {}; * @endcode */ template C4_ALWAYS_INLINE csubstr serialize_to_arena(Tree * tree, T const& scalar) { if constexpr (_is_string_nocvref::value) return serialize_to_arena_str(tree, to_csubstr(scalar)); else return serialize_to_arena_scalar(tree, scalar); } #else // pre-C++17: need to use SFINAE template C4_ALWAYS_INLINE auto serialize_to_arena(Tree * tree, T const& scalar) -> typename std::enable_if<_is_string_nocvref::value, csubstr>::type { return serialize_to_arena_str(tree, to_csubstr(scalar)); } template C4_ALWAYS_INLINE auto serialize_to_arena(Tree * tree, T const& scalar) -> typename std::enable_if< ! _is_string_nocvref::value, csubstr>::type { return serialize_to_arena_scalar(tree, scalar); } #endif // pre-C++17: need to use SFINAE /** implementation for null values */ C4_ALWAYS_INLINE csubstr serialize_to_arena(Tree * C4_RESTRICT, std::nullptr_t /*scalar*/) noexcept { return csubstr{}; } /** @} */ //----------------------------------------------------------------------------- // fwd decl: write/read, write_key/read_key /** @cond dev */ template void write(Tree * tree, id_type id, T const& v); template void write_key(Tree *, id_type id, T const& v); template C4_NODISCARD C4_ALWAYS_INLINE ReadResult read(Tree const* tree, id_type id, T * v); template C4_NODISCARD C4_ALWAYS_INLINE ReadResult read_key(Tree const* tree, id_type id, T * v); template C4_NODISCARD C4_ALWAYS_INLINE ReadResult read(Tree const* tree, id_type id, Wrapper const& w); template C4_NODISCARD C4_ALWAYS_INLINE ReadResult read_key(Tree const* tree, id_type id, Wrapper const& w); /** @endcond */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @addtogroup doc_tree * * @{ */ /** a node scalar is a csubstr, which may be tagged and anchored. */ struct NodeScalar { csubstr tag; csubstr scalar; csubstr anchor; public: /// initialize as an empty scalar NodeScalar() noexcept : tag(), scalar(), anchor() {} // NOLINT /// initialize as an untagged scalar template NodeScalar(const char (&s)[N]) noexcept : tag(), scalar(s), anchor() {} NodeScalar(csubstr s ) noexcept : tag(), scalar(s), anchor() {} /// initialize as a tagged scalar template NodeScalar(const char (&t)[N], const char (&s)[N]) noexcept : tag(t), scalar(s), anchor() {} NodeScalar(csubstr t , csubstr s ) noexcept : tag(t), scalar(s), anchor() {} public: ~NodeScalar() noexcept = default; NodeScalar(NodeScalar &&) noexcept = default; NodeScalar(NodeScalar const&) noexcept = default; NodeScalar& operator= (NodeScalar &&) noexcept = default; NodeScalar& operator= (NodeScalar const&) noexcept = default; public: bool empty() const noexcept { return tag.empty() && scalar.empty() && anchor.empty(); } void clear() noexcept { tag.clear(); scalar.clear(); anchor.clear(); } void set_ref_maybe_replacing_scalar(csubstr ref, bool has_scalar) RYML_NOEXCEPT { csubstr trimmed = ref.begins_with('*') ? ref.sub(1) : ref; anchor = trimmed; if((!has_scalar) || !scalar.ends_with(trimmed)) scalar = ref; } }; static_assert(std::is_trivially_copyable::value, "must be trivially copyable"); //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @cond dev */ // LCOV_EXCL_START struct RYML_DEPRECATED("") NodeInit { NodeType type; NodeScalar key; NodeScalar val; public: /// initialize as an empty node NodeInit() : type(NOTYPE), key(), val() {} /// initialize as a typed node NodeInit(type_bits t) : type(t), key(), val() {} /// initialize as a sequence member NodeInit(NodeScalar const& v) : type(VAL), key(), val(v) { _add_flags(); } /// initialize as a sequence member with explicit type NodeInit(NodeScalar const& v, type_bits t) : type(t|VAL), key(), val(v) { _add_flags(); } /// initialize as a mapping member NodeInit( NodeScalar const& k, NodeScalar const& v) : type(KEYVAL), key(k), val(v) { _add_flags(); } /// initialize as a mapping member with explicit type NodeInit(type_bits t, NodeScalar const& k, NodeScalar const& v) : type(t), key(k), val(v) { _add_flags(); } /// initialize as a mapping member with explicit type (eg for SEQ or MAP) NodeInit(type_bits t, NodeScalar const& k ) : type(t), key(k), val( ) { _add_flags(KEY); } public: void clear() { type.clear(); key.clear(); val.clear(); } void _add_flags(type_bits more_flags=0) { type = (type.m_bits|more_flags); if( ! key.tag.empty()) type = (type.m_bits|KEYTAG); if( ! val.tag.empty()) type = (type.m_bits|VALTAG); if( ! key.anchor.empty()) type = (type.m_bits|KEYANCH); if( ! val.anchor.empty()) type = (type.m_bits|VALANCH); } bool _check() const { // key cannot be empty RYML_ASSERT_BASIC_(key.scalar.empty() == ((type & KEY) == 0)); // key tag cannot be empty RYML_ASSERT_BASIC_(key.tag.empty() == ((type & KEYTAG) == 0)); // val may be empty even though VAL is set. But when VAL is not set, val must be empty RYML_ASSERT_BASIC_(((type & VAL) != 0) || val.scalar.empty()); // val tag cannot be empty RYML_ASSERT_BASIC_(val.tag.empty() == ((type & VALTAG) == 0)); return true; } }; /** @endcond */ // LCOV_EXCL_STOP //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** contains the data for each YAML node. */ struct NodeData { NodeType m_type; NodeScalar m_key; NodeScalar m_val; id_type m_parent; id_type m_first_child; id_type m_last_child; id_type m_next_sibling; id_type m_prev_sibling; }; static_assert(std::is_trivially_copyable::value, "must be trivially copyable"); //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- class RYML_EXPORT Tree { public: /** @name construction and assignment */ /** @{ */ Tree() : Tree(get_callbacks()) {} Tree(Callbacks const& cb); Tree(id_type node_capacity, size_t arena_capacity=RYML_DEFAULT_TREE_ARENA_CAPACITY) : Tree(node_capacity, arena_capacity, get_callbacks()) {} Tree(id_type node_capacity, size_t arena_capacity, Callbacks const& cb); ~Tree() noexcept; Tree(Tree const& that); Tree(Tree && that) noexcept; Tree& operator= (Tree const& that); Tree& operator= (Tree && that) noexcept; /** @} */ public: /** @name memory and sizing */ /** @{ */ void reserve(id_type node_capacity=RYML_DEFAULT_TREE_CAPACITY); /** clear the tree and zero every node * @note does NOT clear the arena * @see clear_arena() */ void clear(); void clear_arena() { m_arena_pos = 0; } /** Query for zero size. The tree can be empty only when constructed with explicitly zero-capacity. */ bool empty() const { return m_size == 0; } id_type size() const { return m_size; } id_type capacity() const { return m_cap; } id_type slack() const { RYML_ASSERT_BASIC_(m_cap >= m_size); return m_cap - m_size; } Callbacks const& callbacks() const { return m_callbacks; } void callbacks(Callbacks const& cb) { m_callbacks = cb; } /** @} */ public: /** @name node getters */ /** @{ */ //! get a pointer to a node's NodeData. //! node can be NONE, in which case a nullptr is returned NodeData *get(id_type node) // NOLINT(readability-make-member-function-const) { if(node == NONE) return nullptr; RYML_ASSERT_VISIT_CB_(m_callbacks, node >= 0 && node < m_cap, this, node); return m_buf + node; } //! get a pointer to a node's NodeData. //! node can be NONE, in which case a nullptr is returned. NodeData const *get(id_type node) const { if(node == NONE) return nullptr; RYML_ASSERT_VISIT_CB_(m_callbacks, node >= 0 && node < m_cap, this, node); return m_buf + node; } //! An if-less form of get() that demands a valid node index. //! This function is implementation only; use at your own risk. NodeData * _p(id_type node) { RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE && node >= 0 && node < m_cap, this, node); return m_buf + node; } // NOLINT(readability-make-member-function-const) //! An if-less form of get() that demands a valid node index. //! This function is implementation only; use at your own risk. NodeData const * _p(id_type node) const { RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE && node >= 0 && node < m_cap, this, node); return m_buf + node; } //! Get the id of the root node. The tree must not be empty. The tree can be empty only when constructed with explicitly zero-capacity. id_type root_id() const { RYML_ASSERT_VISIT_CB_(m_callbacks, m_size > 0, this, id_type(0)); return 0; } //! Get the id of the root node, or NONE if the tree is empty. id_type root_id_maybe() const { return m_size ? 0 : id_type(NONE); } //! get the id of a node belonging to this tree. //! @p n can be nullptr, in which case NONE is returned //! @p n must belong to this tree id_type id(NodeData const* n) const { if( ! n) return NONE; RYML_ASSERT_VISIT_CB_(m_callbacks, n >= m_buf && n < m_buf + m_cap, this, NONE); return static_cast(n - m_buf); } /** @} */ public: /** @name NodeRef helpers */ /** @{ */ //! Get a NodeRef of a node by id NodeRef ref(id_type node); //! Get a NodeRef of a node by id ConstNodeRef ref(id_type node) const; //! Get a NodeRef of a node by id ConstNodeRef cref(id_type node) const; //! Get the root as a @ref NodeRef . Note that a non-const Tree implicitly converts to @ref NodeRef. NodeRef rootref(); //! Get the root as a @ref ConstNodeRef . Note that Tree implicitly converts to @ref ConstNodeRef. ConstNodeRef rootref() const; //! Get the root as a @ref ConstNodeRef . Note that Tree implicitly converts to @ref ConstNodeRef. ConstNodeRef crootref() const; //! get the i-th document of the stream //! @note @p i is NOT the node id, but the doc position within the stream NodeRef docref(id_type i); //! get the i-th document of the stream //! @note @p i is NOT the node id, but the doc position within the stream ConstNodeRef docref(id_type i) const; //! get the i-th document of the stream //! @note @p i is NOT the node id, but the doc position within the stream ConstNodeRef cdocref(id_type i) const; //! find a root child (ie child of root) by name, return it as a NodeRef //! @note requires the root to be a map. NodeRef operator[] (csubstr key); //! find a root child (ie child of root) by name, return it as a NodeRef //! @note requires the root to be a map. ConstNodeRef operator[] (csubstr key) const; //! find a root child (ie child of root) by index: return the root node's @p i-th child as a NodeRef //! @note @p i is NOT the node id, but the child's position within the parent NodeRef operator[] (id_type i); //! find a root child (ie child of root) by index: return the root node's @p i-th child as a NodeRef //! @note @p i is NOT the node id, but the child's position within the parent ConstNodeRef operator[] (id_type i) const; /** @} */ public: /** @name node property getters */ /** @{ */ NodeType type(id_type node) const { return _p(node)->m_type; } csubstr const& key (id_type node) const { RYML_ASSERT_VISIT_CB_(m_callbacks, has_key(node), this, node); return _p(node)->m_key.scalar; } csubstr const& key_tag (id_type node) const { RYML_ASSERT_VISIT_CB_(m_callbacks, has_key_tag(node), this, node); return _p(node)->m_key.tag; } csubstr const& key_ref (id_type node) const { RYML_ASSERT_VISIT_CB_(m_callbacks, is_key_ref(node), this, node); return _p(node)->m_key.anchor; } csubstr const& key_anchor(id_type node) const { RYML_ASSERT_VISIT_CB_(m_callbacks, has_key_anchor(node), this, node); return _p(node)->m_key.anchor; } NodeScalar const& keysc (id_type node) const { RYML_ASSERT_VISIT_CB_(m_callbacks, has_key(node), this, node); return _p(node)->m_key; } csubstr const& val (id_type node) const { RYML_ASSERT_VISIT_CB_(m_callbacks, has_val(node), this, node); return _p(node)->m_val.scalar; } csubstr const& val_tag (id_type node) const { RYML_ASSERT_VISIT_CB_(m_callbacks, has_val_tag(node), this, node); return _p(node)->m_val.tag; } csubstr const& val_ref (id_type node) const { RYML_ASSERT_VISIT_CB_(m_callbacks, is_val_ref(node), this, node); return _p(node)->m_val.anchor; } csubstr const& val_anchor(id_type node) const { RYML_ASSERT_VISIT_CB_(m_callbacks, has_val_anchor(node), this, node); return _p(node)->m_val.anchor; } NodeScalar const& valsc (id_type node) const { RYML_ASSERT_VISIT_CB_(m_callbacks, has_val(node), this, node); return _p(node)->m_val; } /** @} */ public: /** @name node type predicates */ /** @{ */ C4_ALWAYS_INLINE bool type_has_any(id_type node, type_bits bits) const { return _p(node)->m_type.has_any(bits); } C4_ALWAYS_INLINE bool type_has_all(id_type node, type_bits bits) const { return _p(node)->m_type.has_all(bits); } C4_ALWAYS_INLINE bool type_has_none(id_type node, type_bits bits) const { return _p(node)->m_type.has_none(bits); } C4_ALWAYS_INLINE bool is_stream(id_type node) const { return _p(node)->m_type.is_stream(); } C4_ALWAYS_INLINE bool is_doc(id_type node) const { return _p(node)->m_type.is_doc(); } C4_ALWAYS_INLINE bool is_container(id_type node) const { return _p(node)->m_type.is_container(); } C4_ALWAYS_INLINE bool is_map(id_type node) const { return _p(node)->m_type.is_map(); } C4_ALWAYS_INLINE bool is_seq(id_type node) const { return _p(node)->m_type.is_seq(); } C4_ALWAYS_INLINE bool has_key(id_type node) const { return _p(node)->m_type.has_key(); } C4_ALWAYS_INLINE bool has_val(id_type node) const { return _p(node)->m_type.has_val(); } C4_ALWAYS_INLINE bool is_val(id_type node) const { return _p(node)->m_type.is_val(); } C4_ALWAYS_INLINE bool is_keyval(id_type node) const { return _p(node)->m_type.is_keyval(); } C4_ALWAYS_INLINE bool has_key_tag(id_type node) const { return _p(node)->m_type.has_key_tag(); } C4_ALWAYS_INLINE bool has_val_tag(id_type node) const { return _p(node)->m_type.has_val_tag(); } C4_ALWAYS_INLINE bool has_key_anchor(id_type node) const { return _p(node)->m_type.has_key_anchor(); } C4_ALWAYS_INLINE bool has_val_anchor(id_type node) const { return _p(node)->m_type.has_val_anchor(); } C4_ALWAYS_INLINE bool has_anchor(id_type node) const { return _p(node)->m_type.has_anchor(); } C4_ALWAYS_INLINE bool is_key_ref(id_type node) const { return _p(node)->m_type.is_key_ref(); } C4_ALWAYS_INLINE bool is_val_ref(id_type node) const { return _p(node)->m_type.is_val_ref(); } C4_ALWAYS_INLINE bool is_ref(id_type node) const { return _p(node)->m_type.is_ref(); } C4_ALWAYS_INLINE bool parent_is_seq(id_type node) const { RYML_ASSERT_VISIT_CB_(m_callbacks, has_parent(node), this, node); return is_seq(_p(node)->m_parent); } C4_ALWAYS_INLINE bool parent_is_map(id_type node) const { RYML_ASSERT_VISIT_CB_(m_callbacks, has_parent(node), this, node); return is_map(_p(node)->m_parent); } /** true when the node has an anchor named a */ C4_ALWAYS_INLINE bool has_anchor(id_type node, csubstr a) const { return _p(node)->m_key.anchor == a || _p(node)->m_val.anchor == a; } /** true if the node key is empty, or its scalar verifies @ref scalar_is_null(). * @warning the node must verify @ref Tree::has_key() (asserted) (ie must be a member of a map) * @see https://github.com/biojppm/rapidyaml/issues/413 */ C4_ALWAYS_INLINE bool key_is_null(id_type node) const { RYML_ASSERT_VISIT_CB_(m_callbacks, has_key(node), this, node); NodeData const* C4_RESTRICT n = _p(node); return !n->m_type.is_key_quoted() && (n->m_type.key_is_null() || scalar_is_null(n->m_key.scalar)); } /** true if the node val is empty, or its scalar verifies @ref scalar_is_null(). * @warning the node must verify @ref Tree::has_val() (asserted) (ie must be a scalar / must not be a container) * @see https://github.com/biojppm/rapidyaml/issues/413 */ C4_ALWAYS_INLINE bool val_is_null(id_type node) const { RYML_ASSERT_VISIT_CB_(m_callbacks, has_val(node), this, node); NodeData const* C4_RESTRICT n = _p(node); return !n->m_type.is_val_quoted() && (n->m_type.val_is_null() || scalar_is_null(n->m_val.scalar)); } /// true if the key was a scalar requiring filtering and was left /// unfiltered during the parsing (see ParserOptions) C4_ALWAYS_INLINE bool is_key_unfiltered(id_type node) const { return _p(node)->m_type.is_key_unfiltered(); } /// true if the val was a scalar requiring filtering and was left /// unfiltered during the parsing (see ParserOptions) C4_ALWAYS_INLINE bool is_val_unfiltered(id_type node) const { return _p(node)->m_type.is_val_unfiltered(); } RYML_DEPRECATED("use has_key_anchor()") bool is_key_anchor(id_type node) const { return _p(node)->m_type.has_key_anchor(); } RYML_DEPRECATED("use has_val_anchor()") bool is_val_anchor(id_type node) const { return _p(node)->m_type.has_val_anchor(); } RYML_DEPRECATED("use has_anchor()") bool is_anchor(id_type node) const { return _p(node)->m_type.has_anchor(); } RYML_DEPRECATED("use has_anchor_or_ref()") bool is_anchor_or_ref(id_type node) const { return _p(node)->m_type.has_anchor() || _p(node)->m_type.is_ref(); } /** @} */ public: /** @name hierarchy predicates */ /** @{ */ bool is_root(id_type node) const { RYML_ASSERT_VISIT_CB_(m_callbacks, _p(node)->m_parent != NONE || node == 0, this, node); return _p(node)->m_parent == NONE; } bool has_parent(id_type node) const { return _p(node)->m_parent != NONE; } /** true when ancestor is parent or parent of a parent of node */ bool is_ancestor(id_type node, id_type ancestor) const; /** true when key and val are empty, and has no children */ bool empty(id_type node) const { return ! has_children(node) && _p(node)->m_key.empty() && (( ! (_p(node)->m_type & VAL)) || _p(node)->m_val.empty()); } /** true if @p node has a child with id @p ch */ bool has_child(id_type node, id_type ch) const { return _p(ch)->m_parent == node; } /** true if @p node has a child with key @p key */ bool has_child(id_type node, csubstr key) const { return find_child(node, key) != NONE; } /** true if @p node has any children */ bool has_children(id_type node) const { return _p(node)->m_first_child != NONE; } /** true if @p node has a sibling with id @p sib */ bool has_sibling(id_type node, id_type sib) const { return _p(node)->m_parent == _p(sib)->m_parent; } /** true if one of the node's siblings has the given key */ bool has_sibling(id_type node, csubstr key) const { return find_sibling(node, key) != NONE; } /** true if node is not a single child */ bool has_other_siblings(id_type node) const { NodeData const *n = _p(node); if C4_LIKELY(n->m_parent != NONE) { n = _p(n->m_parent); return n->m_first_child != n->m_last_child; } return false; } /** @} */ public: /** @name hierarchy getters */ /** @{ */ id_type parent(id_type node) const { return _p(node)->m_parent; } id_type prev_sibling(id_type node) const { return _p(node)->m_prev_sibling; } id_type next_sibling(id_type node) const { return _p(node)->m_next_sibling; } /** O(#num_children) */ id_type num_children(id_type node) const; id_type child_pos(id_type node, id_type ch) const; id_type first_child(id_type node) const { return _p(node)->m_first_child; } id_type last_child(id_type node) const { return _p(node)->m_last_child; } id_type child(id_type node, id_type pos) const; ///< find child by position, or NONE if there are less than pos children posi id_type find_child(id_type node, csubstr const& key) const; ///< find child by name, or NONE if no child is found with this key /// like @ref Tree::child(), but return a @ref ReadResult with the status C4_NODISCARD ReadResult child_r(id_type node, id_type pos, id_type *child_id) const { return ReadResult(node, *child_id = child(node, pos)); } /// like @ref Tree::find_child(), but return a @ref ReadResult with the status C4_NODISCARD ReadResult find_child_r(id_type node, csubstr const& key, id_type *child_id) const { return ReadResult(node, *child_id = find_child(node, key)); } /** O(#num_siblings) */ /** counts with this */ id_type num_siblings(id_type node) const { return is_root(node) ? 1 : num_children(_p(node)->m_parent); } /** does not count with this */ id_type num_other_siblings(id_type node) const { id_type ns = num_siblings(node); RYML_ASSERT_VISIT_CB_(m_callbacks, ns > 0, this, node); return ns-1; } id_type sibling_pos(id_type node, id_type sib) const { RYML_ASSERT_VISIT_CB_(m_callbacks, ! is_root(node) || node == root_id(), this, node); return child_pos(_p(node)->m_parent, sib); } id_type first_sibling(id_type node) const { return is_root(node) ? node : _p(_p(node)->m_parent)->m_first_child; } id_type last_sibling(id_type node) const { return is_root(node) ? node : _p(_p(node)->m_parent)->m_last_child; } id_type sibling(id_type node, id_type pos) const { return child(_p(node)->m_parent, pos); } id_type find_sibling(id_type node, csubstr const& key) const { return find_child(_p(node)->m_parent, key); } /// like @ref Tree::sibling(), but return a @ref ReadResult with the status C4_NODISCARD ReadResult sibling_r(id_type node, id_type pos, id_type *sibling_id) const { return child_r(_p(node)->m_parent, pos, sibling_id); } /// like @ref Tree::find_sibling(), but return a @ref ReadResult if with the status C4_NODISCARD ReadResult find_sibling_r(id_type node, csubstr const& key, id_type *sibling_id) const { return find_child_r(_p(node)->m_parent, key, sibling_id); } id_type depth_asc(id_type node) const; /**< O(log(num_tree_nodes)) get the ascending depth of the node: number of levels between root and node */ id_type depth_desc(id_type node) const; /**< O(num_tree_nodes) get the descending depth of the node: number of levels between node and deepest child */ /** gets the @p i document node index. requires that the root node is a stream. */ id_type doc(id_type i) const { id_type rid = root_id(); RYML_ASSERT_VISIT_CB_(m_callbacks, is_stream(rid), this, rid); return child(rid, i); } /** get the document which is a parent document of node i, or the root if the tree is not a stream */ id_type ancestor_doc(id_type node) const { NodeData const *nd; do { nd = _p(node); if(nd->m_type.is_doc() || nd->m_parent == NONE) break; node = nd->m_parent; } while(nd->m_parent != NONE); return node; } /** @} */ public: /** @name node style predicates and modifiers. see the corresponding predicate in NodeType */ /** @{ */ C4_ALWAYS_INLINE bool is_container_styled(id_type node) const { return _p(node)->m_type.is_container_styled(); } C4_ALWAYS_INLINE bool is_block(id_type node) const { return _p(node)->m_type.is_block(); } C4_ALWAYS_INLINE bool is_flow_sl(id_type node) const { return _p(node)->m_type.is_flow_sl(); } RYML_DEPRECATED("use one of .is_flow_ml{1,n,x}()") C4_ALWAYS_INLINE bool is_flow_ml(id_type node) const { return _p(node)->m_type.is_flow_ml1(); } C4_ALWAYS_INLINE bool is_flow_ml1(id_type node) const { return _p(node)->m_type.is_flow_ml1(); } C4_ALWAYS_INLINE bool is_flow_mln(id_type node) const { return _p(node)->m_type.is_flow_mln(); } C4_ALWAYS_INLINE bool is_flow_mlx(id_type node) const { return _p(node)->m_type.is_flow_mlx(); } C4_ALWAYS_INLINE bool is_flow(id_type node) const { return _p(node)->m_type.is_flow(); } C4_ALWAYS_INLINE bool has_flow_space(id_type node) const { return _p(node)->m_type.has_flow_space(); } C4_ALWAYS_INLINE bool is_key_styled(id_type node) const { return _p(node)->m_type.is_key_styled(); } C4_ALWAYS_INLINE bool is_val_styled(id_type node) const { return _p(node)->m_type.is_val_styled(); } C4_ALWAYS_INLINE bool is_key_literal(id_type node) const { return _p(node)->m_type.is_key_literal(); } C4_ALWAYS_INLINE bool is_val_literal(id_type node) const { return _p(node)->m_type.is_val_literal(); } C4_ALWAYS_INLINE bool is_key_folded(id_type node) const { return _p(node)->m_type.is_key_folded(); } C4_ALWAYS_INLINE bool is_val_folded(id_type node) const { return _p(node)->m_type.is_val_folded(); } C4_ALWAYS_INLINE bool is_key_squo(id_type node) const { return _p(node)->m_type.is_key_squo(); } C4_ALWAYS_INLINE bool is_val_squo(id_type node) const { return _p(node)->m_type.is_val_squo(); } C4_ALWAYS_INLINE bool is_key_dquo(id_type node) const { return _p(node)->m_type.is_key_dquo(); } C4_ALWAYS_INLINE bool is_val_dquo(id_type node) const { return _p(node)->m_type.is_val_dquo(); } C4_ALWAYS_INLINE bool is_key_plain(id_type node) const { return _p(node)->m_type.is_key_plain(); } C4_ALWAYS_INLINE bool is_val_plain(id_type node) const { return _p(node)->m_type.is_val_plain(); } C4_ALWAYS_INLINE bool is_key_quoted(id_type node) const { return _p(node)->m_type.is_key_quoted(); } C4_ALWAYS_INLINE bool is_val_quoted(id_type node) const { return _p(node)->m_type.is_val_quoted(); } C4_ALWAYS_INLINE bool is_quoted(id_type node) const { return _p(node)->m_type.is_quoted(); } C4_ALWAYS_INLINE NodeType key_style(id_type node) const { RYML_ASSERT_VISIT_CB_(m_callbacks, has_key(node), this, node); return _p(node)->m_type.key_style(); } C4_ALWAYS_INLINE NodeType val_style(id_type node) const { RYML_ASSERT_VISIT_CB_(m_callbacks, has_val(node) || is_root(node), this, node); return _p(node)->m_type.val_style(); } C4_ALWAYS_INLINE void set_container_style(id_type node, type_bits style) { RYML_ASSERT_VISIT_CB_(m_callbacks, is_container(node), this, node); _p(node)->m_type.set_container_style(style); } C4_ALWAYS_INLINE void set_key_style(id_type node, type_bits style) { RYML_ASSERT_VISIT_CB_(m_callbacks, has_key(node), this, node); _p(node)->m_type.set_key_style(style); } C4_ALWAYS_INLINE void set_val_style(id_type node, type_bits style) { RYML_ASSERT_VISIT_CB_(m_callbacks, has_val(node), this, node); _p(node)->m_type.set_val_style(style); } void clear_style(id_type node, bool recurse=false); void set_style_conditionally(id_type node, NodeType type_mask, NodeType rem_style_flags, NodeType add_style_flags, bool recurse=false); /** @} */ public: /** @name node type modifiers */ /** @{ */ void set_stream(id_type node) { RYML_ASSERT_VISIT_CB_(m_callbacks, is_root(node), this, node); RYML_ASSERT_VISIT_CB_(m_callbacks, (_p(node)->m_type & (DOC|MAP|VAL)) == 0, this, node); _p(node)->m_type |= STREAM; } void set_doc(id_type node) { RYML_ASSERT_VISIT_CB_(m_callbacks, is_root(node) || (is_root(parent(node)) && is_stream(parent(node))), this, node); _p(node)->m_type |= DOC; } void set_val(id_type node, csubstr val) RYML_NOEXCEPT { RYML_ASSERT_VISIT_CB_(m_callbacks, (_p(node)->m_type & (SEQ|MAP)) == 0, this, node); RYML_ASSERT_VISIT_CB_(m_callbacks, (parent(node) == NONE || (_p(parent(node))->m_type & (SEQ|MAP))), this, node); NodeData *C4_RESTRICT nd = _p(node); nd->m_type |= VAL; nd->m_val.scalar = val; } void set_val(id_type node, csubstr val, NodeType more_flags) RYML_NOEXCEPT { RYML_ASSERT_VISIT_CB_(m_callbacks, (_p(node)->m_type & (SEQ|MAP)) == 0, this, node); RYML_ASSERT_VISIT_CB_(m_callbacks, (parent(node) == NONE || (_p(parent(node))->m_type & (SEQ|MAP))), this, node); NodeData *C4_RESTRICT nd = _p(node); nd->m_type |= VAL|more_flags; nd->m_val.scalar = val; } void set_key(id_type node, csubstr key) RYML_NOEXCEPT { RYML_ASSERT_VISIT_CB_(m_callbacks, (parent(node) != NONE && (_p(parent(node))->m_type & MAP)), this, node); NodeData *C4_RESTRICT nd = _p(node); nd->m_type |= KEY; nd->m_key.scalar = key; } void set_key(id_type node, csubstr key, NodeType more_flags) RYML_NOEXCEPT { RYML_ASSERT_VISIT_CB_(m_callbacks, (parent(node) != NONE && (_p(parent(node))->m_type & MAP)), this, node); NodeData *C4_RESTRICT nd = _p(node); nd->m_type |= KEY|more_flags; nd->m_key.scalar = key; } void set_seq(id_type node) RYML_NOEXCEPT { RYML_ASSERT_VISIT_CB_(m_callbacks, (_p(node)->m_type & (VAL|MAP)) == 0, this, node); _p(node)->m_type |= SEQ; } void set_seq(id_type node, NodeType more_flags) RYML_NOEXCEPT { RYML_ASSERT_VISIT_CB_(m_callbacks, ((_p(node)->m_type|more_flags) & (VAL|MAP)) == 0, this, node); _p(node)->m_type |= SEQ|more_flags; } void set_map(id_type node) RYML_NOEXCEPT { RYML_ASSERT_VISIT_CB_(m_callbacks, (_p(node)->m_type & (VAL|SEQ)) == 0, this, node); _p(node)->m_type |= MAP; } void set_map(id_type node, NodeType more_flags) RYML_NOEXCEPT { RYML_ASSERT_VISIT_CB_(m_callbacks, ((_p(node)->m_type|more_flags) & (VAL|SEQ)) == 0, this, node); _p(node)->m_type |= MAP|more_flags; } void set_key_tag(id_type node, csubstr tag) { RYML_ASSERT_VISIT_CB_(m_callbacks, has_key(node), this, node); _p(node)->m_key.tag = tag; _add_flags(node, KEYTAG); } void set_val_tag(id_type node, csubstr tag) { RYML_ASSERT_VISIT_CB_(m_callbacks, has_val(node) || is_container(node), this, node); _p(node)->m_val.tag = tag; _add_flags(node, VALTAG); } void set_key_anchor(id_type node, csubstr anchor) { RYML_ASSERT_VISIT_CB_(m_callbacks, ! is_key_ref(node), this, node); _p(node)->m_key.anchor = anchor.triml('&'); _add_flags(node, KEYANCH); } void set_val_anchor(id_type node, csubstr anchor) { RYML_ASSERT_VISIT_CB_(m_callbacks, ! is_val_ref(node), this, node); _p(node)->m_val.anchor = anchor.triml('&'); _add_flags(node, VALANCH); } void set_key_ref (id_type node, csubstr ref ) { RYML_ASSERT_VISIT_CB_(m_callbacks, ! has_key_anchor(node), this, node); NodeData* C4_RESTRICT n = _p(node); n->m_key.set_ref_maybe_replacing_scalar(ref, n->m_type.has_key()); _add_flags(node, KEY|KEYREF); } void set_val_ref (id_type node, csubstr ref ) { RYML_ASSERT_VISIT_CB_(m_callbacks, ! has_val_anchor(node), this, node); NodeData* C4_RESTRICT n = _p(node); n->m_val.set_ref_maybe_replacing_scalar(ref, n->m_type.has_val()); _add_flags(node, VAL|VALREF); } void rem_key_anchor(id_type node) { _p(node)->m_key.anchor.clear(); _rem_flags(node, KEYANCH); } void rem_val_anchor(id_type node) { _p(node)->m_val.anchor.clear(); _rem_flags(node, VALANCH); } void rem_key_ref (id_type node) { _p(node)->m_key.anchor.clear(); _rem_flags(node, KEYREF); } void rem_val_ref (id_type node) { _p(node)->m_val.anchor.clear(); _rem_flags(node, VALREF); } void rem_anchor_ref(id_type node) { _p(node)->m_key.anchor.clear(); _p(node)->m_val.anchor.clear(); _rem_flags(node, KEYANCH|VALANCH|KEYREF|VALREF); } /** @} */ private: C4_NORETURN C4_NO_INLINE C4_COLD void err_visit_(id_type node) const { RYML_ERR_VISIT_CB_(m_callbacks, this, node, "invalid node"); } public: /** @name serialization - checked */ /** @{ */ template C4_ALWAYS_INLINE void save(id_type node, T const& val) { if C4_LIKELY(node != NONE && node < m_cap && node >= 0) { write(this, node, val); return; } err_visit_(node); } template C4_ALWAYS_INLINE void save(id_type node, T const& val, NodeType more_flags) { if C4_LIKELY(node != NONE && node < m_cap && node >= 0) { write(this, node, val); _p(node)->m_type |= more_flags; return; } err_visit_(node); } template C4_ALWAYS_INLINE void save_key(id_type node, T const& key) { if C4_LIKELY(node != NONE && node < m_cap && node >= 0) { write_key(this, node, key); return; } err_visit_(node); } template C4_ALWAYS_INLINE void save_key(id_type node, T const& key, NodeType more_flags) { if C4_LIKELY(node != NONE && node < m_cap && node >= 0) { write_key(this, node, key); _p(node)->m_type |= more_flags; return; } err_visit_(node); } /** @} */ public: /** @name serialization - asserted */ /** @{ */ template C4_ALWAYS_INLINE void set_serialized(id_type node, T const& val) RYML_NOEXCEPT { RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE && node >= 0 && node < m_cap, this, node); write(this, node, val); } template C4_ALWAYS_INLINE void set_serialized(id_type node, T const& val, NodeType more_flags) RYML_NOEXCEPT { RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE && node >= 0 && node < m_cap, this, node); write(this, node, val); _p(node)->m_type |= more_flags; } template C4_ALWAYS_INLINE void set_key_serialized(id_type node, T const& key) RYML_NOEXCEPT { RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE && node >= 0 && node < m_cap, this, node); write_key(this, node, key); } template C4_ALWAYS_INLINE void set_key_serialized(id_type node, T const& key, NodeType more_flags) RYML_NOEXCEPT { RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE && node >= 0 && node < m_cap, this, node); write_key(this, node, key); _p(node)->m_type |= more_flags; } /** @} */ public: /** @name deserialization - checked * * These methods raise an error if the deserialization failed or * optionally if the node is not readable. */ /** @{ */ static C4_ALWAYS_INLINE ReadResult to_result_(bool, id_type node) noexcept { return ReadResult(node); } static C4_ALWAYS_INLINE ReadResult to_result_(ReadResult notlegacy, id_type) noexcept { return notlegacy; } /** (1) deserialize the node's contents (val or container) to the * given variable, forwarding to the user-overrideable @ref read() * function (see @ref doc_serialization_tree_read). This function * differs from @ref Tree::deserialize() in that here the error * callback is called if the deserialization failed, or * (optionally) the node is not readable. */ template C4_ALWAYS_INLINE void load(id_type node, T * v, bool check_readable=true) const { const bool can_read_val = (node != NONE && node < m_cap && node >= 0 && (_p(node)->m_type & (VAL|MAP|SEQ))); RYML_ASSERT_VISIT_CB_(m_callbacks, can_read_val, this, node); if C4_LIKELY(!check_readable || can_read_val) { const ReadResult result(read(this, node, v), node); if C4_LIKELY(result) return; else node = result.node; } err_visit_(node); } /** (2) like (1), but for wrapper tag types such as @ref * c4::fmt::base64() */ template C4_ALWAYS_INLINE void load(id_type node, Wrapper const& w, bool check_readable=true) const { RYML_CHECK_TYPE_IS_WRAPPER_LIKE_(Wrapper); const bool can_read_val = (node != NONE && node < m_cap && node >= 0 && (_p(node)->m_type & (VAL|MAP|SEQ))); RYML_ASSERT_VISIT_CB_(m_callbacks, can_read_val, this, node); if C4_LIKELY(!check_readable || can_read_val) { const ReadResult result(read(this, node, w), node); if C4_LIKELY(result) return; else node = result.node; } err_visit_(node); } /** (1) deserialize the node's key (necessarily a scalar) to the * given variable, forwarding to the user-overrideable @ref * read_key() function (see @ref * doc_serialization_node_read). This function differs from @ref * Tree::deserialize_key() in that here the error callback is * called if the deserialization failed, or (optionally) the node * is not readable. */ template C4_ALWAYS_INLINE void load_key(id_type node, T * k, bool check_readable=true) const { const bool can_read_key = (node != NONE && node < m_cap && node >= 0 && (_p(node)->m_type & KEY)); RYML_ASSERT_VISIT_CB_(m_callbacks, can_read_key, this, node); if C4_LIKELY(!check_readable || can_read_key) { const ReadResult result(read_key(this, node, k), node); if C4_LIKELY(result) return; else node = result.node; } err_visit_(node); } /** (2) like (1), but for wrapper tag types such as @ref * c4::fmt::base64() */ template C4_ALWAYS_INLINE void load_key(id_type node, Wrapper const& w, bool check_readable=true) const { RYML_CHECK_TYPE_IS_WRAPPER_LIKE_(Wrapper); bool can_read_key = (node != NONE && node < m_cap && node >= 0 && (_p(node)->m_type & KEY)); RYML_ASSERT_VISIT_CB_(m_callbacks, can_read_key, this, node); if C4_LIKELY(!check_readable || can_read_key) { const ReadResult result(read_key(this, node, w), node); if C4_LIKELY(result) return; else node = result.node; } err_visit_(node); } /** @} */ public: /** @name deserialization - asserted preconditions */ /** @{ */ /** (1) deserialize a node's contents to a variable */ template C4_NODISCARD C4_ALWAYS_INLINE ReadResult deserialize(id_type node, T * v) const { RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE && node >= 0 && node < m_cap, this, node); RYML_ASSERT_VISIT_CB_(m_callbacks, _p(node)->m_type & (VAL|MAP|SEQ), this, node); // use the adapter ctor to accomodate legacy read() implementations return ReadResult(read(this, node, v), node); } /** (2) like (1), but for a wrapper type like those used in tag * functions */ template C4_NODISCARD C4_ALWAYS_INLINE ReadResult deserialize(id_type node, Wrapper const& w) const { RYML_CHECK_TYPE_IS_WRAPPER_LIKE_(Wrapper); RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE && node >= 0 && node < m_cap, this, node); RYML_ASSERT_VISIT_CB_(m_callbacks, _p(node)->m_type & (VAL|MAP|SEQ), this, node); // use the adapter ctor to accomodate legacy read() implementations return ReadResult(read(this, node, w), node); } /** (1) deserialize a node's key to a variable */ template C4_NODISCARD C4_ALWAYS_INLINE ReadResult deserialize_key(id_type node, T * v) const { RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE && node >= 0 && node < m_cap, this, node); RYML_ASSERT_VISIT_CB_(m_callbacks, has_key(node), this, node); // use the adapter ctor to accomodate legacy read_key() implementations return ReadResult(read_key(this, node, v), node); } /** (2) like (1), but for a wrapper type like those used in tag * functions */ template C4_NODISCARD C4_ALWAYS_INLINE ReadResult deserialize_key(id_type node, Wrapper const& w) const { RYML_CHECK_TYPE_IS_WRAPPER_LIKE_(Wrapper); RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE && node >= 0 && node < m_cap, this, node); RYML_ASSERT_VISIT_CB_(m_callbacks, has_key(node), this, node); // use the adapter ctor to accomodate legacy read_key() implementations return ReadResult(read_key(this, node, w), node); } /** @} */ public: /** @name lookup and deserialize */ /** @{ */ /** (1) find a child by name and deserialize its contents to the * given variable (ie call .deserialize() on the child if it * exists). Otherwise, the variable is kept unchanged. * * @return a @ref ReadResult set with this node's id if no child * exists, or the ReadResult from the deserialization. * * @see see also @ref Tree::find_child_r() */ template C4_NODISCARD C4_ALWAYS_INLINE ReadResult deserialize_child(id_type node, csubstr child_key, T * v) const { id_type ch; ReadResult r = find_child_r(node, child_key, &ch); if(r) r = deserialize(ch, v); return r; } /** (2) like (1), but assign from fallback if no such child exists. */ template C4_NODISCARD C4_ALWAYS_INLINE ReadResult deserialize_child(id_type node, csubstr child_key, T * v, T const& fallback) const { id_type ch; if(find_child_r(node, child_key, &ch)) return deserialize(ch, v); *v = fallback; return ReadResult(); } /** (3) like (1), but for wrapper tag types such as @ref c4::fmt::base64() */ template C4_NODISCARD C4_ALWAYS_INLINE ReadResult deserialize_child(id_type node, csubstr child_key, Wrapper const& wrapper) const { id_type ch; ReadResult r = find_child_r(node, child_key, &ch); if(r) r = deserialize(ch, wrapper); return r; } /** (1) find a child by position and deserialize its contents to * the given variable (ie call .deserialize() on the child if it * exists). Otherwise, the variable is kept unchanged. * * @return a @ref ReadResult set with this node's id if no child * exists, or the ReadResult from the deserialization. * * @see see also @ref Tree::child_r() */ template C4_NODISCARD C4_ALWAYS_INLINE ReadResult deserialize_child(id_type node, id_type child_pos, T * v) const { RYML_ASSERT_VISIT_CB_(m_callbacks, is_container(node), this, node); // this assertion is needed because child_r() does not assert, contrary to find_child_r() id_type ch; ReadResult r = child_r(node, child_pos, &ch); if(r) r = deserialize(ch, v); return r; } /** (2) like (1), but assign from fallback if no such child exists */ template C4_NODISCARD C4_ALWAYS_INLINE ReadResult deserialize_child(id_type node, id_type child_pos, T * v, T const& fallback) const { RYML_ASSERT_VISIT_CB_(m_callbacks, is_container(node), this, node); // this assertion is needed because child_r() does not assert, contrary to find_child_r() id_type ch; if(child_r(node, child_pos, &ch)) return deserialize(ch, v); *v = fallback; return ReadResult(); } /** (3) like (1), but for wrapper tag types such as @ref * c4::fmt::base64() */ template C4_NODISCARD C4_ALWAYS_INLINE ReadResult deserialize_child(id_type node, id_type child_pos, Wrapper const& wrapper) const { RYML_ASSERT_VISIT_CB_(m_callbacks, is_container(node), this, node); // this assertion is needed because child_r() does not assert, contrary to find_child_r() id_type ch; ReadResult r = child_r(node, child_pos, &ch); if(r) r = deserialize(ch, wrapper); return r; } /** @} */ public: /** @name tree modifiers */ /** @{ */ /** reorder the tree in memory so that all the nodes are stored * in a linear sequence when visited in depth-first order. * This will invalidate existing ids, since the node id is its * position in the tree's node array. */ void reorder(); /** @} */ public: /** @name anchors and references/aliases */ /** @{ */ /** Resolve references (aliases <- anchors), by forwarding to @ref * ReferenceResolver::resolve(); refer to @ref * ReferenceResolver::resolve() for further details. */ void resolve(ReferenceResolver *C4_RESTRICT rr, bool clear_anchors=true); /** Resolve references (aliases <- anchors), by forwarding to @ref * ReferenceResolver::resolve(); refer to @ref * ReferenceResolver::resolve() for further details. This overload * uses a throwaway resolver object. */ void resolve(bool clear_anchors=true); /** @} */ public: /** @name tags and tag directives */ /** @{ */ /** Resolve tags in the tree such as \c "!!str" -> * \c "", \c "!foo" -> \c "" and custom tags * as well, ie tags of the form \c "!handle!tag" for which there is a * corresponding \c "%TAG" directive * * @param cache an object of type @ref TagCache to minimize memory * usage by avoiding repeated instantiation of the resolved * tags in the tree's arena. * * @param all if true, resolve all tags; if false resolve only * custom tags, ie those that have a prefix such as * \c "!m!tag" with a matching \c "\%TAG" directive */ void resolve_tags(TagCache &cache, bool all=true); void normalize_tags(); void normalize_tags_long(); id_type num_tag_directives() const; void add_tag_directive(csubstr handle, csubstr prefix, id_type id); void clear_tag_directives(); /** resolve the given tag, appearing at node_id. Write the result into output. * @return the number of characters required for the resolved tag */ size_t resolve_tag(substr output, csubstr tag, id_type node_id) const; /** Wrapper for @ref Tree::resolve_tag(), returning a substring */ csubstr resolve_tag_sub(substr output, csubstr tag, id_type node_id) const { size_t needed = resolve_tag(output, tag, node_id); return needed <= output.len ? output.first(needed) : output; } c4::yml::TagDirectiveRange tag_directives() const { return m_tag_directives.directives(); } /** @cond dev */ RYML_DEPRECATED("use c4::yml::tag_directive_const_iterator") typedef TagDirective const* tag_directive_const_iterator; RYML_DEPRECATED("use c4::yml::TagDirectiveRange") typedef c4::yml::TagDirectiveRange TagDirectiveProxy; /** @endcond */ /** @} */ public: /** @name modifying hierarchy */ /** @{ */ /** create and insert a new child of @p parent. insert after the (to-be) * sibling @p after, which must be a child of @p parent. To insert as the * first child, set after to NONE */ C4_ALWAYS_INLINE id_type insert_child(id_type parent, id_type after) { RYML_ASSERT_VISIT_CB_(m_callbacks, parent != NONE, this, parent); RYML_ASSERT_VISIT_CB_(m_callbacks, is_container(parent) || is_root(parent), this, parent); RYML_ASSERT_VISIT_CB_(m_callbacks, after == NONE || (_p(after)->m_parent == parent), this, parent); id_type child = _claim(); _set_hierarchy(child, parent, after); return child; } /** create and insert a node as the first child of @p parent */ C4_ALWAYS_INLINE id_type prepend_child(id_type parent) { return insert_child(parent, NONE); } /** create and insert a node as the last child of @p parent */ C4_ALWAYS_INLINE id_type append_child(id_type parent) { return insert_child(parent, _p(parent)->m_last_child); } C4_ALWAYS_INLINE id_type _append_child__unprotected(id_type parent) { id_type child = _claim(); _set_hierarchy(child, parent, _p(parent)->m_last_child); return child; } public: //! create and insert a new sibling of n. insert after "after" C4_ALWAYS_INLINE id_type insert_sibling(id_type node, id_type after) { return insert_child(_p(node)->m_parent, after); } /** create and insert a node as the first node of @p parent */ C4_ALWAYS_INLINE id_type prepend_sibling(id_type node) { return prepend_child(_p(node)->m_parent); } C4_ALWAYS_INLINE id_type append_sibling(id_type node) { return append_child(_p(node)->m_parent); } public: /** remove an entire branch at once: ie remove the children and the node itself */ void remove(id_type node) { remove_children(node); _release(node); } /** remove all the node's children, but keep the node itself */ void remove_children(id_type node); public: /** change the node's position in the parent */ void move(id_type node, id_type after); /** change the node's parent and position */ void move(id_type node, id_type new_parent, id_type after); /** change the node's parent and position to a different tree * @return the index of the new node in the destination tree */ id_type move(Tree * src, id_type node, id_type new_parent, id_type after); /** ensure the first node is a stream. Eg, change this tree * * DOCMAP * MAP * KEYVAL * KEYVAL * SEQ * VAL * * to * * STREAM * DOCMAP * MAP * KEYVAL * KEYVAL * SEQ * VAL * * If the root is already a stream, this is a no-op. */ void set_root_as_stream(); bool change_type(id_type node, NodeType type); bool change_type(id_type node, type_bits type) { return change_type(node, (NodeType)type); } public: /** recursively duplicate a node from this tree into a new parent, * placing it after one of its children * @return the index of the copy */ id_type duplicate(id_type node, id_type new_parent, id_type after); /** recursively duplicate a node from a different tree into a new parent, * placing it after one of its children * @return the index of the copy */ id_type duplicate(Tree const* src, id_type node, id_type new_parent, id_type after); /** recursively duplicate the node's children (but not the node) * @return the index of the last duplicated child */ id_type duplicate_children(id_type node, id_type parent, id_type after); /** recursively duplicate the node's children (but not the node), where * the node is from a different tree * @return the index of the last duplicated child */ id_type duplicate_children(Tree const* src, id_type node, id_type parent, id_type after); /** duplicate the node's children (but not the node) in a new parent, but * omit repetitions where a duplicated node has the same key (in maps) or * value (in seqs). If one of the duplicated children has the same key * (in maps) or value (in seqs) as one of the parent's children, the one * that is placed closest to the end will prevail. */ id_type duplicate_children_no_rep(id_type node, id_type parent, id_type after); id_type duplicate_children_no_rep(Tree const* src, id_type node, id_type parent, id_type after); void duplicate_contents(id_type node, id_type where); void duplicate_contents(Tree const* src, id_type node, id_type where); public: void merge_with(Tree const* src, id_type src_node=NONE, id_type dst_root=NONE); /** @} */ public: /** @name locations */ /** @{ */ /** Get the location of a node from the parse used to parse this tree. */ Location location(Parser const& p, id_type node) const; private: bool _location_from_node(Parser const& p, id_type node, Location *C4_RESTRICT loc, id_type level) const; bool _location_from_cont(Parser const& p, id_type node, Location *C4_RESTRICT loc) const; /** @} */ public: /** @name internal string arena */ /** @{ */ /** get the current size of the tree's internal arena */ size_t arena_size() const { return m_arena_pos; } /** get the current capacity of the tree's internal arena */ size_t arena_capacity() const { return m_arena.len; } /** get the current slack of the tree's internal arena */ size_t arena_slack() const { RYML_ASSERT_VISIT_CB_(m_callbacks, m_arena.len >= m_arena_pos, this, NONE); return m_arena.len - m_arena_pos; } RYML_DEPRECATED("use arena_size() instead") size_t arena_pos() const { return m_arena_pos; } /** get the current arena */ csubstr arena() const { return m_arena.first(m_arena_pos); } /** get the current arena */ substr arena() { return m_arena.first(m_arena_pos); } // NOLINT(readability-make-member-function-const) /** get the free space at the end of the arena */ csubstr arena_rem() const { return m_arena.sub(m_arena_pos); } /** get the free space at the end of the arena */ substr arena_rem() { return m_arena.sub(m_arena_pos); } // NOLINT(readability-make-member-function-const) /** return true if the given substring is part of the tree's string arena */ C4_ALWAYS_INLINE bool in_arena(csubstr s) const { return m_arena.is_super(s); } /** serialize the given variable to the tree's * arena, growing it as needed to accomodate the serialization. * * @note To customize how the type gets serialized to a string, * you can overload c4::to_chars(substr, T const&) * * @note To customize how the type gets serialized to the arena, * you can overload @ref scalar_serialize() * * @note Growing the arena may cause relocation of the entire * existing arena, and thus change the contents of individual * nodes, and thus cost O(numnodes)+O(arenasize). To avoid this * cost, ensure that the arena is reserved to an appropriate size * using @ref Tree::reserve_arena(). * * @see alloc_arena() */ template C4_ALWAYS_INLINE csubstr to_arena(T const& C4_RESTRICT a) { return serialize_to_arena(this, a); } /** copy the given string to the tree's arena, growing the arena * by the required size. * * @note this method differs from @ref to_arena() in that it * returns a mutable substr, and further it does not deal * with some corner cases for null/empty strings * * @note Growing the arena may cause relocation of the entire * existing arena, and thus change the contents of individual * nodes, and thus cost O(numnodes)+O(arenasize). To avoid this * cost, ensure that the arena is reserved to an appropriate size * before using @ref Tree::reserve_arena() * * @see reserve_arena() * @see alloc_arena() */ substr copy_to_arena(csubstr s) { RYML_ASSERT_VISIT_CB_(m_callbacks, !s.overlaps(m_arena), this, NONE); substr cp = alloc_arena(s.len); RYML_ASSERT_VISIT_CB_(m_callbacks, cp.len == s.len, this, NONE); RYML_ASSERT_VISIT_CB_(m_callbacks, !s.overlaps(cp), this, NONE); C4_SUPPRESS_WARNING_GCC_PUSH #if (!defined(__clang__)) && (defined(__GNUC__) && __GNUC__ >= 10) C4_SUPPRESS_WARNING_GCC("-Wstringop-overflow=") // no need for terminating \0 C4_SUPPRESS_WARNING_GCC("-Wrestrict") // there's an assert to ensure no violation of restrict behavior #endif if(s.len) memcpy(cp.str, s.str, s.len); C4_SUPPRESS_WARNING_GCC_POP return cp; } /** grow the tree's string arena by the given size and return a substr * of the added portion * * @note Growing the arena may cause relocation of the entire * existing arena, and thus change the contents of individual * nodes, and thus cost O(numnodes)+O(arenasize). To avoid this * cost, ensure that the arena is reserved to an appropriate size * using @ref Tree::reserve_arena(). * * @see reserve_arena() */ substr alloc_arena(size_t sz) { if(sz > arena_slack()) _grow_arena(sz - arena_slack()); substr s = _request_span(sz); return s; } /** ensure the tree's internal string arena is at least the given capacity * @warning This operation may be expensive, with a potential complexity of O(numNodes)+O(arenasize). * @warning Growing the arena may cause relocation of the entire * existing arena, and thus change the contents of individual nodes. */ void reserve_arena(size_t arena_cap=RYML_DEFAULT_TREE_ARENA_CAPACITY) { if(arena_cap > m_arena.len) { substr buf; buf.str = RYML_CB_ALLOC_(m_callbacks, char, arena_cap); buf.len = arena_cap; if(m_arena.str) { RYML_ASSERT_VISIT_CB_(m_callbacks, m_arena.len >= 0, this, NONE); _relocate(buf); // does a memcpy and changes nodes using the arena RYML_CB_FREE_(m_callbacks, m_arena.str, char, m_arena.len); } m_arena = buf; } } /** @} */ public: /** @cond dev */ substr _grow_arena(size_t more) { size_t cap = m_arena.len + more; cap = cap < RYML_DEFAULT_TREE_ARENA_CAPACITY_START ? RYML_DEFAULT_TREE_ARENA_CAPACITY_START : cap; cap = cap < 2 * m_arena.len ? 2 * m_arena.len : cap; reserve_arena(cap); return m_arena.sub(m_arena_pos); } substr _request_span(size_t sz) { RYML_ASSERT_VISIT_CB_(m_callbacks, m_arena_pos + sz <= m_arena.len, this, NONE); substr s; s = m_arena.sub(m_arena_pos, sz); m_arena_pos += sz; return s; } substr _relocated(csubstr s, substr next_arena) const { RYML_ASSERT_VISIT_CB_(m_callbacks, m_arena.is_super(s) || s.len == 0, this, NONE); RYML_ASSERT_VISIT_CB_(m_callbacks, m_arena.sub(0, m_arena_pos).is_super(s) || s.len == 0, this, NONE); auto pos = (s.str - m_arena.str); // this is larger than 0 based on the assertions above substr r(next_arena.str + pos, s.len); RYML_ASSERT_VISIT_CB_(m_callbacks, r.str - next_arena.str == pos, this, NONE); RYML_ASSERT_VISIT_CB_(m_callbacks, next_arena.sub(0, m_arena_pos).is_super(r) || r.len == 0, this, NONE); return r; } /** @endcond */ public: /** @name lookup */ /** @{ */ struct RYML_EXPORT lookup_result { id_type target; id_type closest; size_t path_pos; csubstr path; operator bool() const { return target != NONE; } lookup_result() : target(NONE), closest(NONE), path_pos(0), path() {} lookup_result(csubstr path_, id_type start) : target(NONE), closest(start), path_pos(0), path(path_) {} /** get the part ot the input path that was resolved */ csubstr resolved() const; /** get the part ot the input path that was unresolved */ csubstr unresolved() const; }; /** for example foo.bar[0].baz */ lookup_result lookup_path(csubstr path, id_type start=NONE) const; /** defaulted lookup: lookup @p path; if the lookup fails, recursively modify * the tree so that the corresponding lookup_path() would return the * default value. * @see lookup_path() */ id_type lookup_path_or_modify(csubstr default_value, csubstr path, id_type start=NONE); /** defaulted lookup: lookup @p path; if the lookup fails, recursively modify * the tree so that the corresponding lookup_path() would return the * branch @p src_node (from the tree @p src). * @see lookup_path() */ id_type lookup_path_or_modify(Tree const *src, id_type src_node, csubstr path, id_type start=NONE); /** @} */ private: struct _lookup_path_token { csubstr value; NodeType type; _lookup_path_token() : value(), type() {} // LCOV_EXCL_LINE _lookup_path_token(csubstr v, NodeType t) : value(v), type(t) {} operator bool() const { return type != NOTYPE; } bool is_index() const { return value.begins_with('[') && value.ends_with(']'); } }; id_type _lookup_path_or_create(csubstr path, id_type start); void _lookup_path (lookup_result *r) const; void _lookup_path_modify(lookup_result *r); id_type _next_node (lookup_result *r, _lookup_path_token *parent) const; id_type _next_node_modify(lookup_result *r, _lookup_path_token *parent); static void _advance(lookup_result *r, size_t more); _lookup_path_token _next_token(lookup_result *r, _lookup_path_token const& parent) const; private: void _clear(); void _free(); void _copy(Tree const& that); void _move(Tree & that) noexcept; void _relocate(substr next_arena); public: /** @cond dev*/ #if ! RYML_USE_ASSERT C4_ALWAYS_INLINE void _check_next_flags(id_type, type_bits) {} #else void _check_next_flags(id_type node, type_bits f) { NodeData *n = _p(node); type_bits o = n->m_type; // old C4_UNUSED(o); if(f & MAP) { RYML_ASSERT_VISIT_MSG_CB_(m_callbacks, (f & SEQ) == 0, this, node, "cannot mark simultaneously as map and seq"); RYML_ASSERT_VISIT_MSG_CB_(m_callbacks, (f & VAL) == 0, this, node, "cannot mark simultaneously as map and val"); RYML_ASSERT_VISIT_MSG_CB_(m_callbacks, (o & SEQ) == 0, this, node, "cannot turn a seq into a map; clear first"); RYML_ASSERT_VISIT_MSG_CB_(m_callbacks, (o & VAL) == 0, this, node, "cannot turn a val into a map; clear first"); } else if(f & SEQ) { RYML_ASSERT_VISIT_MSG_CB_(m_callbacks, (f & MAP) == 0, this, node, "cannot mark simultaneously as seq and map"); RYML_ASSERT_VISIT_MSG_CB_(m_callbacks, (f & VAL) == 0, this, node, "cannot mark simultaneously as seq and val"); RYML_ASSERT_VISIT_MSG_CB_(m_callbacks, (o & MAP) == 0, this, node, "cannot turn a map into a seq; clear first"); RYML_ASSERT_VISIT_MSG_CB_(m_callbacks, (o & VAL) == 0, this, node, "cannot turn a val into a seq; clear first"); } if(f & KEY) { RYML_ASSERT_VISIT_CB_(m_callbacks, !is_root(node), this, node); RYML_ASSERT_VISIT_CB_(m_callbacks, is_map(parent(node)), this, node); } if((f & VAL) && !is_root(node)) { auto pid = parent(node); C4_UNUSED(pid); RYML_ASSERT_VISIT_CB_(m_callbacks, is_map(pid) || is_seq(pid), this, node); } } #endif void _add_flags(id_type node, type_bits f) { NodeData *d = _p(node); type_bits fb = f | d->m_type; _check_next_flags(node, fb); d->m_type = fb; } void _rem_flags(id_type node, type_bits f) { NodeData *d = _p(node); type_bits fb = d->m_type & ~f; _check_next_flags(node, fb); d->m_type = fb; } id_type _do_reorder(id_type *node, id_type count); void _swap(id_type n_, id_type m_); void _swap_props(id_type n_, id_type m_); void _swap_hierarchy(id_type n_, id_type m_); void _copy_hierarchy(id_type dst_, id_type src_); void _copy_props(id_type dst_, id_type src_) { _copy_props(dst_, this, src_); } void _copy_props_wo_key(id_type dst_, id_type src_) { _copy_props_wo_key(dst_, this, src_); } void _copy_props(id_type dst_, Tree const* that_tree, id_type src_) { NodeData & C4_RESTRICT dst = *_p(dst_); NodeData const& C4_RESTRICT src = *that_tree->_p(src_); dst.m_type = src.m_type; dst.m_key = src.m_key; dst.m_val = src.m_val; } void _copy_props(id_type dst_, Tree const* that_tree, id_type src_, type_bits src_mask) { NodeData & C4_RESTRICT dst = *_p(dst_); NodeData const& C4_RESTRICT src = *that_tree->_p(src_); dst.m_type = (src.m_type & src_mask) | (dst.m_type & ~src_mask); dst.m_key = src.m_key; dst.m_val = src.m_val; } void _copy_props_wo_key(id_type dst_, Tree const* that_tree, id_type src_) { auto & C4_RESTRICT dst = *_p(dst_); auto const& C4_RESTRICT src = *that_tree->_p(src_); dst.m_type = (src.m_type & ~KEYMASK_) | (dst.m_type & KEYMASK_); dst.m_val = src.m_val; } void _copy_props_wo_key(id_type dst_, Tree const* that_tree, id_type src_, type_bits src_mask) { auto & C4_RESTRICT dst = *_p(dst_); auto const& C4_RESTRICT src = *that_tree->_p(src_); dst.m_type = (src.m_type & ((~KEYMASK_)|src_mask)) | (dst.m_type & (KEYMASK_|~src_mask)); dst.m_val = src.m_val; } void _clear_type(id_type node) { _p(node)->m_type = NOTYPE; } void _clear(id_type node) { auto *C4_RESTRICT n = _p(node); n->m_type = NOTYPE; n->m_key.clear(); n->m_val.clear(); n->m_parent = NONE; n->m_first_child = NONE; n->m_last_child = NONE; } void _clear_key(id_type node) { _p(node)->m_key.clear(); _rem_flags(node, KEY); } void _clear_val(id_type node) { _p(node)->m_val.clear(); _rem_flags(node, VAL); } /** @endcond */ private: void _clear_range(id_type first, id_type num); id_type _claim(); void _claim_root(); void _release(id_type node); void _free_list_add(id_type node); void _free_list_rem(id_type node); void _set_hierarchy(id_type node, id_type parent, id_type after_sibling); void _rem_hierarchy(id_type node); public: // members are exposed, but you should NOT access them directly NodeData *m_buf; id_type m_cap; id_type m_size; id_type m_free_head; id_type m_free_tail; substr m_arena; size_t m_arena_pos; Callbacks m_callbacks; TagDirectives m_tag_directives; public: /** @cond dev */ // LCOV_EXCL_START C4_SUPPRESS_WARNING_GCC_CLANG_PUSH C4_SUPPRESS_WARNING_MSVC_PUSH C4_SUPPRESS_WARNING_GCC_CLANG("-Wdeprecated") C4_SUPPRESS_WARNING_GCC_CLANG("-Wdeprecated-declarations") C4_SUPPRESS_WARNING_MSVC(4996) // deprecated RYML_DEPRECATED("use .type().type_str(buf)") const char* type_str(id_type node) const { return NodeType::type_str(_p(node)->m_type); } RYML_DEPRECATED("use has_other_siblings()") static bool has_siblings(id_type /*node*/) { return true; } RYML_DEPRECATED("use set_key()+set_val()") void to_keyval(id_type node, csubstr key, csubstr val, type_bits more_flags=0); RYML_DEPRECATED("use set_key()+set_map()") void to_map(id_type node, csubstr key, type_bits more_flags=0); RYML_DEPRECATED("use set_key()+set_seq()") void to_seq(id_type node, csubstr key, type_bits more_flags=0); RYML_DEPRECATED("use set_val()") void to_val(id_type node, csubstr val, type_bits more_flags=0); RYML_DEPRECATED("use set_map()") void to_map(id_type node, type_bits more_flags=0); RYML_DEPRECATED("use set_seq()") void to_seq(id_type node, type_bits more_flags=0); RYML_DEPRECATED("use set_doc()") void to_doc(id_type node, type_bits more_flags=0); RYML_DEPRECATED("use set_stream()") void to_stream(id_type node, type_bits more_flags=0); RYML_DEPRECATED("use resolve_tags(TagCache&)") void resolve_tags() { TagCache cache; resolve_tags(cache); } RYML_DEPRECATED("") void _set(id_type node, NodeInit const& i) { RYML_ASSERT_VISIT_CB_(m_callbacks, i._check(), this, node); NodeData *n = _p(node); RYML_ASSERT_VISIT_CB_(m_callbacks, n->m_key.scalar.empty() || i.key.scalar.empty() || i.key.scalar == n->m_key.scalar, this, node); _add_flags(node, i.type); if(n->m_key.scalar.empty()) { if( ! i.key.scalar.empty()) { set_key(node, i.key.scalar); } } n->m_key.tag = i.key.tag; n->m_val = i.val; } RYML_DEPRECATED("") void _set_key(id_type node, NodeScalar const& key, NodeType more_flags=0) { _p(node)->m_key = key; _add_flags(node, KEY|more_flags); } RYML_DEPRECATED("") void _set_val(id_type node, NodeScalar const& val, NodeType more_flags=0) { _p(node)->m_val = val; _add_flags(node, VAL|more_flags); } C4_SUPPRESS_WARNING_MSVC_POP C4_SUPPRESS_WARNING_GCC_CLANG_POP /** @endcond */ // LCOV_EXCL_STOP }; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @addtogroup doc_serialization_tree_write_arena * * @{ */ /** Forward to @ref scalar_serialize(), giving it the tree's arena and * resizing the arena as needed to fit the result. */ template csubstr serialize_to_arena_scalar(Tree * tree, T const& a) { substr buf = tree->arena_rem(); // buffer: the free part of the tree's arenra. again: size_t num = scalar_serialize(buf, a); // try to write into it if C4_LIKELY(num <= buf.len) // was it enough? { buf = buf.first(num); // fit the payload } else { buf = tree->_grow_arena(num); // does not advance pos goto again; // NOLINT } tree->m_arena_pos += num; return buf; } /** @} */ /** @addtogroup doc_serialization_tree_write * * @{ */ #if (C4_CPP >= 17) || defined(__DOXYGEN__) /** Return extra style flags to use when setting a scalar as val. * Defaults to VAL_PLAIN for arithmetic types, or NOTYPE otherwise */ template C4_ALWAYS_INLINE type_bits scalar_flags_val(T const&) noexcept { if constexpr (std::is_arithmetic_v) return VAL_PLAIN; else return NOTYPE; } /** Return extra style flags to use when setting a scalar as key. * Defaults to KEY_PLAIN for arithmetic types, or NOTYPE otherwise */ template C4_ALWAYS_INLINE type_bits scalar_flags_key(T const&) noexcept { if constexpr (std::is_arithmetic_v) return KEY_PLAIN; else return NOTYPE; } #else // pre-C++17 implementation: need to use SFINAE template C4_ALWAYS_INLINE auto scalar_flags_val(T const&) noexcept -> typename std::enable_if::value, type_bits>::type { return VAL_PLAIN; } template C4_ALWAYS_INLINE auto scalar_flags_key(T const&) noexcept -> typename std::enable_if::value, type_bits>::type { return KEY_PLAIN; } template C4_ALWAYS_INLINE auto scalar_flags_val(T const&) noexcept -> typename std::enable_if< ! std::is_arithmetic::value, type_bits>::type { return NOTYPE; } template C4_ALWAYS_INLINE auto scalar_flags_key(T const&) noexcept -> typename std::enable_if< ! std::is_arithmetic::value, type_bits>::type { return NOTYPE; } #endif // pre-C++17 implementation //----------------------------------------------------------------------------- /** Serialize a variable to the tree's arena, and set it as the node's val. */ template C4_ALWAYS_INLINE void write(Tree * tree, id_type id, T const& v) { tree->set_val(id, serialize_to_arena(tree, v), scalar_flags_val(v)); } /** Serialize a variable to the tree's arena, and set it as the node's key. * * @warning The key MUST be a scalar value. The tree cannot handle * container keys. */ template C4_ALWAYS_INLINE void write_key(Tree * tree, id_type id, T const& v) { tree->set_key(id, serialize_to_arena(tree, v), scalar_flags_key(v)); } /** @} */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @addtogroup doc_serialization_tree_read * @{ */ /** Deserialize a scalar node's val from a tree object, returning * false if the conversion failed. * * @return false if the conversion failed * @see @ref scalar_deserialize() * @see the counterpart function @ref read_key() */ template C4_NODISCARD C4_ALWAYS_INLINE ReadResult read(Tree const* tree, id_type id, T * v) { // caller only checks that type is one of VAL|MAP|SEQ (because it // can't be more concrete than that). Here, we expect a VAL so now // we can check for that: NodeData const* C4_RESTRICT nd = tree->_p(id); return ReadResult((nd->m_type & VAL) && scalar_deserialize(nd->m_val.scalar, v), id); } /** overload to enable use of wrapper tag-types like eg @ref * c4::fmt::base64() */ template C4_NODISCARD C4_ALWAYS_INLINE ReadResult read(Tree const* tree, id_type id, Wrapper const& w) { // caller only checks that type is one of VAL|MAP|SEQ (because it // can't be more concrete than that). Here, we expect a VAL so now // we can check for that: NodeData const* C4_RESTRICT nd = tree->_p(id); return ReadResult((nd->m_type & VAL) && from_chars(nd->m_val.scalar, w), id); } /** Deserialize a node's key from a tree object, returning false if * the conversion failed * * @return false if the conversion failed * @see the counterpart function @ref read(Tree const*, id_type, T*) */ template C4_NODISCARD C4_ALWAYS_INLINE ReadResult read_key(Tree const* tree, id_type id, T * v) { // caller already checks availability of key return ReadResult(scalar_deserialize(tree->_p(id)->m_key.scalar, v), id); } /** overload to enable use of wrapper tag-types like eg @ref * c4::fmt::base64() */ template C4_NODISCARD C4_ALWAYS_INLINE ReadResult read_key(Tree const* tree, id_type id, Wrapper const& w) { // caller already checks availability of key return ReadResult(from_chars(tree->_p(id)->m_key.scalar, w), id); } /** @} */ /** @} */ } // namespace yml } // namespace c4 // NOLINTEND(modernize-avoid-c-style-cast) C4_SUPPRESS_WARNING_POP #endif /* C4_YML_TREE_HPP_ */ // (end src/c4/yml/tree.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/node.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_NODE_HPP_ #define C4_YML_NODE_HPP_ /** @file node.hpp Node classes */ #ifndef C4_YML_TREE_HPP_ //#include "c4/yml/tree.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/tree.hpp must have been amalgamated before this point" #endif C4_SUPPRESS_WARNING_PUSH C4_SUPPRESS_WARNING_GCC_CLANG("-Wtype-limits") C4_SUPPRESS_WARNING_GCC_CLANG("-Wold-style-cast") C4_SUPPRESS_WARNING_GCC("-Wuseless-cast") C4_SUPPRESS_WARNING_CLANG("-Wnull-dereference") #if defined(__GNUC__) && __GNUC__ >= 6 C4_SUPPRESS_WARNING_GCC("-Wnull-dereference") #endif C4_SUPPRESS_WARNING_MSVC(4251/*needs to have dll-interface to be used by clients of struct*/) C4_SUPPRESS_WARNING_MSVC(4296/*expression is always 'boolean_value'*/) C4_SUPPRESS_WARNING_MSVC(4996/*deprecated*/) // NOLINTBEGIN(modernize-avoid-c-style-cast) namespace c4 { namespace yml { /** @cond dev */ #ifndef __DOXYGEN__ // forward decls class NodeRef; class ConstNodeRef; template ReadResult read(ConstNodeRef const& C4_RESTRICT n, T *v); template ReadResult read_key(ConstNodeRef const& C4_RESTRICT n, T *v); template void write(NodeRef *n, T const& v); template void write(NodeRef &n, T const& v); template void write_key(NodeRef *n, T const& v); template void write_key(NodeRef &n, T const& v); #endif namespace detail { template struct child_iterator { using value_type = NodeRefType; using tree_type = typename NodeRefType::tree_type; tree_type * C4_RESTRICT m_tree; id_type m_child_id; child_iterator(tree_type * t, id_type id) noexcept : m_tree(t), m_child_id(id) {} child_iterator& operator++ () RYML_NOEXCEPT { RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, m_child_id != NONE, m_tree, NONE); m_child_id = m_tree->next_sibling(m_child_id); return *this; } NodeRefType operator* () const RYML_NOEXCEPT { return NodeRefType(m_tree, m_child_id); } bool operator!= (child_iterator that) const RYML_NOEXCEPT { RYML_ASSERT_VISIT_(m_tree == that.m_tree, m_tree, NONE); return m_child_id != that.m_child_id; } }; template struct children_view { using iterator = child_iterator; using tree_type = typename NodeRefType::tree_type; tree_type *tree; id_type b, e; children_view(tree_type *t, id_type b_, id_type e_) noexcept : tree(t), b(b_), e(e_) {} C4_ALWAYS_INLINE iterator begin() const noexcept { return {tree, b}; } C4_ALWAYS_INLINE iterator end () const noexcept { return {tree, e}; } }; template static ViewType make_children_view(TreeType *C4_RESTRICT tree, id_type id) RYML_NOEXCEPT { return ViewType(tree, tree->get(id)->m_first_child, NONE); } template static ViewType make_siblings_view(TreeType *C4_RESTRICT tree, id_type id) RYML_NOEXCEPT { NodeData const *nd = tree->get(id); id_type first = (nd->m_parent != NONE) ? tree->get(nd->m_parent)->m_first_child : NONE; return ViewType(tree, first, NONE); } // LCOV_EXCL_START template RYML_DEPRECATED("") bool _visit(NodeRefType &node, Visitor fn, id_type indentation_level, bool skip_root=false) { id_type increment = 0; if( ! (node.is_root() && skip_root)) { if(fn(node, indentation_level)) return true; ++increment; } if(node.has_children()) { for(auto ch : node.children()) { if(_visit(ch, fn, indentation_level + increment, false)) // no need to forward skip_root as it won't be root { return true; } } } return false; } template RYML_DEPRECATED("") bool _visit_stacked(NodeRefType &node, Visitor fn, id_type indentation_level, bool skip_root=false) { id_type increment = 0; if( ! (node.is_root() && skip_root)) { if(fn(node, indentation_level)) { return true; } ++increment; } if(node.has_children()) { fn.push(node, indentation_level); for(auto ch : node.children()) { if(_visit_stacked(ch, fn, indentation_level + increment, false)) // no need to forward skip_root as it won't be root { fn.pop(node, indentation_level); return true; } } fn.pop(node, indentation_level); } return false; } // LCOV_EXCL_STOP } // detail /** @endcond */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @addtogroup doc_node_classes * * @{ */ namespace detail { /** a CRTP base providing read-only methods for @ref ConstNodeRef and @ref NodeRef */ template struct RoNodeMethods // NOLINT { /** @cond dev */ // CRTP helper macros, undefined at the end #define mtree_ ((Impl const* C4_RESTRICT)this)->m_tree #define tree_ ((ConstImpl const* C4_RESTRICT)this)->m_tree #define id_ ((ConstImpl const* C4_RESTRICT)this)->m_id #define this_ ((Impl const* C4_RESTRICT)this) #define this_assert_readable_() ((Impl const* C4_RESTRICT)this)->assert_readable_() C4_SUPPRESS_WARNING_GCC_CLANG_WITH_PUSH("-Wcast-align") // the leading members are aligned /** @endcond */ public: /** @name node property getters */ /** @{ */ // vertically aligned to highlight differences. // documentation to the right --> C4_ALWAYS_INLINE NodeType type() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->type(id_); } /**< Forward to @ref Tree::type(). Node must be readable. */ C4_ALWAYS_INLINE csubstr key() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->key(id_); } /**< Forward to @ref Tree::key(). Node must be readable. */ C4_ALWAYS_INLINE csubstr key_tag() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->key_tag(id_); } /**< Forward to @ref Tree::key_tag(). Node must be readable. */ C4_ALWAYS_INLINE csubstr key_ref() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->key_ref(id_); } /**< Forward to @ref Tree::key_ref(). Node must be readable. */ C4_ALWAYS_INLINE csubstr key_anchor() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->key_anchor(id_); } /**< Forward to @ref Tree::key_anchor(). Node must be readable. */ C4_ALWAYS_INLINE csubstr val() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->val(id_); } /**< Forward to @ref Tree::val(). Node must be readable. */ C4_ALWAYS_INLINE csubstr val_tag() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->val_tag(id_); } /**< Forward to @ref Tree::val_tag(). Node must be readable. */ C4_ALWAYS_INLINE csubstr val_ref() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->val_ref(id_); } /**< Forward to @ref Tree::val_ref(). Node must be readable. */ C4_ALWAYS_INLINE csubstr val_anchor() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->val_anchor(id_); } /**< Forward to @ref Tree::val_anchor(). Node must be readable. */ C4_ALWAYS_INLINE NodeScalar const& keysc() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->keysc(id_); } /**< Forward to @ref Tree::keysc(). Node must be readable. */ C4_ALWAYS_INLINE NodeScalar const& valsc() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->valsc(id_); } /**< Forward to @ref Tree::valsc(). Node must be readable. */ C4_ALWAYS_INLINE bool key_is_null() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->key_is_null(id_); } /**< Forward to @ref Tree::key_is_null(). Node must be readable. */ C4_ALWAYS_INLINE bool val_is_null() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->val_is_null(id_); } /**< Forward to @ref Tree::val_is_null(). Node must be readable. */ C4_ALWAYS_INLINE bool is_key_unfiltered() const noexcept { this_assert_readable_(); return tree_->is_key_unfiltered(id_); } /**< Forward to @ref Tree::is_key_unfiltered(). Node must be readable. */ C4_ALWAYS_INLINE bool is_val_unfiltered() const noexcept { this_assert_readable_(); return tree_->is_val_unfiltered(id_); } /**< Forward to @ref Tree::is_val_unfiltered(). Node must be readable. */ /** @} */ public: /** @name node type predicates */ /** @{ */ // vertically aligned to highlight differences. // documentation to the right --> C4_ALWAYS_INLINE bool empty() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->empty(id_); } /**< Forward to @ref Tree::empty(). Node must be readable. */ C4_ALWAYS_INLINE bool is_stream() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_stream(id_); } /**< Forward to @ref Tree::is_stream(). Node must be readable. */ C4_ALWAYS_INLINE bool is_doc() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_doc(id_); } /**< Forward to @ref Tree::is_doc(). Node must be readable. */ C4_ALWAYS_INLINE bool is_container() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_container(id_); } /**< Forward to @ref Tree::is_container(). Node must be readable. */ C4_ALWAYS_INLINE bool is_map() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_map(id_); } /**< Forward to @ref Tree::is_map(). Node must be readable. */ C4_ALWAYS_INLINE bool is_seq() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_seq(id_); } /**< Forward to @ref Tree::is_seq(). Node must be readable. */ C4_ALWAYS_INLINE bool has_val() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->has_val(id_); } /**< Forward to @ref Tree::has_val(). Node must be readable. */ C4_ALWAYS_INLINE bool has_key() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->has_key(id_); } /**< Forward to @ref Tree::has_key(). Node must be readable. */ C4_ALWAYS_INLINE bool is_val() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_val(id_); } /**< Forward to @ref Tree::is_val(). Node must be readable. */ C4_ALWAYS_INLINE bool is_keyval() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_keyval(id_); } /**< Forward to @ref Tree::is_keyval(). Node must be readable. */ C4_ALWAYS_INLINE bool has_key_tag() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->has_key_tag(id_); } /**< Forward to @ref Tree::has_key_tag(). Node must be readable. */ C4_ALWAYS_INLINE bool has_val_tag() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->has_val_tag(id_); } /**< Forward to @ref Tree::has_val_tag(). Node must be readable. */ C4_ALWAYS_INLINE bool has_key_anchor() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->has_key_anchor(id_); } /**< Forward to @ref Tree::has_key_anchor(). Node must be readable. */ C4_ALWAYS_INLINE bool has_val_anchor() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->has_val_anchor(id_); } /**< Forward to @ref Tree::has_val_anchor(). Node must be readable. */ C4_ALWAYS_INLINE bool has_anchor() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->has_anchor(id_); } /**< Forward to @ref Tree::has_anchor(). Node must be readable. */ C4_ALWAYS_INLINE bool is_key_ref() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_key_ref(id_); } /**< Forward to @ref Tree::is_key_ref(). Node must be readable. */ C4_ALWAYS_INLINE bool is_val_ref() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_val_ref(id_); } /**< Forward to @ref Tree::is_val_ref(). Node must be readable. */ C4_ALWAYS_INLINE bool is_ref() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_ref(id_); } /**< Forward to @ref Tree::is_ref(). Node must be readable. */ C4_ALWAYS_INLINE bool parent_is_seq() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->parent_is_seq(id_); } /**< Forward to @ref Tree::parent_is_seq(). Node must be readable. */ C4_ALWAYS_INLINE bool parent_is_map() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->parent_is_map(id_); } /**< Forward to @ref Tree::parent_is_map(). Node must be readable. */ /** @} */ public: /** @name style predicates */ /** @{ */ // vertically aligned to highlight differences. // documentation to the right --> C4_ALWAYS_INLINE bool type_has_any(type_bits bits) const RYML_NOEXCEPT { this_assert_readable_(); return tree_->type_has_any(id_, bits); } /**< Forward to @ref Tree::type_has_any(). Node must be readable. */ C4_ALWAYS_INLINE bool type_has_all(type_bits bits) const RYML_NOEXCEPT { this_assert_readable_(); return tree_->type_has_all(id_, bits); } /**< Forward to @ref Tree::type_has_all(). Node must be readable. */ C4_ALWAYS_INLINE bool type_has_none(type_bits bits) const RYML_NOEXCEPT { this_assert_readable_(); return tree_->type_has_none(id_, bits); } /**< Forward to @ref Tree::type_has_none(). Node must be readable. */ C4_ALWAYS_INLINE NodeType key_style() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->key_style(id_); } /**< Forward to @ref Tree::key_style(). Node must be readable. */ C4_ALWAYS_INLINE NodeType val_style() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->val_style(id_); } /**< Forward to @ref Tree::val_style(). Node must be readable. */ C4_ALWAYS_INLINE bool is_container_styled() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_container_styled(id_); } /**< Forward to @ref Tree::is_container_styled(). Node must be readable. */ C4_ALWAYS_INLINE bool is_block() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_block(id_); } /**< Forward to @ref Tree::is_block(). Node must be readable. */ C4_ALWAYS_INLINE bool is_flow() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_flow(id_); } /**< Forward to @ref Tree::is_flow(). Node must be readable. */ C4_ALWAYS_INLINE bool is_flow_sl() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_flow_sl(id_); } /**< Forward to @ref Tree::is_flow_sl(). Node must be readable. */ RYML_DEPRECATED("use one of .is_flow_ml{1,x,n}()") C4_ALWAYS_INLINE bool is_flow_ml() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_flow_ml1(id_); } /**< Forward to @ref Tree::is_flow_ml1(). Node must be readable. */ C4_ALWAYS_INLINE bool is_flow_ml1() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_flow_ml1(id_); } /**< Forward to @ref Tree::is_flow_ml1(). Node must be readable. */ C4_ALWAYS_INLINE bool is_flow_mln() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_flow_mln(id_); } /**< Forward to @ref Tree::is_flow_mln(). Node must be readable. */ C4_ALWAYS_INLINE bool is_flow_mlx() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_flow_mlx(id_); } /**< Forward to @ref Tree::is_flow_mlx(). Node must be readable. */ C4_ALWAYS_INLINE bool has_flow_space() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->has_flow_space(id_); } /**< Forward to @ref Tree::has_flow_space(). Node must be readable. */ C4_ALWAYS_INLINE bool is_key_styled() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_key_styled(id_); } /**< Forward to @ref Tree::is_key_styled(). Node must be readable. */ C4_ALWAYS_INLINE bool is_val_styled() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_val_styled(id_); } /**< Forward to @ref Tree::is_val_styled(). Node must be readable. */ C4_ALWAYS_INLINE bool is_key_literal() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_key_literal(id_); } /**< Forward to @ref Tree::is_key_literal(). Node must be readable. */ C4_ALWAYS_INLINE bool is_val_literal() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_val_literal(id_); } /**< Forward to @ref Tree::is_val_literal(). Node must be readable. */ C4_ALWAYS_INLINE bool is_key_folded() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_key_folded(id_); } /**< Forward to @ref Tree::is_key_folded(). Node must be readable. */ C4_ALWAYS_INLINE bool is_val_folded() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_val_folded(id_); } /**< Forward to @ref Tree::is_val_folded(). Node must be readable. */ C4_ALWAYS_INLINE bool is_key_squo() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_key_squo(id_); } /**< Forward to @ref Tree::is_key_squo(). Node must be readable. */ C4_ALWAYS_INLINE bool is_val_squo() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_val_squo(id_); } /**< Forward to @ref Tree::is_val_squo(). Node must be readable. */ C4_ALWAYS_INLINE bool is_key_dquo() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_key_dquo(id_); } /**< Forward to @ref Tree::is_key_dquo(). Node must be readable. */ C4_ALWAYS_INLINE bool is_val_dquo() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_val_dquo(id_); } /**< Forward to @ref Tree::is_val_dquo(). Node must be readable. */ C4_ALWAYS_INLINE bool is_key_plain() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_key_plain(id_); } /**< Forward to @ref Tree::is_key_plain(). Node must be readable. */ C4_ALWAYS_INLINE bool is_val_plain() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_val_plain(id_); } /**< Forward to @ref Tree::is_val_plain(). Node must be readable. */ C4_ALWAYS_INLINE bool is_key_quoted() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_key_quoted(id_); } /**< Forward to @ref Tree::is_key_quoted(). Node must be readable. */ C4_ALWAYS_INLINE bool is_val_quoted() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_val_quoted(id_); } /**< Forward to @ref Tree::is_val_quoted(). Node must be readable. */ C4_ALWAYS_INLINE bool is_quoted() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_quoted(id_); } /**< Forward to @ref Tree::is_quoted(). Node must be readable. */ /** @} */ public: /** @name hierarchy predicates */ /** @{ */ // vertically aligned to highlight differences. // documentation to the right --> C4_ALWAYS_INLINE bool is_root() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_root(id_); } /**< Forward to @ref Tree::is_root(). Node must be readable. */ C4_ALWAYS_INLINE bool has_parent() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->has_parent(id_); } /**< Forward to @ref Tree::has_parent() Node must be readable. */ C4_ALWAYS_INLINE bool is_ancestor(ConstImpl const& ancestor) const RYML_NOEXCEPT { this_assert_readable_(); return tree_->is_ancestor(id_, ancestor.m_id); } /**< Forward to @ref Tree::is_ancestor() Node must be readable. */ C4_ALWAYS_INLINE bool has_child(ConstImpl const& n) const RYML_NOEXCEPT { this_assert_readable_(); return n.readable() ? tree_->has_child(id_, n.m_id) : false; } /**< Forward to @ref Tree::has_child(). Node must be readable. */ C4_ALWAYS_INLINE bool has_child(id_type node) const RYML_NOEXCEPT { this_assert_readable_(); return tree_->has_child(id_, node); } /**< Forward to @ref Tree::has_child(). Node must be readable. */ C4_ALWAYS_INLINE bool has_child(csubstr name) const RYML_NOEXCEPT { this_assert_readable_(); return tree_->has_child(id_, name); } /**< Forward to @ref Tree::has_child(). Node must be readable. */ C4_ALWAYS_INLINE bool has_children() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->has_children(id_); } /**< Forward to @ref Tree::has_children(). Node must be readable. */ C4_ALWAYS_INLINE bool has_sibling(ConstImpl const& n) const RYML_NOEXCEPT { this_assert_readable_(); return n.readable() ? tree_->has_sibling(id_, n.m_id) : false; } /**< Forward to @ref Tree::has_sibling(). Node must be readable. */ C4_ALWAYS_INLINE bool has_sibling(id_type node) const RYML_NOEXCEPT { this_assert_readable_(); return tree_->has_sibling(id_, node); } /**< Forward to @ref Tree::has_sibling(). Node must be readable. */ C4_ALWAYS_INLINE bool has_sibling(csubstr name) const RYML_NOEXCEPT { this_assert_readable_(); return tree_->has_sibling(id_, name); } /**< Forward to @ref Tree::has_sibling(). Node must be readable. */ C4_ALWAYS_INLINE bool has_other_siblings() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->has_other_siblings(id_); } /**< Forward to @ref Tree::has_other_siblings(). Node must be readable. */ /** @} */ public: /** @name hierarchy getters */ /** @{ */ // vertically aligned to highlight differences. // documentation to the right --> C4_ALWAYS_INLINE id_type num_children() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->num_children(id_); } /**< O(num_children). Forward to @ref Tree::num_children(). */ C4_ALWAYS_INLINE id_type num_siblings() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->num_siblings(id_); } /**< O(num_children). Forward to @ref Tree::num_siblings(). */ C4_ALWAYS_INLINE id_type num_other_siblings() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->num_other_siblings(id_); } /**< O(num_siblings). Forward to @ref Tree::num_other_siblings(). */ C4_ALWAYS_INLINE id_type child_pos(ConstImpl const& n) const RYML_NOEXCEPT { this_assert_readable_(); RYML_ASSERT_VISIT_CB_(tree_->m_callbacks, n.readable(), n.tree(), n.id()); return tree_->child_pos(id_, n.m_id); } /**< O(num_children). Forward to @ref Tree::child_pos(). */ C4_ALWAYS_INLINE id_type sibling_pos(ConstImpl const& n) const RYML_NOEXCEPT { this_assert_readable_(); RYML_ASSERT_VISIT_CB_(tree_->callbacks(), n.readable(), n.tree(), n.id()); return tree_->child_pos(tree_->parent(id_), n.m_id); } /**< O(num_siblings). Forward to @ref Tree::sibling_pos(). */ C4_ALWAYS_INLINE id_type depth_asc() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->depth_asc(id_); } /** O(log(num_nodes)). Forward to Tree::depth_asc(). Node must be readable. */ C4_ALWAYS_INLINE id_type depth_desc() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->depth_desc(id_); } /** O(num_nodes). Forward to Tree::depth_desc(). Node must be readable. */ /** @} */ public: /** @name locations */ /** @{ */ Location location(Parser const& parser) const { this_assert_readable_(); return tree_->location(parser, id_); } /** @} */ public: /** @name deserialization: fully checked for lazy code * * These methods raise an error if the deserialization failed or * optionally if the node is not readable. * */ /** @{ */ /** (1) deserialize the node's contents (val or container) to the * given variable, forwarding to the user-overrideable @ref read() * function, which can be for ConstNodeRef (see @ref * doc_serialization_node_read) or for tree+id (see @ref * doc_serialization_tree_read). This method differs from @ref * ConstNodeRef::deserialize() in that here the error callback is * called if the deserialization failed, or (optionally) the node * is not readable. */ template void load(T *v, bool check_readable=true) const { if(check_readable) check_val_(); else assert_val_(); // assert otherwise // we can call read() directly because we checked everything // (or the caller told us so) // use the adapter ctor to accomodate legacy read() implementations const ReadResult result(read((ConstImpl const&)*this, v), id_); if C4_UNLIKELY(!result) err_visit_(tree_, result.node, "could not deserialize node"); } /** (2) like (1), but for wrapper tag types such as @ref * c4::fmt::base64() */ template void load(Wrapper const& wrapper, bool check_readable=true) const { RYML_CHECK_TYPE_IS_WRAPPER_LIKE_(Wrapper); if(check_readable) check_val_(); else assert_val_(); // assert otherwise // we can call read() directly because we checked everything // (or the caller told us so) // use the adapter ctor to accomodate legacy read() implementations const ReadResult result(read((ConstImpl const&)*this, wrapper), id_); if C4_UNLIKELY(!result) err_visit_(tree_, result.node, "could not deserialize node"); } /** (1) deserialize the node's key (necessarily a scalar) to the * given variable, forwarding to the user-overrideable @ref read_key() * function, which can be for ConstNodeRef (see @ref * doc_serialization_node_read) or for tree+id (see @ref * doc_serialization_tree_read). This method differs from @ref * ConstNodeRef::deserialize_key() in that here the error callback is * called if the deserialization failed, or (optionally) the node * is not readable. */ template void load_key(T *k, bool check_readable=true) const { if(check_readable) check_key_(); else assert_key_(); // assert otherwise // we can call read_key() directly because we checked // everything (or the caller told us so) // use the adapter ctor to accomodate legacy read_key() implementations const ReadResult result(read_key((ConstImpl const&)*this, k), id_); if C4_UNLIKELY(!result) err_visit_(tree_, result.node, "could not deserialize key"); } /** (2) like (1), but for wrapper tag types such as @ref * c4::fmt::base64() */ template void load_key(Wrapper const& wrapper, bool check_readable=true) const { RYML_CHECK_TYPE_IS_WRAPPER_LIKE_(Wrapper); if(check_readable) check_key_(); else assert_key_(); // assert otherwise // we can call read_key() directly because we checked // everything (or the caller told us so) // use the adapter ctor to accomodate legacy read_key() implementations const ReadResult result(read_key((ConstImpl const&)*this, wrapper), id_); if C4_UNLIKELY(!result) err_visit_(tree_, result.node, "could not deserialize key"); } /** @} */ public: /** @name deserialization: asserts node readability, returns success status */ /** @{ */ /** (1) deserialize the node's contents (val or container) to the * given variable, forwarding to the user-overrideable @ref read() * function (see @ref doc_serialization_node_read). * @return a @ref ReadResult with the deserialization status. */ template C4_NODISCARD ReadResult deserialize(T *v) const { assert_val_(); // use the adapter ctor to accomodate legacy read() implementations return ReadResult(read((ConstImpl const&)*this, v), id_); } /** (2) like (1), but for wrapper tag types such as @ref * c4::fmt::base64() */ template C4_NODISCARD ReadResult deserialize(Wrapper const& wrapper) const { RYML_CHECK_TYPE_IS_WRAPPER_LIKE_(Wrapper); assert_val_(); // use the adapter ctor to accomodate legacy read() implementations return ReadResult(read((ConstImpl const&)*this, wrapper), id_); } /** (1) deserialize the node's key (necessarily a scalar) to the * given variable, forwarding to the user-overrideable @ref * read_key() function (see @ref doc_serialization_node_read). * * @return a @ref ReadResult with the deserialization status. */ template C4_NODISCARD ReadResult deserialize_key(T *v) const { assert_key_(); // use the adapter ctor to accomodate legacy read_key() implementations return ReadResult(read_key((ConstImpl const&)*this, v), id_); } /** (2) like (1), but for wrapper tag types such as @ref * c4::fmt::base64() */ template C4_NODISCARD ReadResult deserialize_key(Wrapper const& wrapper) const { RYML_CHECK_TYPE_IS_WRAPPER_LIKE_(Wrapper); assert_key_(); // use the adapter ctor to accomodate legacy read_key() implementations return ReadResult(read_key((ConstImpl const&)*this, wrapper), id_); } /** @} */ public: /** @name lookup and deserialize */ /** @{ */ /** (1) find a child by name and deserialize its contents to the * given variable (ie call .deserialize() on the child if it * exists). Otherwise, the variable is kept unchanged. * * @return a @ref ReadResult set with this node's id if no child * exists, or the ReadResult from the deserialization. * * @see see also @ref ConstNodeRef::find_child_r() */ template C4_NODISCARD C4_ALWAYS_INLINE ReadResult deserialize_child(csubstr child_key, T *v) const { this_assert_readable_(); ConstImpl ch; ReadResult r = this_->find_child_r(child_key, &ch); if(r) r = ch.deserialize(v); return r; } /** (2) like (1), but assign from fallback if no such child exists. */ template C4_NODISCARD C4_ALWAYS_INLINE ReadResult deserialize_child(csubstr child_key, T *v, T const& fallback) const { this_assert_readable_(); ConstImpl ch; if(this_->find_child_r(child_key, &ch)) return ch.deserialize(v); *v = fallback; return ReadResult(); } /** (3) like (1), but for wrapper tag types such as @ref c4::fmt::base64() */ template C4_NODISCARD C4_ALWAYS_INLINE ReadResult deserialize_child(csubstr child_key, Wrapper const& v) const { this_assert_readable_(); ConstImpl ch; ReadResult r = this_->find_child_r(child_key, &ch); if(r) r = ch.deserialize(v); return r; } /** (1) find a child by position and deserialize its contents to * the given variable (ie call .deserialize() on the child if it * exists). Otherwise, the variable is kept unchanged. * * @return a @ref ReadResult set with this node's id if no child * exists, or the ReadResult from the deserialization. * * @see see also @ref ConstNodeRef::child_r() */ template C4_NODISCARD C4_ALWAYS_INLINE ReadResult deserialize_child(id_type child_pos, T *v) const { this_assert_readable_(); ConstImpl ch; ReadResult r = this_->child_r(child_pos, &ch); if(r) r = ch.deserialize(v); return r; } /** (2) like (1), but assign from fallback if no such child exists */ template C4_NODISCARD C4_ALWAYS_INLINE ReadResult deserialize_child(id_type child_pos, T *v, T const& fallback) const { this_assert_readable_(); ConstImpl ch; if(this_->child_r(child_pos, &ch)) return ch.deserialize(v); *v = fallback; return ReadResult(); } /** (3) like (1), but for wrapper tag types such as @ref * c4::fmt::base64() */ template C4_NODISCARD C4_ALWAYS_INLINE ReadResult deserialize_child(id_type child_pos, Wrapper const& wrapper) const { this_assert_readable_(); ConstImpl ch; ReadResult r = this_->child_r(child_pos, &ch); if(r) r = ch.deserialize(wrapper); return r; } /** @} */ public: C4_SUPPRESS_WARNING_PUSH C4_SUPPRESS_WARNING_GCC_CLANG("-Wdeprecated") C4_SUPPRESS_WARNING_GCC_CLANG("-Wdeprecated-declarations") C4_SUPPRESS_WARNING_MSVC(4996) // deprecated /** @name legacy operators */ /** @{ */ template RYML_LEGACY_OPERATOR("use .load()") Impl const& operator>> (T &v) const { load(&v); return (Impl const&)*this; } template RYML_LEGACY_OPERATOR("use .load()") Impl const& operator>> (T const& wrapper) const { load(wrapper); return (Impl const&)*this; } template RYML_LEGACY_OPERATOR("use .load_key()") Impl const& operator>> (Key const& v) const { load_key(&v.k); return (Impl const&)*this; } /** @} */ C4_SUPPRESS_WARNING_POP protected: // error helpers void check_val_() const { if C4_UNLIKELY(!tree_) err_basic_("node not readable"); else if C4_UNLIKELY(!(((Impl const* C4_RESTRICT)this)->readable())) err_visit_(tree_, id_, "node not readable"); else if C4_UNLIKELY(!(tree_->type(id_) & (VAL|MAP|SEQ))) err_visit_(tree_, id_, "node has no contents"); } void check_key_() const { if C4_UNLIKELY(!tree_) err_basic_("node not readable"); else if C4_UNLIKELY(!(((Impl const* C4_RESTRICT)this)->readable())) err_visit_(tree_, id_, "node not readable"); else if C4_UNLIKELY(!(tree_->type(id_) & KEY)) err_visit_(tree_, id_, "node has no key"); } C4_NORETURN C4_NO_INLINE C4_COLD static void err_basic_(const char *msg) { RYML_ERR_BASIC_(msg); } C4_NORETURN C4_NO_INLINE C4_COLD static void err_visit_(Tree const *tree, id_type id, const char *msg) { RYML_ERR_VISIT_CB_(tree->m_callbacks, tree, id, msg); } #if RYML_USE_ASSERT void assert_val_() const { check_val_(); } void assert_key_() const { check_key_(); } #else C4_ALWAYS_INLINE void assert_val_() const noexcept {} C4_ALWAYS_INLINE void assert_key_() const noexcept {} #endif public: // deprecated functions // these functions will be removed in future releases. If you // disagree with a particular function being deprecated, let us // know by opening a new issue at https://github.com/biojppm/rapidyaml/issues /** @cond dev */ // LCOV_EXCL_START C4_SUPPRESS_WARNING_PUSH C4_SUPPRESS_WARNING_GCC_CLANG("-Wdeprecated") C4_SUPPRESS_WARNING_GCC_CLANG("-Wdeprecated-declarations") C4_SUPPRESS_WARNING_MSVC(4996) // deprecated RYML_DEPRECATED("use .type().type_str(buf)") const char* type_str() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->type_str(id_); } /**< Forward to @ref Tree::type_str(). Node must be readable. */ RYML_DEPRECATED("use has_other_siblings()") bool has_siblings() const RYML_NOEXCEPT { this_assert_readable_(); return tree_->has_siblings(id_); } RYML_DEPRECATED("use has_key_anchor()") bool is_key_anchor() const noexcept { this_assert_readable_(); return tree_->has_key_anchor(id_); } RYML_DEPRECATED("use has_val_anchor()") bool is_val_hanchor() const noexcept { this_assert_readable_(); return tree_->has_val_anchor(id_); } RYML_DEPRECATED("use has_anchor()") bool is_anchor() const noexcept { this_assert_readable_(); return tree_->has_anchor(id_); } RYML_DEPRECATED("use has_anchor() || is_ref()") bool is_anchor_or_ref() const noexcept { this_assert_readable_(); return tree_->is_anchor_or_ref(id_); } template RYML_DEPRECATED("use .deserialize_child()") bool get_if(csubstr name, T *var) const { this_assert_readable_(); ConstImpl ch = ((ConstImpl const*)this)->find_child(name); if(ch.readable()) { ch.load(var); return true; } return false; } template RYML_DEPRECATED("use .deserialize_child()") bool get_if(id_type pos, T *var) const { this_assert_readable_(); ConstImpl ch = ((ConstImpl const*)this)->child(pos); if(ch.readable()) { ch.load(var); return true; } return false; } template RYML_DEPRECATED("use .deserialize_child()") bool get_if(csubstr name, T *var, T const& fallback) const { if(get_if(name, var)) return true; *var = fallback; return false; } template RYML_DEPRECATED("use .deserialize_child()") bool get_if(id_type pos, T *var, T const& fallback) const { if(get_if(pos, var)) return true; *var = fallback; return false; } template RYML_DEPRECATED("") bool visit(Visitor fn, id_type indentation_level=0, bool skip_root=true) const RYML_NOEXCEPT { this_assert_readable_(); return detail::_visit(*(ConstImpl const*)this, fn, indentation_level, skip_root); } template RYML_DEPRECATED("") auto visit(Visitor fn, id_type indentation_level = 0, bool skip_root = true) RYML_NOEXCEPT -> typename std ::enable_if::value, bool>::type { this_assert_readable_(); return detail::_visit(*(Impl *)this, fn, indentation_level, skip_root); } template RYML_DEPRECATED("") bool visit_stacked(Visitor fn, id_type indentation_level=0, bool skip_root=true) const RYML_NOEXCEPT { this_assert_readable_(); return detail::_visit_stacked(*(ConstImpl const*)this, fn, indentation_level, skip_root); } template RYML_DEPRECATED("") auto visit_stacked(Visitor fn, id_type indentation_level=0, bool skip_root=true) RYML_NOEXCEPT -> typename std ::enable_if::value, bool>::type { this_assert_readable_(); return detail::_visit_stacked(*(Impl*)this, fn, indentation_level, skip_root); } /** @endcond */ // LCOV_EXCL_STOP C4_SUPPRESS_WARNING_POP #undef this_assert_readable_ #undef this_ #undef mtree_ #undef tree_ #undef id_ C4_SUPPRESS_WARNING_GCC_CLANG_POP }; } // detail //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** Holds a pointer to an existing tree, and a node id. It can be used * only to read from the tree. * * @warning The lifetime of the tree must be larger than that of this * object. It is up to the user to ensure that this happens. */ class RYML_EXPORT ConstNodeRef : public detail::RoNodeMethods // NOLINT { public: using tree_type = Tree const; public: Tree const* C4_RESTRICT m_tree; id_type m_id; private: friend NodeRef; friend struct detail::RoNodeMethods; public: /** @name construction */ /** @{ */ ConstNodeRef() noexcept : m_tree(nullptr), m_id(NONE) {} ConstNodeRef(Tree const &t) noexcept : m_tree(&t), m_id(t .root_id()) {} ConstNodeRef(Tree const *t) noexcept : m_tree(t ), m_id(t->root_id()) {} ConstNodeRef(Tree const *t, id_type id) noexcept : m_tree(t), m_id(id) {} ConstNodeRef(ConstNodeRef const&) noexcept = default; ConstNodeRef(ConstNodeRef &&) noexcept = default; inline ConstNodeRef(NodeRef const&) noexcept; inline ConstNodeRef(NodeRef &&) noexcept; /** @} */ public: /** @name assignment */ /** @{ */ ConstNodeRef& operator= (ConstNodeRef const&) noexcept = default; ConstNodeRef& operator= (ConstNodeRef &&) noexcept = default; ConstNodeRef& operator= (NodeRef const&) noexcept; ConstNodeRef& operator= (NodeRef &&) noexcept; /** @} */ public: /** @name state queries * * see @ref NodeRef for an explanation on what these states mean */ /** @{ */ C4_ALWAYS_INLINE bool invalid() const noexcept { return (!m_tree) || (m_id == NONE); } /** because a ConstNodeRef cannot be used to write to the tree, * readable() has the same meaning as !invalid() */ C4_ALWAYS_INLINE bool readable() const noexcept { return m_tree != nullptr && m_id != NONE; } /** because a ConstNodeRef cannot be used to write to the tree, it can never be a seed. * This method is provided for API equivalence between ConstNodeRef and NodeRef. */ constexpr static C4_ALWAYS_INLINE bool is_seed() noexcept { return false; } /** @} */ private: void assert_readable_() const { RYML_ASSERT_BASIC_(m_tree != nullptr); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, m_id != NONE && (m_id < m_tree->capacity()), m_tree, m_id); } void check_readable_() const { if C4_UNLIKELY(!m_tree) RYML_ERR_BASIC_("invalid node"); if C4_UNLIKELY(!m_tree || m_id == NONE || (m_id > m_tree->capacity())) RYML_ERR_VISIT_CB_(m_tree->m_callbacks, m_tree, m_id, "invalid node"); } public: /** @name member getters */ /** @{ */ C4_ALWAYS_INLINE Tree const* tree() const noexcept { return m_tree; } C4_ALWAYS_INLINE id_type id() const noexcept { return m_id; } /** @} */ public: /** @name comparisons */ /** @{ */ C4_ALWAYS_INLINE bool operator== (ConstNodeRef const& that) const RYML_NOEXCEPT { return that.m_tree == m_tree && m_id == that.m_id; } C4_ALWAYS_INLINE bool operator!= (ConstNodeRef const& that) const RYML_NOEXCEPT { return ! this->operator== (that); } /** @} */ public: /** @name node property getters */ /** @{ */ C4_ALWAYS_INLINE NodeData const* get() const RYML_NOEXCEPT { return readable() ? m_tree->get(m_id) : nullptr; } /**< Forward to @ref Tree::type(). Node must be readable. */ /** @} */ public: /** @name hierarchy getters */ /** @{ */ // vertically aligned to highlight differences. // documentation to the right --> C4_ALWAYS_INLINE ConstNodeRef parent() const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->parent(m_id)}; } /**< Forward to @ref Tree::parent(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef first_child() const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->first_child(m_id)}; } /**< Forward to @ref Tree::first_child(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef last_child() const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->last_child (m_id)}; } /**< Forward to @ref Tree::last_child(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef child(id_type pos) const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->child(m_id, pos)}; } /**< Forward to @ref Tree::child(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef find_child(csubstr name) const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->find_child(m_id, name)}; } /**< Forward to @ref Tree::find_child(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef prev_sibling() const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->prev_sibling(m_id)}; } /**< Forward to @ref Tree::prev_sibling(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef next_sibling() const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->next_sibling(m_id)}; } /**< Forward to @ref Tree::next_sibling(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef first_sibling() const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->first_sibling(m_id)}; } /**< Forward to @ref Tree::first_sibling(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef last_sibling () const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->last_sibling(m_id)}; } /**< Forward to @ref Tree::last_sibling(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef sibling(id_type pos) const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->sibling(m_id, pos)}; } /**< Forward to @ref Tree::sibling(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef find_sibling(csubstr name) const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->find_sibling(m_id, name)}; } /**< Forward to @ref Tree::find_sibling(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef ancestor_doc() const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->ancestor_doc(m_id)}; } /**< Forward to @ref Tree::ancestor_doc(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef doc(id_type i) const RYML_NOEXCEPT { RYML_ASSERT_BASIC_(m_tree); return {m_tree, m_tree->doc(i)}; } /**< Forward to @ref Tree::doc(). Node must be readable. succeeds even when the node may have invalid or seed id */ C4_NODISCARD C4_ALWAYS_INLINE ReadResult child_r(id_type pos, ConstNodeRef *child) const RYML_NOEXCEPT { assert_readable_(); child->m_tree = m_tree; ReadResult result = m_tree-> child_r(m_id, pos, &child->m_id); return result; }; /**< Forward to @ref Tree::child_r(). Node must be readable. */ C4_NODISCARD C4_ALWAYS_INLINE ReadResult find_child_r(csubstr name, ConstNodeRef *child) const RYML_NOEXCEPT { assert_readable_(); child->m_tree = m_tree; ReadResult result = m_tree->find_child_r(m_id, name, &child->m_id); return result; }; /**< Forward to @ref Tree::find_child_r(). Node must be readable. */ C4_NODISCARD C4_ALWAYS_INLINE ReadResult sibling_r(id_type pos, ConstNodeRef *sibling) const RYML_NOEXCEPT { assert_readable_(); sibling->m_tree = m_tree; ReadResult result = m_tree-> sibling_r(m_id, pos, &sibling->m_id); return result; }; /**< Forward to @ref Tree::sibling_r(). Node must be readable. */ C4_NODISCARD C4_ALWAYS_INLINE ReadResult find_sibling_r(csubstr name, ConstNodeRef *sibling) const RYML_NOEXCEPT { assert_readable_(); sibling->m_tree = m_tree; ReadResult result = m_tree->find_sibling_r(m_id, name, &sibling->m_id); return result; }; /**< Forward to @ref Tree::find_sibling_r(). Node must be readable. */ /** @} */ public: /** @name square_brackets * operator[] */ /** @{ */ /** Find a child by key; complexity is O(num_children). * * Behaves similar to the non-const overload, but further asserts * that the returned node is readable (because it can never be in * a seed state). The assertion is performed only if @ref * RYML_USE_ASSERT is set to true. As with the non-const overload, * it is UB to use the return value if it is not valid. * * @see https://github.com/biojppm/rapidyaml/issues/389 */ C4_ALWAYS_INLINE ConstNodeRef operator[] (csubstr key) const RYML_NOEXCEPT { assert_readable_(); id_type ch = m_tree->find_child(m_id, key); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, ch != NONE, m_tree, m_id); return {m_tree, ch}; } /** Find a child by position; complexity is O(pos). * * Behaves similar to the non-const overload, but further asserts * that the returned node is readable (because it can never be in * a seed state). This assertion is performed only if @ref * RYML_USE_ASSERT is set to true. As with the non-const overload, * it is UB to use the return value if it is not valid. * * @see https://github.com/biojppm/rapidyaml/issues/389 */ C4_ALWAYS_INLINE ConstNodeRef operator[] (id_type pos) const RYML_NOEXCEPT { assert_readable_(); id_type ch = m_tree->child(m_id, pos); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, ch != NONE, m_tree, m_id); return {m_tree, ch}; } /** @} */ public: /** @name at * * These functions are the analogue to operator[], with the * difference that they emit an error instead of an * assertion. That is, if any of the pre or post conditions is * violated, an error is always emitted (resulting in a call to * the error callback). * * @{ */ /** Get a child by name, with error checking; complexity is * O(num_children). * * Behaves as operator[](csubstr) const, but always raises an * error (even when RYML_USE_ASSERT is set to false) when the * returned node does not exist, or when this node is not * readable, or when it is not a map. This behaviour is similar to * std::vector::at(), but the error consists in calling the error * callback instead of directly raising an exception. */ ConstNodeRef at(csubstr key) const { check_readable_(); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, m_tree->is_map(m_id), m_tree, m_id); id_type ch = m_tree->find_child(m_id, key); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, ch != NONE, m_tree, m_id); return {m_tree, ch}; } /** Get a child by position, with error checking; complexity is * O(pos). * * Behaves as operator[](id_type) const, but always raises an error * (even when RYML_USE_ASSERT is set to false) when the returned * node does not exist, or when this node is not readable, or when * it is not a container. This behaviour is similar to * std::vector::at(), but the error consists in calling the error * callback instead of directly raising an exception. */ ConstNodeRef at(id_type pos) const { check_readable_(); const id_type cap = m_tree->capacity(); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, (pos >= 0 && pos < cap), m_tree, m_id); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, m_tree->is_container(m_id), m_tree, m_id); const id_type ch = m_tree->child(m_id, pos); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, ch != NONE, m_tree, m_id); return {m_tree, ch}; } /** @} */ public: /** @name iteration */ /** @{ */ using iterator = detail::child_iterator; using const_iterator = detail::child_iterator; using children_view = detail::children_view; using const_children_view = detail::children_view; C4_ALWAYS_INLINE const_iterator begin() const RYML_NOEXCEPT { assert_readable_(); return const_iterator(m_tree, m_tree->first_child(m_id)); } /**< get an iterator to the first child */ C4_ALWAYS_INLINE const_iterator cbegin() const RYML_NOEXCEPT { assert_readable_(); return const_iterator(m_tree, m_tree->first_child(m_id)); } /**< get an iterator to the first child */ C4_ALWAYS_INLINE const_iterator end() const RYML_NOEXCEPT { assert_readable_(); return const_iterator(m_tree, NONE); } /**< get an iterator to after the last child */ C4_ALWAYS_INLINE const_iterator cend() const RYML_NOEXCEPT { assert_readable_(); return const_iterator(m_tree, NONE); } /**< get an iterator to after the last child */ C4_ALWAYS_INLINE const_children_view children() const RYML_NOEXCEPT { assert_readable_(); return detail::make_children_view(m_tree, m_id); } /**< get an iterable view over children */ C4_ALWAYS_INLINE const_children_view cchildren() const RYML_NOEXCEPT { assert_readable_(); return detail::make_children_view(m_tree, m_id); } /**< get an iterable view over children */ C4_ALWAYS_INLINE const_children_view siblings() const RYML_NOEXCEPT { assert_readable_(); return detail::make_siblings_view(m_tree, m_id); } /** get an iterable view over all siblings (including the calling node) */ C4_ALWAYS_INLINE const_children_view csiblings() const RYML_NOEXCEPT { assert_readable_(); return detail::make_siblings_view(m_tree, m_id); } /** get an iterable view over all siblings (including the calling node) */ /** @} */ public: // deprecated functions // these functions will be removed in future releases. If you // disagree with a particular function being deprecated, let us // know by opening a new issue at https://github.com/biojppm/rapidyaml/issues /** @cond dev */ // LCOV_EXCL_START C4_SUPPRESS_WARNING_PUSH C4_SUPPRESS_WARNING_GCC_CLANG("-Wdeprecated") C4_SUPPRESS_WARNING_GCC_CLANG("-Wdeprecated-declarations") C4_SUPPRESS_WARNING_MSVC(4996) // deprecated RYML_DEPRECATED("use ConstNodeRef()") ConstNodeRef(std::nullptr_t) noexcept : m_tree(nullptr), m_id(NONE) {} RYML_DEPRECATED("use node = {}") ConstNodeRef& operator= (std::nullptr_t) noexcept { m_tree = nullptr; m_id = NONE; return *this; } RYML_DEPRECATED("use one of readable(), is_seed() or !invalid()") bool valid() const noexcept { return m_tree != nullptr && m_id != NONE; } RYML_DEPRECATED("use invalid()") bool operator== (std::nullptr_t) const noexcept { return m_tree == nullptr || m_id == NONE; } RYML_DEPRECATED("use !invalid()") bool operator!= (std::nullptr_t) const noexcept { return !(m_tree == nullptr || m_id == NONE); } RYML_DEPRECATED("use (this->val() == s)") bool operator== (csubstr s) const RYML_NOEXCEPT { RYML_ASSERT_BASIC_(m_tree); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, m_id != NONE, m_tree, NONE); return m_tree->val(m_id) == s; } RYML_DEPRECATED("use (this->val() != s)") bool operator!= (csubstr s) const RYML_NOEXCEPT { RYML_ASSERT_BASIC_(m_tree); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, m_id != NONE, m_tree, NONE); return m_tree->val(m_id) != s; } /** @endcond */ // LCOV_EXCL_STOP }; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // NOLINTBEGIN(cppcoreguidelines-c-copy-assignment-signature,misc-unconventional-assign-operator) /** A reference to a node in an existing yaml tree, offering a more * convenient API than the index-based API used in the tree. * * Unlike its imutable ConstNodeRef peer, a NodeRef can be used to * mutate the tree, both by writing to existing nodes and by creating * new nodes to subsequently write to. Semantically, a NodeRef * object can be in one of three states: * * ```text * invalid := not pointing at anything * readable := points at an existing tree/node * seed := points at an existing tree, and the node * may come to exist, if we write to it. * ``` * * So both `readable` and `seed` are states where the node is also `valid`. * * ```cpp * Tree t = parse_in_arena("{a: b}"); * NodeRef invalid; // not pointing at anything. * NodeRef readable = t["a"]; // also valid, because "a" exists * NodeRef seed = t["none"]; // also valid, but is seed because "none" is not in the map * ``` * * When the object is in seed state, using it to read from the tree is * UB. The seed node can be used to write to the tree, provided that * its create() method is called prior to writing, which happens in * most modifying methods in NodeRef. * * It is the owners's responsibility to verify that an existing * node is readable before subsequently using it to read from the * tree. * * @warning The lifetime of the tree must be larger than that of this * object. It is up to the user to ensure that this happens. */ class RYML_EXPORT NodeRef : public detail::RoNodeMethods // NOLINT { public: using tree_type = Tree; using base_type = detail::RoNodeMethods; private: Tree *C4_RESTRICT m_tree; id_type m_id; /** This member is used to enable lazy operator[] writing. * * When a child with a key or index is not found, m_id is set to * the id of the parent and the asked-for key or index are stored * in this member until a write does happen. Then it is given as * key or index for creating the child. * * When a key is used, the csubstr stores it (so the csubstr's * string is non-null and the csubstr's size is different from * NONE). When an index is used instead, the csubstr's string is * set to null, and only the csubstr's size is set to a value * different from NONE. * * Otherwise, when operator[] does find the child, then this member * is empty: m_seed.str is null and m_seed.len is NONE. */ csubstr m_seed; C4_ALWAYS_INLINE void _clear_seed() noexcept { // this must be done manually or an assert is triggered: m_seed.str = nullptr; m_seed.len = NONE; } friend ConstNodeRef; friend struct detail::RoNodeMethods; public: /** @name construction */ /** @{ */ NodeRef() noexcept : m_tree(nullptr), m_id(NONE), m_seed() { _clear_seed(); } NodeRef(Tree &t) noexcept : m_tree(&t), m_id(t .root_id()), m_seed() { _clear_seed(); } NodeRef(Tree *t) noexcept : m_tree(t ), m_id(t->root_id()), m_seed() { _clear_seed(); } NodeRef(Tree *t, id_type id) noexcept : m_tree(t), m_id(id), m_seed() { _clear_seed(); } NodeRef(Tree *t, id_type id, id_type seed_pos) noexcept : m_tree(t), m_id(id), m_seed() { m_seed.str = nullptr; m_seed.len = (size_t)seed_pos; } NodeRef(Tree *t, id_type id, csubstr seed_key) noexcept : m_tree(t), m_id(id), m_seed(seed_key) {} /** @} */ public: /** @name assignment */ /** @{ */ NodeRef(NodeRef const&) noexcept = default; NodeRef(NodeRef &&) noexcept = default; NodeRef& operator= (NodeRef const&) noexcept = default; NodeRef& operator= (NodeRef &&) noexcept = default; /** @} */ public: /** @name state_queries * @{ */ /** true if the object is not referring to any existing or seed node. @see the doc for @ref NodeRef */ bool invalid() const noexcept { return m_tree == nullptr || m_id == NONE; } /** true if the object is not invalid and in seed state. @see the doc for @ref NodeRef */ bool is_seed() const noexcept { return (m_tree != nullptr && m_id != NONE) && has_seed_(); } /** true if the object is not invalid and not in seed state. @see the doc for @ref NodeRef */ bool readable() const noexcept { return (m_tree != nullptr && m_id != NONE) && !has_seed_(); } /** @} */ private: C4_ALWAYS_INLINE bool valid_id_() const noexcept { return m_id != NONE && m_id < m_tree->capacity(); } C4_ALWAYS_INLINE bool has_seed_() const noexcept { return m_seed.str != nullptr || m_seed.len != (size_t)NONE; } void assert_readable_() const { RYML_ASSERT_BASIC_(m_tree != nullptr); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, valid_id_() && !has_seed_(), m_tree, m_id); } void check_readable_() const { if C4_UNLIKELY(!m_tree) err_basic_("invalid node"); if C4_UNLIKELY((m_id == NONE || (m_id > m_tree->capacity()) || (m_seed.str != nullptr || m_seed.len != (size_t)NONE))) err_visit_(m_tree, m_id, "invalid node"); } void check_writeable_() const { if C4_UNLIKELY(!m_tree) err_basic_("invalid node"); } void assert_writeable_() const { RYML_ASSERT_BASIC_(m_tree != nullptr); } public: /** @name comparisons */ /** @{ */ bool operator== (NodeRef const& that) const { if(m_tree == that.m_tree && m_id == that.m_id) { bool seed = is_seed(); if(seed == that.is_seed()) { if(seed) { return (m_seed.len == that.m_seed.len) && (m_seed.str == that.m_seed.str || m_seed == that.m_seed); // do strcmp only in the last resort } return true; } } return false; } bool operator!= (NodeRef const& that) const { return ! this->operator==(that); } bool operator== (ConstNodeRef const& that) const { return m_tree == that.m_tree && m_id == that.m_id && !is_seed(); } bool operator!= (ConstNodeRef const& that) const { return ! this->operator==(that); } /** @} */ public: /** @name node_property_getters * @{ */ C4_ALWAYS_INLINE id_type id() const noexcept { return m_id; } C4_ALWAYS_INLINE Tree const* tree() const noexcept { return m_tree; } C4_ALWAYS_INLINE Tree * tree() noexcept { return m_tree; } C4_ALWAYS_INLINE NodeData const* get() const RYML_NOEXCEPT { return readable() ? m_tree->get(m_id) : nullptr; } /**< Forward to @ref Tree::type(). Node must be readable. */ C4_ALWAYS_INLINE NodeData * get() RYML_NOEXCEPT { return readable() ? m_tree->get(m_id) : nullptr; } /**< Forward to @ref Tree::type(). Node must be readable. */ /** @} */ public: /** @name node_setters */ /** @{ */ /// if this node is in seed state, create the node in the tree void create() { RYML_ASSERT_BASIC_(m_tree != nullptr); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, m_id != NONE && m_id < m_tree->capacity(), m_tree, m_id); if(m_seed.str) // we have a seed key: use it to create the new map child { m_id = m_tree->append_child(m_id); m_tree->set_key(m_id, m_seed); m_seed.str = nullptr; m_seed.len = (size_t)NONE; } else if(m_seed.len != (size_t)NONE) // we have a seed index: create a seq child at that position { RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, (size_t)m_tree->num_children(m_id) == m_seed.len, m_tree, m_id); m_id = m_tree->append_child(m_id); m_seed.str = nullptr; m_seed.len = (size_t)NONE; } } void set_stream() { create(); m_tree->set_stream(m_id); } void set_doc() { create(); m_tree->set_doc(m_id); } void set_key(csubstr key) { create(); m_tree->set_key(m_id, key); } void set_key(csubstr key, NodeType more_flags) { create(); m_tree->set_key(m_id, key, more_flags); } void set_val(csubstr val) { create(); m_tree->set_val(m_id, val); } void set_val(csubstr val, NodeType more_flags) { create(); m_tree->set_val(m_id, val, more_flags); } void set_seq() { create(); m_tree->set_seq(m_id); } void set_seq(NodeType more_flags) { create(); m_tree->set_seq(m_id, more_flags); } void set_map() { create(); m_tree->set_map(m_id); } void set_map(NodeType more_flags) { create(); m_tree->set_map(m_id, more_flags); } void set_key_tag(csubstr key_tag) { create(); m_tree->set_key_tag(m_id, key_tag); } void set_val_tag(csubstr val_tag) { create(); m_tree->set_val_tag(m_id, val_tag); } void set_key_anchor(csubstr key_anchor) { create(); m_tree->set_key_anchor(m_id, key_anchor); } void set_val_anchor(csubstr val_anchor) { create(); m_tree->set_val_anchor(m_id, val_anchor); } void set_key_ref(csubstr key_ref) { create(); m_tree->set_key_ref(m_id, key_ref); } void set_val_ref(csubstr val_ref) { create(); m_tree->set_val_ref(m_id, val_ref); } void set_container_style(type_bits style) { create(); m_tree->set_container_style(m_id, style); } void set_key_style(type_bits style) { create(); m_tree->set_key_style(m_id, style); } void set_val_style(type_bits style) { create(); m_tree->set_val_style(m_id, style); } /** @} */ public: /** @name node_modifiers */ /** @{ */ void change_type(NodeType t) { assert_readable_(); m_tree->change_type(m_id, t); } /** remove the KEY (flags included) from a scalar */ void clear_key() { assert_readable_(); m_tree->_clear_key(m_id); } /** remove the VAL (flags included) from a scalar */ void clear_val() { assert_readable_(); m_tree->_clear_val(m_id); } /** remove the children from a scalar */ void clear_children() { assert_readable_(); m_tree->remove_children(m_id); } void clear_style(bool recurse=false) { assert_readable_(); m_tree->clear_style(m_id, recurse); } void set_style_conditionally(NodeType type_mask, NodeType rem_style_flags, NodeType add_style_flags, bool recurse=false) { assert_readable_(); m_tree->set_style_conditionally(m_id, type_mask, rem_style_flags, add_style_flags, recurse); } /** @} */ public: /** @name serialization */ /** @{ */ /** forward to @ref Tree::to_arena() . Serializes a scalar type to * the tree's arena. The type must be serializeable as a scalar. */ template csubstr to_arena(T const& C4_RESTRICT s) { RYML_ASSERT_BASIC_(m_tree); // no need for valid or readable return m_tree->to_arena(s); } template void save(T const& C4_RESTRICT k) { check_writeable_(); create(); write(*this, k); } template void save(T const& C4_RESTRICT k, NodeType style_flags) { check_writeable_(); create(); write(*this, k); RYML_ASSERT_BASIC_(!(style_flags & ~STYLE)); _add_flags(style_flags); } template void save_key(T const& C4_RESTRICT k) { check_writeable_(); create(); write_key(*this, k); } template void save_key(T const& C4_RESTRICT k, NodeType style_flags) { check_writeable_(); create(); write_key(*this, k); RYML_ASSERT_BASIC_(!(style_flags & ~STYLE)); _add_flags(style_flags); } /** serialize a variable to this node. If the variable is a * scalar, it is first serialized to the arena, and then assigned * to the node's val. Otherwise, the node will be made a * container, and its contents populated from the variable. */ template void set_serialized(T const& C4_RESTRICT v) { assert_writeable_(); create(); write(*this, v); } template void set_serialized(T const& C4_RESTRICT v, NodeType style_flags) { assert_writeable_(); create(); write(*this, v); RYML_ASSERT_BASIC_(!(style_flags & ~STYLE)); _add_flags(style_flags); } /** serialize a variable, then assign the result to the node's key * * @warning The variable must be serialized as a scalar, ie it * cannot be serialized as a container. */ template void set_key_serialized(T const& C4_RESTRICT k) { assert_writeable_(); create(); write_key(*this, k); } template void set_key_serialized(T const& C4_RESTRICT k, NodeType style_flags) { assert_writeable_(); create(); write_key(*this, k); RYML_ASSERT_BASIC_(!(style_flags & ~STYLE)); _add_flags(style_flags); } /** @} */ public: /** @name hierarchy getters */ /** @{ */ // vertically aligned to highlight differences. // documentation to the right --> C4_ALWAYS_INLINE NodeRef parent() RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->parent(m_id)}; } /**< Forward to @ref Tree::parent(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef parent() const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->parent(m_id)}; } /**< Forward to @ref Tree::parent(). Node must be readable. */ C4_ALWAYS_INLINE NodeRef first_child() RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->first_child(m_id)}; } /**< Forward to @ref Tree::first_child(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef first_child() const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->first_child(m_id)}; } /**< Forward to @ref Tree::first_child(). Node must be readable. */ C4_ALWAYS_INLINE NodeRef last_child() RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->last_child(m_id)}; } /**< Forward to @ref Tree::last_child(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef last_child() const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->last_child (m_id)}; } /**< Forward to @ref Tree::last_child(). Node must be readable. */ C4_ALWAYS_INLINE NodeRef child(id_type pos) RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->child(m_id, pos)}; } /**< Forward to @ref Tree::child(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef child(id_type pos) const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->child(m_id, pos)}; } /**< Forward to @ref Tree::child(). Node must be readable. */ C4_NODISCARD C4_ALWAYS_INLINE ReadResult child_r(id_type pos, NodeRef *child) RYML_NOEXCEPT { assert_readable_(); child->m_tree = m_tree; ReadResult result = m_tree->child_r(m_id, pos, &child->m_id); return result; }; /**< Forward to @ref Tree::child_r(). Node must be readable. */ C4_NODISCARD C4_ALWAYS_INLINE ReadResult child_r(id_type pos, ConstNodeRef *child) const RYML_NOEXCEPT { assert_readable_(); child->m_tree = m_tree; ReadResult result = m_tree->child_r(m_id, pos, &child->m_id); return result; }; /**< Forward to @ref Tree::child_r(). Node must be readable. */ C4_ALWAYS_INLINE NodeRef find_child(csubstr name) RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->find_child(m_id, name)}; } /**< Forward to @ref Tree::find_child(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef find_child(csubstr name) const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->find_child(m_id, name)}; } /**< Forward to @ref Tree::find_child(). Node must be readable. */ C4_NODISCARD C4_ALWAYS_INLINE ReadResult find_child_r(csubstr name, NodeRef *child) RYML_NOEXCEPT { assert_readable_(); child->m_tree = m_tree; ReadResult result = m_tree->find_child_r(m_id, name, &child->m_id); return result; }; /**< Forward to @ref Tree::find_child_r(). Node must be readable. */ C4_NODISCARD C4_ALWAYS_INLINE ReadResult find_child_r(csubstr name, ConstNodeRef *child) const RYML_NOEXCEPT { assert_readable_(); child->m_tree = m_tree; ReadResult result = m_tree->find_child_r(m_id, name, &child->m_id); return result; }; /**< Forward to @ref Tree::find_child_r(). Node must be readable. */ C4_ALWAYS_INLINE NodeRef prev_sibling() RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->prev_sibling(m_id)}; } /**< Forward to @ref Tree::prev_sibling(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef prev_sibling() const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->prev_sibling(m_id)}; } /**< Forward to @ref Tree::prev_sibling(). Node must be readable. */ C4_ALWAYS_INLINE NodeRef next_sibling() RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->next_sibling(m_id)}; } /**< Forward to @ref Tree::next_sibling(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef next_sibling() const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->next_sibling(m_id)}; } /**< Forward to @ref Tree::next_sibling(). Node must be readable. */ C4_ALWAYS_INLINE NodeRef first_sibling() RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->first_sibling(m_id)}; } /**< Forward to @ref Tree::first_sibling(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef first_sibling() const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->first_sibling(m_id)}; } /**< Forward to @ref Tree::first_sibling(). Node must be readable. */ C4_ALWAYS_INLINE NodeRef last_sibling() RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->last_sibling(m_id)}; } /**< Forward to @ref Tree::last_sibling(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef last_sibling() const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->last_sibling(m_id)}; } /**< Forward to @ref Tree::last_sibling(). Node must be readable. */ C4_ALWAYS_INLINE NodeRef sibling(id_type pos) RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->sibling(m_id, pos)}; } /**< Forward to @ref Tree::sibling(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef sibling(id_type pos) const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->sibling(m_id, pos)}; } /**< Forward to @ref Tree::sibling(). Node must be readable. */ C4_ALWAYS_INLINE ReadResult sibling_r(id_type pos, NodeRef *sibling) RYML_NOEXCEPT { assert_readable_(); sibling->m_tree = m_tree; ReadResult result = m_tree->sibling_r(m_id, pos, &sibling->m_id); return result; }; /**< Forward to @ref Tree::sibling_r(). Node must be readable. */ C4_ALWAYS_INLINE ReadResult sibling_r(id_type pos, ConstNodeRef *sibling) const RYML_NOEXCEPT { assert_readable_(); sibling->m_tree = m_tree; ReadResult result = m_tree->sibling_r(m_id, pos, &sibling->m_id); return result; }; /**< Forward to @ref Tree::sibling_r(). Node must be readable. */ C4_ALWAYS_INLINE NodeRef find_sibling(csubstr name) RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->find_sibling(m_id, name)}; } /**< Forward to @ref Tree::find_sibling(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef find_sibling(csubstr name) const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->find_sibling(m_id, name)}; } /**< Forward to @ref Tree::find_sibling(). Node must be readable. */ C4_ALWAYS_INLINE ReadResult find_sibling_r(csubstr name, NodeRef *sibling) RYML_NOEXCEPT { assert_readable_(); sibling->m_tree = m_tree; ReadResult result = m_tree->find_sibling_r(m_id, name, &sibling->m_id); return result; }; /**< Forward to @ref Tree::find_sibling_r(). Node must be readable. */ C4_ALWAYS_INLINE ReadResult find_sibling_r(csubstr name, ConstNodeRef *sibling) const RYML_NOEXCEPT { assert_readable_(); sibling->m_tree = m_tree; ReadResult result = m_tree->find_sibling_r(m_id, name, &sibling->m_id); return result; }; /**< Forward to @ref Tree::find_sibling_r(). Node must be readable. */ C4_ALWAYS_INLINE NodeRef ancestor_doc() RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->ancestor_doc(m_id)}; } /**< Forward to @ref Tree::ancestor_doc(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef ancestor_doc() const RYML_NOEXCEPT { assert_readable_(); return {m_tree, m_tree->ancestor_doc(m_id)}; } /**< Forward to @ref Tree::ancestor_doc(). Node must be readable. */ C4_ALWAYS_INLINE NodeRef doc(id_type i) RYML_NOEXCEPT { RYML_ASSERT_BASIC_(m_tree); return {m_tree, m_tree->doc(i)}; } /**< Forward to @ref Tree::doc(). Node must be readable. */ C4_ALWAYS_INLINE ConstNodeRef doc(id_type i) const RYML_NOEXCEPT { RYML_ASSERT_BASIC_(m_tree); return {m_tree, m_tree->doc(i)}; } /**< Forward to @ref Tree::doc(). Node must be readable. succeeds even when the node may have invalid or seed id */ /** @} */ public: /** @name square_brackets * operator[] */ /** @{ */ /** Find child by key; complexity is O(num_children). * * Returns the requested node, or an object in seed state if no * such child is found (see @ref NodeRef for an explanation of * what is seed state). When the object is in seed state, using it * to read from the tree is UB. The seed node can be used to write * to the tree provided that its create() method is called prior * to writing, which happens in most modifying methods in * NodeRef. It is the caller's responsibility to verify that the * returned node is readable before subsequently using it to read * from the tree. * * @warning the calling object must be readable. This precondition * is asserted. The assertion is performed only if @ref * RYML_USE_ASSERT is set to true. As with the non-const overload, * it is UB to call this method if the node is not readable. * * @see https://github.com/biojppm/rapidyaml/issues/389 */ C4_ALWAYS_INLINE NodeRef operator[] (csubstr key) RYML_NOEXCEPT { assert_readable_(); id_type ch = m_tree->find_child(m_id, key); return ch != NONE ? NodeRef(m_tree, ch) : NodeRef(m_tree, m_id, key); } /** Find child by position; complexity is O(pos). * * Returns the requested node, or an object in seed state if no * such child is found (see @ref NodeRef for an explanation of * what is seed state). When the object is in seed state, using it * to read from the tree is UB. The seed node can be used to write * to the tree provided that its create() method is called prior * to writing, which happens in most modifying methods in * NodeRef. It is the caller's responsibility to verify that the * returned node is readable before subsequently using it to read * from the tree. * * @warning the calling object must be readable. This precondition * is asserted. The assertion is performed only if @ref * RYML_USE_ASSERT is set to true. As with the non-const overload, * it is UB to call this method if the node is not readable. * * @see https://github.com/biojppm/rapidyaml/issues/389 */ C4_ALWAYS_INLINE NodeRef operator[] (id_type pos) RYML_NOEXCEPT { assert_readable_(); id_type ch = m_tree->child(m_id, pos); return ch != NONE ? NodeRef(m_tree, ch) : NodeRef(m_tree, m_id, pos); } /** Find a child by key; complexity is O(num_children). * * Behaves similar to the non-const overload, but further asserts * that the returned node is readable (because it can never be in * a seed state). The assertion is performed only if @ref * RYML_USE_ASSERT is set to true. As with the non-const overload, * it is UB to use the return value if it is not valid. * * @see https://github.com/biojppm/rapidyaml/issues/389 */ C4_ALWAYS_INLINE ConstNodeRef operator[] (csubstr key) const RYML_NOEXCEPT { assert_readable_(); id_type ch = m_tree->find_child(m_id, key); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, ch != NONE, m_tree, m_id); return {m_tree, ch}; } /** Find a child by position; complexity is O(pos). * * Behaves similar to the non-const overload, but further asserts * that the returned node is readable (because it can never be in * a seed state). This assertion is performed only if @ref * RYML_USE_ASSERT is set to true. As with the non-const overload, * it is UB to use the return value if it is not valid. * * @see https://github.com/biojppm/rapidyaml/issues/389 */ C4_ALWAYS_INLINE ConstNodeRef operator[] (id_type pos) const RYML_NOEXCEPT { assert_readable_(); id_type ch = m_tree->child(m_id, pos); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, ch != NONE, m_tree, m_id); return {m_tree, ch}; } /** @} */ public: /** @name at * * These functions are the analogue to operator[], with the * difference that they emit an error instead of an * assertion. That is, if any of the pre or post conditions is * violated, an error is always emitted (resulting in a call to * the error callback). * * @{ */ /** Find child by key; complexity is O(num_children). * * Returns the requested node, or an object in seed state if no * such child is found (see @ref NodeRef for an explanation of * what is seed state). When the object is in seed state, using it * to read from the tree is UB. The seed node can be subsequently * used to write to the tree provided that its create() method is * called prior to writing, which happens inside most mutating * methods in NodeRef. It is the caller's responsibility to verify * that the returned node is readable before subsequently using it * to read from the tree. * * @warning This method will call the error callback (regardless * of build type or of the value of RYML_USE_ASSERT) whenever any * of the following preconditions is violated: a) the object is * valid (points at a tree and a node), b) the calling object must * be readable (must not be in seed state), c) the calling object * must be pointing at a MAP node. The preconditions are similar * to the non-const operator[](csubstr), but instead of using * assertions, this function directly checks those conditions and * calls the error callback if any of the checks fail. * * @note since it is valid behavior for the returned node to be in * seed state, the error callback is not invoked when this * happens. */ C4_ALWAYS_INLINE NodeRef at(csubstr key) { RYML_CHECK_BASIC_(m_tree != nullptr); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, (m_id >= 0 && m_id < m_tree->capacity()), m_tree, m_id); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, readable(), m_tree, m_id); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, m_tree->is_map(m_id), m_tree, m_id); id_type ch = m_tree->find_child(m_id, key); return ch != NONE ? NodeRef(m_tree, ch) : NodeRef(m_tree, m_id, key); } /** Find child by position; complexity is O(pos). * * Returns the requested node, or an object in seed state if no * such child is found (see @ref NodeRef for an explanation of * what is seed state). When the object is in seed state, using it * to read from the tree is UB. The seed node can be used to write * to the tree provided that its create() method is called prior * to writing, which happens in most modifying methods in * NodeRef. It is the caller's responsibility to verify that the * returned node is readable before subsequently using it to read * from the tree. * * @warning This method will call the error callback (regardless * of build type or of the value of RYML_USE_ASSERT) whenever any * of the following preconditions is violated: a) the object is * valid (points at a tree and a node), b) the calling object must * be readable (must not be in seed state), c) the calling object * must be pointing at a MAP node. The preconditions are similar * to the non-const operator[](id_type), but instead of using * assertions, this function directly checks those conditions and * calls the error callback if any of the checks fail. * * @note since it is valid behavior for the returned node to be in * seed state, the error callback is not invoked when this * happens. */ C4_ALWAYS_INLINE NodeRef at(id_type pos) { RYML_CHECK_BASIC_(m_tree != nullptr); const id_type cap = m_tree->capacity(); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, (m_id >= 0 && m_id < cap), m_tree, m_id); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, (pos >= 0 && pos < cap), m_tree, m_id); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, readable(), m_tree, m_id); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, m_tree->is_container(m_id), m_tree, m_id); id_type ch = m_tree->child(m_id, pos); return ch != NONE ? NodeRef(m_tree, ch) : NodeRef(m_tree, m_id, pos); } /** Get a child by name, with error checking; complexity is * O(num_children). * * Behaves as operator[](csubstr) const, but always raises an * error (even when RYML_USE_ASSERT is set to false) when the * returned node does not exist, or when this node is not * readable, or when it is not a map. This behaviour is similar to * std::vector::at(), but the error consists in calling the error * callback instead of directly raising an exception. */ ConstNodeRef at(csubstr key) const { RYML_CHECK_BASIC_(m_tree != nullptr); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, (m_id >= 0 && m_id < m_tree->capacity()), m_tree, m_id); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, readable(), m_tree, m_id); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, m_tree->is_map(m_id), m_tree, m_id); id_type ch = m_tree->find_child(m_id, key); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, ch != NONE, m_tree, m_id); return {m_tree, ch}; } /** Get a child by position, with error checking; complexity is * O(pos). * * Behaves as operator[](id_type) const, but always raises an error * (even when RYML_USE_ASSERT is set to false) when the returned * node does not exist, or when this node is not readable, or when * it is not a container. This behaviour is similar to * std::vector::at(), but the error consists in calling the error * callback instead of directly raising an exception. */ ConstNodeRef at(id_type pos) const { RYML_CHECK_BASIC_(m_tree != nullptr); const id_type cap = m_tree->capacity(); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, (m_id >= 0 && m_id < cap), m_tree, m_id); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, (pos >= 0 && pos < cap), m_tree, m_id); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, readable(), m_tree, m_id); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, m_tree->is_container(m_id), m_tree, m_id); const id_type ch = m_tree->child(m_id, pos); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, ch != NONE, m_tree, m_id); return {m_tree, ch}; } /** @} */ public: /** @name modification of hierarchy */ /** @{ */ NodeRef insert_child(NodeRef after) { assert_readable_(); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, after.m_tree == m_tree, m_tree, m_id); NodeRef r(m_tree, m_tree->insert_child(m_id, after.m_id)); return r; } NodeRef prepend_child() { assert_readable_(); NodeRef r(m_tree, m_tree->insert_child(m_id, NONE)); return r; } NodeRef append_child() { assert_readable_(); NodeRef r(m_tree, m_tree->append_child(m_id)); return r; } NodeRef insert_sibling(ConstNodeRef const& after) { assert_readable_(); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, after.m_tree == m_tree, m_tree, m_id); NodeRef r(m_tree, m_tree->insert_sibling(m_id, after.m_id)); return r; } NodeRef prepend_sibling() { assert_readable_(); NodeRef r(m_tree, m_tree->prepend_sibling(m_id)); return r; } NodeRef append_sibling() { assert_readable_(); NodeRef r(m_tree, m_tree->append_sibling(m_id)); return r; } public: void remove_child(NodeRef & child) { assert_readable_(); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, has_child(child), m_tree, m_id); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, child.parent().id() == id(), m_tree, m_id); m_tree->remove(child.id()); child = NodeRef{}; } //! remove the nth child of this node void remove_child(id_type pos) { assert_readable_(); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, pos >= 0 && pos < num_children(), m_tree, m_id); id_type child = m_tree->child(m_id, pos); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, child != NONE, m_tree, m_id); m_tree->remove(child); } //! remove a child by name void remove_child(csubstr key) { assert_readable_(); id_type child = m_tree->find_child(m_id, key); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, child != NONE, m_tree, m_id); m_tree->remove(child); } public: /** move the node to a different @p parent (which may belong to a * different tree), placing it after @p after. When the * destination parent is in a new tree, then this node's tree * pointer is reset to the tree of the parent node. */ void move(NodeRef const& parent, ConstNodeRef const& after) { assert_readable_(); parent.assert_readable_(); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, parent.m_tree == after.m_tree || after.m_id == NONE, m_tree, m_id); if(parent.m_tree == m_tree) { m_tree->move(m_id, parent.m_id, after.m_id); } else { parent.m_tree->move(m_tree, m_id, parent.m_id, after.m_id); m_tree = parent.m_tree; } } /** duplicate the current node somewhere into a different @p parent * (possibly from a different tree), and place it after the node * @p after. To place into the first position of the parent, * simply pass an empty or default-constructed reference like * this: `n.move({})`. */ NodeRef duplicate(NodeRef const& parent, ConstNodeRef const& after) const { assert_readable_(); parent.assert_readable_(); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, parent.m_tree == after.m_tree || after.m_id == NONE, m_tree, m_id); id_type dup = parent.m_tree->duplicate(m_tree, m_id, parent.m_id, after.m_id); NodeRef r(parent.m_tree, dup); return r; } NodeRef duplicate_children(NodeRef const& parent, ConstNodeRef const& after) const { assert_readable_(); parent.assert_readable_(); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, parent.m_tree == after.m_tree || after.m_id == NONE, m_tree, m_id); id_type last_dup = parent.m_tree->duplicate_children(m_tree, m_id, parent.m_id, after.m_id); NodeRef r(parent.m_tree, last_dup); return r; } /** @} */ public: /** @name iteration */ /** @{ */ using iterator = detail::child_iterator; using const_iterator = detail::child_iterator; using children_view = detail::children_view; using const_children_view = detail::children_view; C4_ALWAYS_INLINE iterator begin() RYML_NOEXCEPT { assert_readable_(); return iterator(m_tree, m_tree->first_child(m_id)); } /**< get a mutable iterator to the first child. NOT AVAILABLE for ConstNodeRef. */ C4_ALWAYS_INLINE const_iterator begin() const RYML_NOEXCEPT { assert_readable_(); return const_iterator(m_tree, m_tree->first_child(m_id)); } /**< get an iterator to the first child */ C4_ALWAYS_INLINE const_iterator cbegin() const RYML_NOEXCEPT { assert_readable_(); return const_iterator(m_tree, m_tree->first_child(m_id)); } /**< get an iterator to the first child */ C4_ALWAYS_INLINE iterator end() RYML_NOEXCEPT { assert_readable_(); return iterator(m_tree, NONE); } /**< get an iterator to after the last child. NOT AVAILABLE for ConstNodeRef. */ C4_ALWAYS_INLINE const_iterator end() const RYML_NOEXCEPT { assert_readable_(); return const_iterator(m_tree, NONE); } /**< get an iterator to after the last child */ C4_ALWAYS_INLINE const_iterator cend() const RYML_NOEXCEPT { assert_readable_(); return const_iterator(m_tree, NONE); } /**< get an iterator to after the last child */ C4_ALWAYS_INLINE children_view children() RYML_NOEXCEPT { assert_readable_(); return detail::make_children_view(m_tree, m_id); } /**< get an iterable view over children */ C4_ALWAYS_INLINE const_children_view children() const RYML_NOEXCEPT { assert_readable_(); return detail::make_children_view(m_tree, m_id); } /**< get an iterable view over children */ C4_ALWAYS_INLINE const_children_view cchildren() const RYML_NOEXCEPT { assert_readable_(); return detail::make_children_view(m_tree, m_id); } /**< get an iterable view over children */ C4_ALWAYS_INLINE children_view siblings() RYML_NOEXCEPT { assert_readable_(); return detail::make_siblings_view(m_tree, m_id); } /** get an iterable view over all siblings (including the calling node) */ C4_ALWAYS_INLINE const_children_view siblings() const RYML_NOEXCEPT { assert_readable_(); return detail::make_siblings_view(m_tree, m_id); } /** get an iterable view over all siblings (including the calling node) */ C4_ALWAYS_INLINE const_children_view csiblings() const RYML_NOEXCEPT { assert_readable_(); return detail::make_siblings_view(m_tree, m_id); } /** get an iterable view over all siblings (including the calling node) */ /** @} */ public: /** @name legacy operators * * these methods will be removed in future releases. If you * disagree with a particular function being deprecated, let us * know by opening a new issue at * https://github.com/biojppm/rapidyaml/issues */ /** @{ */ RYML_LEGACY_OPERATOR(".use the appropriate .set_*() overload") void operator= (type_bits t) { create(); m_tree->_p(m_id)->m_type = t; } RYML_LEGACY_OPERATOR(".use the appropriate .set_*() overload") void operator|= (type_bits t) { create(); m_tree->_add_flags(m_id, t); } RYML_LEGACY_OPERATOR("use .set_val()") NodeRef& operator= (csubstr v) { set_val(v); return *this; } template RYML_LEGACY_OPERATOR("use .set_val()") NodeRef& operator= (const char (&v)[N]) { csubstr sv; sv.assign(v); set_val(sv); return *this; } RYML_LEGACY_OPERATOR("use .set_val()") NodeRef& operator= (std::nullptr_t) { set_val(csubstr{}); return *this; } template RYML_LEGACY_OPERATOR("use .set_key()") NodeRef& operator= (Key const& C4_RESTRICT v) { set_key(v.k); return *this; } template RYML_LEGACY_OPERATOR("use .save()") NodeRef& operator<< (T const& C4_RESTRICT v) { save(v); return *this; } RYML_LEGACY_OPERATOR("use .save()") NodeRef& operator<< (csubstr v) { save(v); return *this; } template RYML_LEGACY_OPERATOR("use .save_key()") NodeRef& operator<< (Key const& C4_RESTRICT v) { save_key(v.k); return *this; } /** @} */ public: // deprecated functions // these methods will be removed in future releases. If you // disagree with a particular function being deprecated, let us // know by opening a new issue at // https://github.com/biojppm/rapidyaml/issues /** @cond dev */ // LCOV_EXCL_START C4_SUPPRESS_WARNING_PUSH C4_SUPPRESS_WARNING_GCC_CLANG("-Wdeprecated") C4_SUPPRESS_WARNING_GCC_CLANG("-Wdeprecated-declarations") C4_SUPPRESS_WARNING_MSVC(4996) // deprecated RYML_DEPRECATED("use NodeRef()") NodeRef(std::nullptr_t) noexcept : m_tree(nullptr), m_id(NONE), m_seed() {} RYML_DEPRECATED("use one of readable(), is_seed() or !invalid()") inline bool valid() const { return m_tree != nullptr && m_id != NONE; } RYML_DEPRECATED("use !readable()") bool operator== (std::nullptr_t) const { return m_tree == nullptr || m_id == NONE || is_seed(); } RYML_DEPRECATED("use readable()") bool operator!= (std::nullptr_t) const { return !(m_tree == nullptr || m_id == NONE || is_seed()); } RYML_DEPRECATED("use `this->val() == s`") bool operator== (csubstr s) const { assert_readable_(); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, has_val(), m_tree, m_id); return m_tree->val(m_id) == s; } RYML_DEPRECATED("use `this->val() != s`") bool operator!= (csubstr s) const { assert_readable_(); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, has_val(), m_tree, m_id); return m_tree->val(m_id) != s; } RYML_DEPRECATED("use .set_*()") void operator= (NodeInit const& v) { create(); _apply(v); } RYML_DEPRECATED("use .set_*()") void operator= (NodeScalar const& v) { create(); _apply(v); } RYML_DEPRECATED("") void clear() { assert_readable_(); m_tree->remove_children(m_id); m_tree->_clear(m_id); } RYML_DEPRECATED("") void _apply(csubstr v) { m_tree->set_val(m_id, v); } RYML_DEPRECATED("") void _apply(NodeScalar const& v) { m_tree->_set_val(m_id, v); } RYML_DEPRECATED("") void _apply(NodeInit const& i) { m_tree->_set(m_id, i); } RYML_DEPRECATED("") NodeRef insert_child(NodeInit const& i, NodeRef after) { assert_readable_(); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, after.m_tree == m_tree, m_tree, m_id); NodeRef r(m_tree, m_tree->insert_child(m_id, after.m_id)); r._apply(i); return r; } RYML_DEPRECATED("") NodeRef prepend_child(NodeInit const& i) { assert_readable_(); NodeRef r(m_tree, m_tree->insert_child(m_id, NONE)); r._apply(i); return r; } RYML_DEPRECATED("") NodeRef append_child(NodeInit const& i) { assert_readable_(); NodeRef r(m_tree, m_tree->append_child(m_id)); r._apply(i); return r; } RYML_DEPRECATED("") NodeRef insert_sibling(NodeInit const& i, ConstNodeRef const& after) { assert_readable_(); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, after.m_tree == m_tree, m_tree, m_id); NodeRef r(m_tree, m_tree->insert_sibling(m_id, after.m_id)); r._apply(i); return r; } RYML_DEPRECATED("") NodeRef prepend_sibling(NodeInit const& i) { assert_readable_(); NodeRef r(m_tree, m_tree->prepend_sibling(m_id)); r._apply(i); return r; } RYML_DEPRECATED("") NodeRef append_sibling(NodeInit const& i) { assert_readable_(); NodeRef r(m_tree, m_tree->append_sibling(m_id)); r._apply(i); return r; } RYML_DEPRECATED("") void move(ConstNodeRef const& after) { assert_readable_(); m_tree->move(m_id, after.m_id); } RYML_DEPRECATED("") NodeRef duplicate(ConstNodeRef const& after) const { assert_readable_(); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, m_tree == after.m_tree || after.m_id == NONE, m_tree, m_id); id_type dup = m_tree->duplicate(m_id, m_tree->parent(m_id), after.m_id); NodeRef r(m_tree, dup); return r; } C4_SUPPRESS_WARNING_POP void _add_flags(NodeType f) { assert_readable_(); m_tree->_add_flags(m_id, f); } /** @endcond */ // LCOV_EXCL_STOP }; // NOLINTEND(cppcoreguidelines-c-copy-assignment-signature,misc-unconventional-assign-operator) /** @} */ //----------------------------------------------------------------------------- inline ConstNodeRef::ConstNodeRef(NodeRef const& that) noexcept : m_tree(that.m_tree) , m_id(!that.is_seed() ? that.id() : (id_type)NONE) { } inline ConstNodeRef::ConstNodeRef(NodeRef && that) noexcept // NOLINT : m_tree(that.m_tree) , m_id(!that.is_seed() ? that.id() : (id_type)NONE) { } inline ConstNodeRef& ConstNodeRef::operator= (NodeRef const& that) noexcept { m_tree = (that.m_tree); m_id = (!that.is_seed() ? that.id() : (id_type)NONE); return *this; } inline ConstNodeRef& ConstNodeRef::operator= (NodeRef && that) noexcept // NOLINT { m_tree = (that.m_tree); m_id = (!that.is_seed() ? that.id() : (id_type)NONE); return *this; } //----------------------------------------------------------------------------- /** @addtogroup doc_serialization_node_read * * freestanding read() and read_key() implementing ryml's built-in * deserialization of fundamental types. * * @{ */ template C4_NODISCARD C4_ALWAYS_INLINE ReadResult read(ConstNodeRef const& C4_RESTRICT n, T *v) { // defer to the tree implementation return n.m_tree->deserialize(n.m_id, v); } template C4_NODISCARD C4_ALWAYS_INLINE ReadResult read(ConstNodeRef const& C4_RESTRICT n, T const& wrapper) { // defer to the tree implementation return n.m_tree->deserialize(n.m_id, wrapper); } template C4_NODISCARD C4_ALWAYS_INLINE ReadResult read_key(ConstNodeRef const& C4_RESTRICT n, T *v) { // defer to the tree implementation return n.m_tree->deserialize_key(n.m_id, v); } template C4_NODISCARD C4_ALWAYS_INLINE ReadResult read_key(ConstNodeRef const& C4_RESTRICT n, T const& wrapper) { // defer to the tree implementation return n.m_tree->deserialize_key(n.m_id, wrapper); } /** @} */ //----------------------------------------------------------------------------- /** @addtogroup doc_serialization_node_write * * freestanding write() and write_key() implementing ryml's * built-in serialization of fundamental types. * * @{ */ template C4_ALWAYS_INLINE void write(NodeRef *n, T const& v) { n->tree()->set_serialized(n->id(), v); // defer to the tree implementation } template C4_ALWAYS_INLINE void write_key(NodeRef *n, T const& v) { n->tree()->set_key_serialized(n->id(), v); // defer to the tree implementation } template C4_ALWAYS_INLINE void write(NodeRef &n, T const& v) { // forward to the pointer call, to ensure the user's function is // called regardless if it is write(NodeRef*,T), write(NodeRef&,T) // or write(NodeRef,T) write(&n, v); } template C4_ALWAYS_INLINE void write_key(NodeRef &n, T const& v) { // forward to the pointer call, to ensure the user's function is // called regardless if it is write(NodeRef*,T), write(NodeRef&,T) // or write(NodeRef,T) write_key(&n, v); } /** @} */ } // namespace yml } // namespace c4 // NOLINTEND(modernize-avoid-c-style-cast) C4_SUPPRESS_WARNING_POP #endif /* C4_YML_NODE_HPP_ */ // (end src/c4/yml/node.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/writer_buf.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_WRITER_BUF_HPP_ #define C4_YML_WRITER_BUF_HPP_ #ifndef C4_YML_ERROR_HPP_ //#include "c4/yml/error.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/error.hpp must have been amalgamated before this point" #endif //#include // memcpy(), memset() // amalgamate: included above namespace c4 { namespace yml { C4_SUPPRESS_WARNING_MSVC_WITH_PUSH(4251) // substr needs to have dll-interface to be used by clients of WriterBuf /** A writer to a memory buffer, in the form of a @ref substr . No * overflow occurs; the buffer size is strictly respected. * * @ingroup doc_writers * @ingroup doc_emit_to_buffer */ struct RYML_EXPORT WriterBuf { substr m_buf; size_t m_pos; WriterBuf(substr sp) noexcept : m_buf(sp), m_pos(0) {} public: /** Return the buffer written so far, or optionally throw an error * if the buffer was too small. */ substr get_result(bool error_on_excess) const { if(m_pos <= m_buf.len) { return m_buf.first(m_pos); } else if(!error_on_excess) { substr sp; sp.str = nullptr; sp.len = m_pos; return sp; } else { RYML_ERR_BASIC_("not enough space in the given buffer"); } } public: template C4_ALWAYS_INLINE void append(const char (&a)[N]) noexcept { static_assert(N > 1, "empty string"); RYML_ASSERT_BASIC_( ! m_buf.overlaps(a)); if(m_pos + N-1 <= m_buf.len) memcpy(m_buf.str + m_pos, a, N-1); m_pos += N-1; } C4_ALWAYS_INLINE void append(csubstr s) noexcept { RYML_ASSERT_BASIC_( ! s.overlaps(m_buf)); if(s.len && m_pos + s.len <= m_buf.len) memcpy(m_buf.str + m_pos, s.str, s.len); m_pos += s.len; } C4_ALWAYS_INLINE void append(const char c) noexcept { if(m_pos + 1 <= m_buf.len) m_buf.str[m_pos] = c; ++m_pos; } C4_ALWAYS_INLINE void append(const char c, size_t num_times) noexcept { if(m_pos + num_times <= m_buf.len) memset(m_buf.str + m_pos, c, num_times); m_pos += num_times; } }; C4_SUPPRESS_WARNING_MSVC_POP } // namespace yml } // namespace c4 #endif /* C4_YML_WRITER_BUF_HPP_ */ // (end src/c4/yml/writer_buf.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/writer_file.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_WRITER_FILE_HPP_ #define C4_YML_WRITER_FILE_HPP_ /** @file writer_file.hpp */ #ifndef C4_YML_ERROR_HPP_ //#include "c4/yml/error.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/error.hpp must have been amalgamated before this point" #endif //#include // fwrite(), fputc() // amalgamate: included above namespace c4 { namespace yml { /** A writer that outputs to a C file handle, defaulting to * stdout. This writer is *much* faster than @ref WriterOStream and * should be preferred to it. * @ingroup doc_writers * @ingroup doc_emit_to_file */ struct RYML_EXPORT WriterFile { FILE * m_file; WriterFile(FILE *f = nullptr) noexcept : m_file(f ? f : stdout) {} template C4_ALWAYS_INLINE void append(const char (&a)[N]) noexcept // NOLINT(*-make-member-function-const) { static_assert(N > 1, "empty string"); (void)fwrite(a, sizeof(char), N - 1, m_file); } C4_ALWAYS_INLINE void append(csubstr s) noexcept // NOLINT(*-make-member-function-const) { if(s.len) { C4_SUPPRESS_WARNING_GCC_CLANG_WITH_PUSH("-Wsign-conversion") (void)fwrite(s.str, sizeof(csubstr::char_type), s.len, m_file); C4_SUPPRESS_WARNING_GCC_CLANG_POP } } C4_ALWAYS_INLINE void append(const char c) noexcept // NOLINT(*-make-member-function-const) { (void)fputc(c, m_file); } C4_ALWAYS_INLINE void append(const char c, size_t num_times) noexcept // NOLINT(*-make-member-function-const) { for(size_t i = 0; i < num_times; ++i) (void)fputc(c, m_file); } }; } // namespace yml } // namespace c4 #endif /* C4_YML_WRITER_FILE_HPP_ */ // (end src/c4/yml/writer_file.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/writer_ostream.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_WRITER_OSTREAM_HPP_ #define C4_YML_WRITER_OSTREAM_HPP_ /** @file writer_ostream.hpp */ #ifndef C4_YML_ERROR_HPP_ //#include "c4/yml/error.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/error.hpp must have been amalgamated before this point" #endif namespace c4 { namespace yml { /** A writer that outputs to an STL-like ostream. * * @ingroup doc_writers * @ingroup doc_emit_to_ostream */ template struct WriterOStream { OStream* m_stream; WriterOStream(OStream *s) noexcept : m_stream(s) {} template C4_ALWAYS_INLINE void append(const char (&a)[N]) noexcept { static_assert(N > 1, "empty string"); m_stream->write(a, N - 1); } C4_ALWAYS_INLINE void append(csubstr s) noexcept { if(s.len) { C4_SUPPRESS_WARNING_GCC_CLANG_WITH_PUSH("-Wsign-conversion") m_stream->write(s.str, s.len); C4_SUPPRESS_WARNING_GCC_CLANG_POP } } C4_ALWAYS_INLINE void append(const char c) noexcept { m_stream->put(c); } C4_ALWAYS_INLINE void append(const char c, size_t num_times) noexcept { for(size_t i = 0; i < num_times; ++i) m_stream->put(c); } }; } // namespace yml } // namespace c4 #endif /* C4_YML_WRITER_OSTREAM_HPP_ */ // (end src/c4/yml/writer_ostream.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/writer.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_WRITER_HPP_ #define C4_YML_WRITER_HPP_ /** @file writer.hpp Umbrella header with all writers */ #ifndef C4_YML_WRITER_BUF_HPP_ //#include // amalgamate: remove include #error "amalgamate: c4/yml/writer_buf.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_WRITER_FILE_HPP_ //#include // amalgamate: remove include #error "amalgamate: c4/yml/writer_file.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_WRITER_OSTREAM_HPP_ //#include // amalgamate: remove include #error "amalgamate: c4/yml/writer_ostream.hpp must have been amalgamated before this point" #endif #endif /* C4_YML_WRITER_HPP_ */ // (end src/c4/yml/writer.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/detail/dbgprint.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_DETAIL_DBGPRINT_HPP_ #define C4_YML_DETAIL_DBGPRINT_HPP_ //----------------------------------------------------------------------------- // debug prints #ifndef RYML_DBG # define _c4dbgt(fmt, ...) # define _c4dbgpf(fmt, ...) # define _c4dbgpf_(fmt, ...) # define _c4dbgp(msg) # define _c4dbgp_(msg) # define _c4dbgq(msg) # define _c4presc(...) # define _c4prscalar(msg, scalar, keep_newlines) #else # define _c4dbgt(fmt, ...) do { \ if(dbg_enabled_()) { \ this->_dbg("{}:{}: " fmt , __FILE__, __LINE__, __VA_ARGS__); \ } \ } while(0) # define _c4dbgpf(fmt, ...) dbg_printf_("{}:{}: " fmt "\n", __FILE__, __LINE__, __VA_ARGS__) # define _c4dbgpf_(fmt, ...) dbg_printf_("{}:{}: " fmt , __FILE__, __LINE__, __VA_ARGS__) # define _c4dbgp(msg) dbg_printf_("{}:{}: " msg "\n", __FILE__, __LINE__ ) # define _c4dbgp_(msg) dbg_printf_("{}:{}: " msg , __FILE__, __LINE__ ) # define _c4dbgq(msg) dbg_printf_(msg "\n") # define _c4presc(...) c4presc_(__VA_ARGS__) # define _c4prscalar(msg, scalar, keep_newlines) \ do { \ if(dbg_enabled_()) { \ _c4dbgpf_("{}: [{}]~~~", msg, scalar.len); \ c4presc_((scalar), (keep_newlines)); \ _c4dbgq("~~~"); \ } \ } while(0) //----------------------------------------------------------------------------- // implementation (only with RYML_DBG) //#include // amalgamate: included above #if defined(C4_MSVC) || defined(C4_MINGW) #include #elif (defined(__clang__) && defined(_MSC_VER)) || \ defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) //#include // amalgamate: included above #else #include #endif #ifndef C4_YML_ESCAPE_SCALAR_HPP_ //#include "c4/yml/escape_scalar.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/escape_scalar.hpp must have been amalgamated before this point" #endif #ifndef C4_DUMP_HPP_ //#include "c4/dump.hpp" // amalgamate: remove include #error "amalgamate: c4/dump.hpp must have been amalgamated before this point" #endif #ifndef C4_FORMAT_HPP_ //#include "c4/format.hpp" // amalgamate: remove include #error "amalgamate: c4/format.hpp must have been amalgamated before this point" #endif C4_SUPPRESS_WARNING_GCC_WITH_PUSH("-Wattributes") namespace c4 { namespace yml { inline bool& dbg_enabled_() { static bool enabled = true; return enabled; } inline C4_NO_INLINE void dbg_set_enabled_(bool yes) { dbg_enabled_() = yes; } inline C4_NO_INLINE void dbg_dumper_(csubstr s) { RYML_ASSERT_BASIC_(s.str || !s.len); if(s.len) fwrite(s.str, 1, s.len, stdout); } template C4_NO_INLINE void dbg_dump_(DumpFn &&dumpfn, csubstr fmt, Args&& ...args) { DumpResults results; // try writing everything: { // buffer for converting individual arguments. it is defined // in a child scope to free it in case the buffer is too small // for any of the arguments. char writebuf[RYML_LOGBUF_SIZE]; results = format_dump_resume(std::forward(dumpfn), writebuf, fmt, std::forward(args)...); } // if any of the arguments failed to fit the buffer, allocate a // larger buffer (with alloca(), up to a limit) and resume writing. // // results.bufsize is set to the size of the largest element // serialized. Eg int(1) will require 1 byte. if(C4_UNLIKELY(results.bufsize > RYML_LOGBUF_SIZE)) { const size_t bufsize = results.bufsize <= RYML_LOGBUF_SIZE_MAX ? results.bufsize : RYML_LOGBUF_SIZE_MAX; #ifdef C4_MSVC substr largerbuf = {static_cast(_alloca(bufsize)), bufsize}; #else substr largerbuf = {static_cast(alloca(bufsize)), bufsize}; #endif results = format_dump_resume(std::forward(dumpfn), results, largerbuf, fmt, std::forward(args)...); } } template C4_NO_INLINE void dbg_printf_(csubstr fmt, Args const& ...args) { if(dbg_enabled_()) dbg_dump_(&dbg_dumper_, fmt, args...); } inline C4_NO_INLINE void c4presc_(csubstr s, bool keep_newlines=false) { if(dbg_enabled_()) escape_scalar_fn(dbg_dumper_, s, keep_newlines); } inline C4_NO_INLINE void c4presc_(const char *s, size_t len, bool keep_newlines=false) { c4presc_(csubstr(s, len), keep_newlines); } struct maybe_null_str_ { csubstr s; maybe_null_str_(csubstr s_) noexcept : s(s_) {} }; // LCOV_EXCL_START inline C4_NO_INLINE size_t to_chars(substr buf, maybe_null_str_ const& v) { return c4::format(buf, v.s.str ? v.s : csubstr("(out of size)")); } // LCOV_EXCL_STOP template C4_NO_INLINE size_t dump(SinkPfn &&sinkfn, substr /*buf*/, maybe_null_str_ const& v) { std::forward(sinkfn)(v.s.str ? v.s : csubstr("(out of size)")); return 0; // no space needed in the buffer } /** print string as [{s.len}]~~~{s}~~~ */ struct prs_ { csubstr subject; size_t maxsize; bool escape; bool keep_newlines; ///< keep newlines when escaping prs_(csubstr s) noexcept : subject(s) , maxsize(s.len) , escape(false) , keep_newlines(true) { } explicit prs_(csubstr s, size_t maxsz, bool esc=false, bool newl=false) noexcept : subject(s) , maxsize(maxsz == npos ? s.len : maxsz) , escape(esc) , keep_newlines(newl) { } explicit prs_(csubstr s, bool esc, bool newl=true) noexcept : subject(s) , maxsize(s.len) , escape(esc) , keep_newlines(newl) { } }; // LCOV_EXCL_START inline C4_NO_INLINE size_t to_chars(substr buf, prs_ const& v) { csubstr s = v.subject; if(C4_LIKELY(s.str != nullptr)) { csubstr ellipsis = ""; if(v.maxsize < s.len) { s = s.first(v.maxsize); ellipsis = "..."; } return !v.escape ? c4::format(buf, "[{}]~~~{}{}~~~", v.subject.len, s, ellipsis) : c4::format(buf, "[{}]~~~{}{}~~~", v.subject.len, escaped_scalar(s, v.keep_newlines), ellipsis); } return c4::format(buf, "[{}](out of size)", v.subject.len); } // LCOV_EXCL_STOP template C4_NO_INLINE size_t dump(SinkPfn &&sinkfn, substr buf, prs_ const& v) { csubstr s = v.subject; size_t sz = to_chars(buf, s.len); if(sz <= buf.len) { if(C4_LIKELY(s.str != nullptr)) { csubstr ellipsis = ""; if(v.maxsize < s.len) { s = s.first(v.maxsize); ellipsis = "..."; } std::forward(sinkfn)("["); std::forward(sinkfn)(buf.first(sz)); std::forward(sinkfn)("]~~~"); if(!v.escape) { std::forward(sinkfn)(s); } else { dump(std::forward(sinkfn), buf, escaped_scalar(s, v.keep_newlines)); } std::forward(sinkfn)(ellipsis); std::forward(sinkfn)("~~~"); } else { std::forward(sinkfn)("["); std::forward(sinkfn)(buf.first(sz)); std::forward(sinkfn)("](out of size)"); } } return sz; // we require this space in the buffer } } // namespace yml } // namespace c4 C4_SUPPRESS_WARNING_GCC_POP #endif // RYML_DBG // helper to export cases to the YAML test suite #ifndef RYML_SAVE_TEST_YAML #define RYML_SAVE_TEST_YAML_(filename, src) #define RYML_SAVE_TEST_JSON_(filename, src) #define RYML_SAVE_TEST_EXPFAIL_() #else #define RYML_SAVE_TEST_YAML_(filename, src) c4::yml::ryml_save_test_yaml(filename, src) #define RYML_SAVE_TEST_JSON_(filename, src) c4::yml::ryml_save_test_json(filename, src) #define RYML_SAVE_TEST_EXPFAIL_() c4::yml::ryml_save_test_expfail() namespace c4 { namespace yml { void ryml_save_test_yaml(csubstr filename, csubstr src); void ryml_save_test_json(csubstr filename, csubstr src); void ryml_save_test_expfail(); } // namespace yml } // namespace c4 #endif // RYML_SAVE_TEST_YAML #endif /* C4_YML_DETAIL_DBGPRINT_HPP_ */ // (end src/c4/yml/detail/dbgprint.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/emit_options.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_EMIT_OPTIONS_HPP_ #define C4_YML_EMIT_OPTIONS_HPP_ #ifndef C4_YML_COMMON_HPP_ //#include // amalgamate: remove include #error "amalgamate: c4/yml/common.hpp must have been amalgamated before this point" #endif namespace c4 { namespace yml { /** A lightweight object containing options to be used when emitting. * @ingroup doc_emit */ struct RYML_EXPORT EmitOptions { public: /** @cond dev */ typedef enum : uint32_t { // NOLINT INDENT_FLOW_ML = 1u << 0u, FORCE_FLOW_SPC = 1u << 1u, EMIT_NONROOT_KEY = 1u << 2u, EMIT_NONROOT_DASH = 1u << 3u, EMIT_NONROOT_MARKUP = EMIT_NONROOT_KEY|EMIT_NONROOT_DASH, JSON_ERR_ON_STREAM = 1u << 4u, JSON_ERR_ON_TAG = 1u << 5u, JSON_ERR_ON_ANCHOR = 1u << 6u, JSON_ERR_MASK_ = JSON_ERR_ON_TAG|JSON_ERR_ON_ANCHOR, DEFAULT_FLAGS = EMIT_NONROOT_KEY|INDENT_FLOW_ML, } Flags_e; /** @endcond */ private: EmitOptions& set_flags_(bool enabled, Flags_e f) { if(enabled) m_flags |= f; else m_flags &= ~f; return *this; } public: /** @name YAML flow customization * * Control formatting of YAML flow containers. * * @{ */ /** Indent the contents of @ref FLOW_ML1 and @ref FLOW_MLN * containers. Enabled by default. */ C4_ALWAYS_INLINE bool indent_flow_ml() const noexcept { return (m_flags & INDENT_FLOW_ML) != 0; } EmitOptions& indent_flow_ml(bool enabled) noexcept { return set_flags_(enabled, INDENT_FLOW_ML); } /** Force everywhere a space after comma in flow mode, overriding * the @ref FLOW_SPC status of individual containers. This only * applies to @ref FLOW_ML1 or @ref FLOW_MLN containers. Disabled * by default. */ EmitOptions& force_flow_spc(bool enabled) noexcept { return set_flags_(enabled, FORCE_FLOW_SPC); } C4_ALWAYS_INLINE bool force_flow_spc() const noexcept { return (m_flags & FORCE_FLOW_SPC) != 0; } /** Set max columns for the emitted YAML in @ref FLOW_MLN * mode. This will make the emitted YAML wrap around when the line * reaches max cols, but only in containers with @ref FLOW_MLN * mode. Defaults to 80 columns. */ EmitOptions& max_cols(id_type cols) noexcept { m_max_cols = cols; return *this; } C4_ALWAYS_INLINE id_type max_cols() const noexcept { return m_max_cols; } static constexpr const id_type max_cols_default = 80; /** @} */ public: /** @name Nested nodes * * Control emission of nested (non-root) nodes. * * @{ */ /** When emit starts on a nested (non-root) node, emit the node's * key as well. This will maek the resulting YAML a map with the * node as its single element. Enabled by default. */ EmitOptions& emit_nonroot_key(bool enabled) noexcept { return set_flags_(enabled, EMIT_NONROOT_KEY); } C4_ALWAYS_INLINE bool emit_nonroot_key() const noexcept { return (m_flags & EMIT_NONROOT_KEY) != 0; } /** When emit starts on a nested (non-root) node, emit a leading * dash. This will make the resulting YAML a seq with the node as * its single element. Disabled by default. */ EmitOptions& emit_nonroot_dash(bool enabled) noexcept { return set_flags_(enabled, EMIT_NONROOT_DASH); } C4_ALWAYS_INLINE bool emit_nonroot_dash() const noexcept { return (m_flags & EMIT_NONROOT_DASH) != 0; } /** @} */ public: /** @name JSON behavior * * Controls the behavior when emitting JSON. * @{ */ /** Whether to trigger an error (or emit as seq) when finding a * stream in json mode. Disabled by default. */ EmitOptions& json_err_on_stream(bool enabled) noexcept { return set_flags_(enabled, JSON_ERR_ON_STREAM); } C4_ALWAYS_INLINE bool json_err_on_stream() const noexcept { return (m_flags & JSON_ERR_ON_STREAM) != 0; } /** Whether to trigger an error (or ignore the tag) when finding a * tag in json mode. Disabled by default. */ EmitOptions& json_err_on_tag(bool enabled) noexcept { return set_flags_(enabled, JSON_ERR_ON_TAG); } C4_ALWAYS_INLINE bool json_err_on_tag() const noexcept { return (m_flags & JSON_ERR_ON_TAG) != 0; } /** Whether to trigger an error (or ignore the anchor) when * finding an anchor in json mode. Disabled by default. */ EmitOptions& json_err_on_anchor(bool enabled) noexcept { return set_flags_(enabled, JSON_ERR_ON_ANCHOR); } C4_ALWAYS_INLINE bool json_err_on_anchor() const noexcept { return (m_flags & JSON_ERR_ON_ANCHOR) != 0; } /** @} */ public: /** @name maximum depth for the emitted tree * * This prevents stack overflows by making the emitter fail when * the tree exceeds the maximum depth. * * @{ */ C4_ALWAYS_INLINE id_type max_depth() const noexcept { return m_max_depth; } EmitOptions& max_depth(id_type d) noexcept { m_max_depth = d; return *this; } static constexpr const id_type max_depth_default = 64; /** @} */ public: bool operator== (const EmitOptions& that) const noexcept { return m_max_depth == that.m_max_depth && m_max_cols == that.m_max_cols && m_flags == that.m_flags; } private: /** @cond dev */ id_type m_max_depth{max_depth_default}; id_type m_max_cols{max_cols_default}; uint32_t m_flags{DEFAULT_FLAGS}; /** @endcond */ public: // deprecated methods /** @cond dev */ RYML_DEPRECATED("use .json_err_on_{tag,anchor}()") C4_ALWAYS_INLINE Flags_e json_error_flags() const noexcept { return static_cast(m_flags & JSON_ERR_MASK_); } RYML_DEPRECATED("use .json_err_on_{tag,anchor}()") EmitOptions& json_error_flags(Flags_e d) noexcept { m_flags = (d & JSON_ERR_MASK_); return *this; } /** @endcond */ }; } // namespace yml } // namespace c4 #endif /* C4_YML_EMIT_HPP_ */ // (end src/c4/yml/emit_options.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/scalar_style.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_SCALAR_STYLE_HPP_ #define C4_YML_SCALAR_STYLE_HPP_ /** @file scalar_style.hpp */ #ifndef C4_YML_NODE_TYPE_HPP_ //#include "c4/yml/node_type.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/node_type.hpp must have been amalgamated before this point" #endif namespace c4 { namespace yml { /** @addtogroup doc_scalar_style * * @{ */ /** query whether a scalar can be encoded using single quotes. * It may not be possible, notably when there is leading * whitespace after a newline. */ RYML_EXPORT bool scalar_style_query_squo(csubstr scalar) noexcept; /** query whether a scalar can be encoded using plain style while in * flow mode. Plain scalars [have more constraints in flow mode than * in block * mode](https://www.yaml.info/learn/quote.html#noplain). @ref * scalar_style_query_plain_block() is the block mode analogous function.*/ RYML_EXPORT bool scalar_style_query_plain_flow(csubstr scalar) noexcept; /** query whether a scalar can be encoded using plain style while in * block mode. Plain scalars [have more constraints in flow mode than * in block * mode](https://www.yaml.info/learn/quote.html#noplain). @ref * scalar_style_query_plain_flow() is the flow mode analogous function.*/ RYML_EXPORT bool scalar_style_query_plain_block(csubstr scalar) noexcept; /** choose a YAML scalar style based on the scalar's contents, while * in flow mode. Plain scalars [have more constraints in flow mode * than in block * mode](https://www.yaml.info/learn/quote.html#noplain). @ref * scalar_style_choose_block() is the block mode analogous * function. */ inline NodeType scalar_style_choose_flow(csubstr scalar) noexcept { if(scalar.len) { if(scalar_style_query_plain_flow(scalar)) return SCALAR_PLAIN; else if(scalar_style_query_squo(scalar)) return SCALAR_SQUO; return SCALAR_DQUO; } return scalar.str ? SCALAR_SQUO : SCALAR_PLAIN; } /** choose a YAML scalar style based on the scalar's contents, while * in block mode. Plain scalars [have more constraints in flow mode * than in block * mode](https://www.yaml.info/learn/quote.html#noplain). @ref * scalar_style_choose_block() is the flow mode analogous function. */ RYML_EXPORT NodeType scalar_style_choose_block(csubstr scalar) noexcept; /** choose a json scalar style based on the scalar's contents */ RYML_EXPORT NodeType scalar_style_choose_json(csubstr scalar) noexcept; //----------------------------------------------------------------------------- /** @cond dev */ // LCOV_EXCL_START RYML_DEPRECATED("use scalar_style_query_plain_{flow,block}()") inline bool scalar_style_query_plain(csubstr s, bool flow=true) noexcept { return flow ? scalar_style_query_plain_flow(s) : scalar_style_query_plain_block(s); } RYML_DEPRECATED("use scalar_style_choose_{flow,block}()") inline NodeType scalar_style_choose(csubstr s, bool flow=true) noexcept { return flow ? scalar_style_choose_flow(s) : scalar_style_choose_block(s); } RYML_DEPRECATED("use scalar_style_choose_json()") inline NodeType scalar_style_json_choose(csubstr scalar) noexcept { return scalar_style_choose_json(scalar); } /** @endcond */ // LCOV_EXCL_STOP /** @} */ } // namespace yml } // namespace c4 #endif /* C4_YML_SCALAR_STYLE_HPP_ */ // (end src/c4/yml/scalar_style.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/emitter.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_EMITTER_HPP_ #define C4_YML_EMITTER_HPP_ /** @file emitter.hpp */ #ifndef C4_YML_EMIT_OPTIONS_HPP_ //#include "c4/yml/emit_options.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/emit_options.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_NODE_TYPE_HPP_ //#include "c4/yml/node_type.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/node_type.hpp must have been amalgamated before this point" #endif namespace c4 { namespace yml { /** @cond dev */ // fwd declarations class Tree; /** Specifies the type of content to emit */ typedef enum { // NOLINT EMIT_YAML = 0, ///< emit YAML EMIT_JSON = 1, ///< emit JSON } EmitType_e; /** @endcond */ /** A YAML/JSON emitter, templated on a writer class such as @ref WriterBuf, * @ref WriterFile, or @ref WriterOStream * @ingroup doc_emit */ template class Emitter : public Writer { public: /** Construct the emitter and its internal Writer state. * * @param opts @ref EmitOptions * @param args arguments to be forwarded to the constructor of the writer. */ template Emitter(EmitOptions const& opts, WriterArgs &&...args) noexcept : Writer(std::forward(args)...) , m_tree() , m_opts(opts) , m_col() , m_depth() , m_ilevel() , m_pws() , m_flow_pws() {} public: /** emit! * * @param type specify what to emit (YAML or JSON) * @param tree the tree to emit * @param id the id of the node to emit */ void emit_as(EmitType_e type, Tree const* tree, id_type id=NONE); public: /** get the emit options for this object */ EmitOptions const& options() const noexcept { return m_opts; } private: // pending whitespace /// pending whitespace typedef enum : uint32_t { PWS_NONE_ = 0u, PWS_SPACE_ = 1u, PWS_NEWL_ = 2u } Pws_e; // NOLINT /// set pending whitespace, ignoring pending C4_ALWAYS_INLINE void pend_none_() noexcept // LCOV_EXCL_LINE { m_pws = PWS_NONE_; } /// set pending whitespace, ignoring pending C4_ALWAYS_INLINE void pend_newl_() noexcept // LCOV_EXCL_LINE { m_pws = PWS_NEWL_; } /// set pending whitespace, ignoring pending C4_ALWAYS_INLINE void pend_space_() noexcept // LCOV_EXCL_LINE { m_pws = PWS_SPACE_; } /// write pending whitespace, and then set the next pending whitespace C4_ALWAYS_INLINE void write_pws_and_pend_(Pws_e next=PWS_NONE_) noexcept // LCOV_EXCL_LINE { if(m_pws == PWS_SPACE_) { write_(' '); } else if(m_pws == PWS_NEWL_) { newl_(); indent_(m_ilevel); } m_pws = next; } /// specs for obtaining pending whitespace in flow mode struct flow_pws { size_t max_cols = 0; // leave this member first to avoid padding Pws_e pend_after_comma = PWS_NONE_; bool active = false; C4_ALWAYS_INLINE Pws_e next_pws(size_t col) const noexcept // LCOV_EXCL_LINE { return (active && col >= max_cols) ? PWS_NEWL_ : pend_after_comma; } void start(NodeType ty, size_t max_cols_) noexcept; void stop() noexcept { active = false; } }; C4_NODISCARD bool maybe_start_flow_pws_ml_(id_type node) noexcept; C4_NODISCARD flow_pws setup_flow_pws_sl_(id_type node) noexcept; private: void emit_yaml_(id_type id); void visit_stream_(id_type id); void visit_doc_(id_type id); void visit_doc_val_(id_type id); void visit_blck_container_(id_type id); void visit_flow_container_(id_type id); void visit_flow_sl_(id_type id); void visit_flow_sl_seq_(id_type id); void visit_flow_sl_map_(id_type id); void visit_flow_ml_(id_type id); void visit_flow_ml_seq_(id_type id); void visit_flow_ml_map_(id_type id); void visit_blck_(id_type id); void visit_blck_seq_(id_type id); void visit_blck_map_(id_type id); void top_open_entry_(id_type id); void top_close_entry_(id_type id); void blck_seq_open_entry_(id_type id); void blck_map_open_entry_(id_type id); void blck_close_entry_(id_type id); void blck_write_scalar_(csubstr str, type_bits type); void flow_seq_open_entry_(id_type id); void flow_map_open_entry_(id_type id); void flow_close_entry_sl_(id_type id, id_type last_sibling, Pws_e pend_after); void flow_close_entry_ml_(id_type id, id_type last_sibling, Pws_e pend_after); void flow_write_scalar_(csubstr str, type_bits type); private: void json_emit_(id_type id); void write_scalar_literal_(csubstr s, id_type level); void write_scalar_folded_(csubstr s, id_type level); void write_scalar_squo_(csubstr s, id_type level); void write_scalar_dquo_(csubstr s, id_type level); void write_scalar_plain_(csubstr s, id_type level); size_t write_escaped_newlines_(csubstr s, size_t i); size_t write_indented_block_(csubstr s, size_t i, id_type level); private: void json_visit_ml_(id_type id, NodeType ty, id_type depth); void json_visit_sl_(id_type id, NodeType ty, id_type depth); bool json_maybe_write_naninf_(csubstr s); void json_writek_(id_type id, NodeType ty); void json_writev_(id_type id, NodeType ty); void json_write_scalar_dquo_(csubstr s); void json_write_number_(csubstr s); private: void write_tag_(csubstr tag) { if(!tag.begins_with('!')) write_('!'); write_(tag); } void write_ref_(csubstr ref) { if(ref != "<<") { if(!ref.begins_with('*')) write_('*'); write_(ref); } } private: template C4_ALWAYS_INLINE void write_(const char (&a)[N]) // LCOV_EXCL_LINE { this->Writer::append(std::forward(a)); m_col += N-1; } C4_ALWAYS_INLINE void write_(csubstr s) // LCOV_EXCL_LINE { this->Writer::append(s); m_col += s.len; } C4_ALWAYS_INLINE void write_(char c) // LCOV_EXCL_LINE { this->Writer::append(c); ++m_col; } C4_ALWAYS_INLINE void indent_(id_type level) // LCOV_EXCL_LINE { C4_SUPPRESS_WARNING_GCC_WITH_PUSH("-Wuseless-cast") size_t num = static_cast(2u * level); this->Writer::append(' ', num); m_col += num; C4_SUPPRESS_WARNING_GCC_POP } /// write a newline and reset the column C4_ALWAYS_INLINE void newl_() // LCOV_EXCL_LINE { this->Writer::append('\n'); m_col = 0; } private: Tree const* C4_RESTRICT m_tree; EmitOptions m_opts; size_t m_col; id_type m_depth; id_type m_ilevel; Pws_e m_pws; flow_pws m_flow_pws; public: // deprecated methods /** @cond dev */ // LCOV_EXCL_START RYML_DEPRECATED("create a new emitter") void options(EmitOptions) noexcept { ; } RYML_DEPRECATED("use .options()") void max_depth(id_type max_depth) noexcept { m_opts.max_depth(max_depth); } RYML_DEPRECATED("use .options()") id_type max_depth() const noexcept { return m_opts.max_depth(); } /** @endcond */ // LCOV_EXCL_STOP }; } // namespace yml } // namespace c4 #endif /* C4_YML_EMITTTER_HPP_ */ // (end src/c4/yml/emitter.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/emitter.def.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_EMITTER_DEF_HPP_ #define C4_YML_EMITTER_DEF_HPP_ /** @file emitter.def.hpp */ #ifndef C4_YML_EMITTER_HPP_ //#include "c4/yml/emitter.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/emitter.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_TREE_HPP_ //#include "c4/yml/tree.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/tree.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_SCALAR_STYLE_HPP_ //#include "c4/yml/scalar_style.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/scalar_style.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_DETAIL_DBGPRINT_HPP_ //#include "c4/yml/detail/dbgprint.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/detail/dbgprint.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_ERROR_HPP_ //#include "c4/yml/error.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/error.hpp must have been amalgamated before this point" #endif C4_SUPPRESS_WARNING_GCC_CLANG_WITH_PUSH("-Wold-style-cast") C4_SUPPRESS_WARNING_GCC("-Wuseless-cast") // NOLINTBEGIN(modernize-avoid-c-style-cast) namespace c4 { namespace yml { namespace detail { enum : type_bits { // NOLINT styles_block_key_ = KEY_LITERAL|KEY_FOLDED, styles_block_val_ = VAL_LITERAL|VAL_FOLDED, styles_block_ = (styles_block_key_ | styles_block_val_), styles_flow_key_ = KEY_STYLE & ~styles_block_key_, styles_flow_val_ = VAL_STYLE & ~styles_block_val_, styles_flow_ = styles_flow_key_ | styles_flow_val_, styles_squo_ = KEY_SQUO|VAL_SQUO, styles_dquo_ = KEY_DQUO|VAL_DQUO, styles_plain_ = KEY_PLAIN|VAL_PLAIN, styles_literal_ = KEY_LITERAL|VAL_LITERAL, styles_folded_ = KEY_FOLDED|VAL_FOLDED, }; } // namespace detail template void Emitter::emit_as(EmitType_e type, Tree const* tree, id_type id) { RYML_ASSERT_BASIC_CB_(tree->callbacks(), !tree || !tree->empty() || id == NONE); if(!tree || tree->empty()) return; if(id == NONE) id = tree->root_id(); RYML_CHECK_VISIT_CB_(tree->callbacks(), id < tree->capacity(), tree, id); m_tree = tree; m_col = 0; m_depth = 0; m_ilevel = 0; m_pws = PWS_NONE_; m_flow_pws = {}; if(type == EMIT_YAML) emit_yaml_(id); else if(type == EMIT_JSON) json_emit_(id); else RYML_ERR_BASIC_CB_(m_tree->callbacks(), "unknown emit type"); // LCOV_EXCL_LINE m_tree = nullptr; } /** @cond dev */ //----------------------------------------------------------------------------- // The startup logic is made complicated from it having to accept // initial non-root nodes, and having to deal with tricky tokens like // doc separators, anchors, tags, optional keys or dashes, and // comments. // // This function kickstarts the tree descent by handling all the // initial and final logic at the top-level scope, thus avoiding // top-level kickstart branches in the recursive descending code // (which should be oblivious of such logic). This makes the recursive // descending code a lot simpler. template void Emitter::emit_yaml_(id_type id) { const NodeType ty = m_tree->type(id); // emit leading tokens, such as keys or comments const bool has_parent = !m_tree->is_root(id); const bool emit_key = has_parent && ty.has_key() && m_opts.emit_nonroot_key(); const bool emit_dash = has_parent && !ty.has_key() && !ty.is_doc() && m_opts.emit_nonroot_dash(); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, !(emit_key && emit_dash), m_tree, id); // emit opening tokens (such as tags, anchors or comments) if(emit_key) { blck_map_open_entry_(id); ++m_ilevel; } else if(emit_dash) { blck_seq_open_entry_(id); ++m_ilevel; } else { top_open_entry_(id); } // emit the payload if(ty.is_stream()) { RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, m_ilevel == 0, m_tree, id); visit_stream_(id); } else if(ty.is_doc()) { RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, m_ilevel == 0, m_tree, id); visit_doc_(id); } else if(ty.is_container()) { visit_blck_container_(id); } else if(ty.has_val()) { visit_doc_val_(id); } // emit closing tokens (such as comments) if(emit_key) { --m_ilevel; blck_close_entry_(id); } else if(emit_dash) { --m_ilevel; blck_close_entry_(id); } else { top_close_entry_(id); } if(ty.is_flow_mlx()) { newl_(); } else if(m_tree->is_root(id) || emit_dash || emit_key || !ty.is_val() || !ty.is_val_plain()) { write_pws_and_pend_(PWS_NONE_); } } //----------------------------------------------------------------------------- template void Emitter::visit_stream_(id_type id) { auto write_tag_directives = [this](const id_type next_node){ const id_type doc = m_tree->ancestor_doc(next_node); const TagDirectiveRange tagds = m_tree->m_tag_directives.lookup_range(doc); if(tagds.e != tagds.b) { const id_type parent = m_tree->parent(next_node); if(next_node != m_tree->first_child(parent)) { write_pws_and_pend_(PWS_NEWL_); write_("..."); } } for(TagDirective const& td : tagds) { write_pws_and_pend_(PWS_NONE_); write_("%TAG "); write_(td.handle); write_(' '); write_(td.prefix); pend_newl_(); } }; const id_type first_child = m_tree->first_child(id); if(first_child != NONE) write_tag_directives(first_child); ++m_depth; for(id_type child = first_child; child != NONE; child = m_tree->next_sibling(child)) { NodeType ty = m_tree->type(child); m_ilevel = 0; write_pws_and_pend_(PWS_NONE_); top_open_entry_(child); visit_doc_(child); top_close_entry_(child); if(ty.is_val()) { if(ty.m_bits & VALNIL) pend_newl_(); } else if(ty.is_container()) { if(ty.is_flow()) pend_newl_(); } if(m_tree->next_sibling(child) != NONE) { write_tag_directives(m_tree->next_sibling(child)); } } --m_depth; } //----------------------------------------------------------------------------- template void Emitter::visit_blck_container_(id_type id) { NodeType ty = m_tree->type(id); if(!(ty.m_bits & CONTAINER_STYLE)) ty.m_bits |= (m_tree->empty(id) ? FLOW_SL : BLOCK); write_pws_and_pend_(PWS_NONE_); if(ty.is_flow_sl()) visit_flow_sl_(id); else if(ty.is_flow_mlx()) visit_flow_ml_(id); else visit_blck_(id); } template void Emitter::visit_flow_container_(id_type id) { NodeType ty = m_tree->type(id); if(!(ty.m_bits & CONTAINER_STYLE)) ty.m_bits |= FLOW_SL; write_pws_and_pend_(PWS_NONE_); if(ty.is_flow_mlx()) visit_flow_ml_(id); else // if(ty.is_flow_sl()) visit_flow_sl_(id); } //----------------------------------------------------------------------------- template void Emitter::visit_doc_val_(id_type id) { // some plain scalars such as '...' and '---' must not // appear at 0-indentation NodeType ty = m_tree->type(id); const csubstr val = m_tree->val(id); type_bits val_style = ty.m_bits & VAL_STYLE; const bool is_ambiguous = ((ty.m_bits & VAL_PLAIN) || !val_style) && (val.begins_with("...") || val.begins_with("---")); if(is_ambiguous) { ++m_ilevel; if(m_pws != PWS_NONE_) pend_newl_(); else indent_(m_ilevel); } write_pws_and_pend_(PWS_NONE_); if(m_tree->is_val_ref(id)) { write_ref_(val); } else { if(!val_style) val_style = scalar_style_choose_block(val); blck_write_scalar_(val, val_style); } if(is_ambiguous) { --m_ilevel; } } //----------------------------------------------------------------------------- template void Emitter::visit_doc_(id_type id) { const NodeType ty = m_tree->type(id); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, ty.is_doc(), m_tree, id); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, !ty.has_key(), m_tree, id); if(ty.is_container()) // this is more frequent { visit_blck_container_(id); } else if(ty.is_val()) { visit_doc_val_(id); } } //----------------------------------------------------------------------------- // to be called only at top level template void Emitter::top_open_entry_(id_type node) { NodeType ty = m_tree->type(node); if(ty.is_doc() && !m_tree->is_root(node)) { write_("---"); pend_space_(); } if(ty.has_val_anchor()) { write_pws_and_pend_(PWS_SPACE_); write_('&'); write_(m_tree->val_anchor(node)); } if(ty.has_val_tag()) { write_pws_and_pend_(PWS_SPACE_); write_tag_(m_tree->val_tag(node)); } if(m_pws == PWS_SPACE_) { if(ty.has_val()) { if(ty.is_val_plain() && !m_tree->val(node).len) pend_none_(); } else { RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), ty.is_container(), m_tree, node); if(!ty.is_flow()) pend_newl_(); } } } //----------------------------------------------------------------------------- template void Emitter::top_close_entry_(id_type node) { NodeType ty = m_tree->type(node); if(ty.is_val() && !(ty.m_bits & VALNIL)) { pend_newl_(); } } //----------------------------------------------------------------------------- template void Emitter::flow_seq_open_entry_(id_type node) { NodeType ty = m_tree->type(node); write_pws_and_pend_(PWS_NONE_); if(ty.m_bits & VALANCH) { write_pws_and_pend_(PWS_SPACE_); write_('&'); write_(m_tree->val_anchor(node)); } if(ty.m_bits & VALTAG) { write_pws_and_pend_(PWS_SPACE_); write_tag_(m_tree->val_tag(node)); } } //----------------------------------------------------------------------------- template void Emitter::flow_map_open_entry_(id_type node) { NodeType ty = m_tree->type(node); write_pws_and_pend_(PWS_NONE_); RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), ty.has_key(), m_tree, node); if(ty.m_bits & KEYANCH) { write_pws_and_pend_(PWS_SPACE_); write_("&"); write_(m_tree->key_anchor(node)); } if(ty.m_bits & KEYTAG) { write_pws_and_pend_(PWS_SPACE_); write_tag_(m_tree->key_tag(node)); } if(ty.m_bits & KEYREF) { write_pws_and_pend_(PWS_SPACE_); write_ref_(m_tree->key(node)); } else { write_pws_and_pend_(PWS_NONE_); csubstr key = m_tree->key(node); if(!(ty.m_bits & detail::styles_flow_key_)) ty.m_bits |= scalar_style_choose_flow(key) & detail::styles_flow_key_; flow_write_scalar_(key, ty.m_bits & detail::styles_flow_key_); } write_pws_and_pend_(PWS_SPACE_); write_(':'); if(ty.m_bits & VALANCH) { write_pws_and_pend_(PWS_SPACE_); write_('&'); write_(m_tree->val_anchor(node)); } if(ty.m_bits & VALTAG) { write_pws_and_pend_(PWS_SPACE_); write_tag_(m_tree->val_tag(node)); } } //----------------------------------------------------------------------------- template C4_NODISCARD bool Emitter::maybe_start_flow_pws_ml_(id_type node) noexcept { RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), m_tree->type(node) & (FLOW_ML1|FLOW_MLN), m_tree, node); if(m_flow_pws.active) return false; NodeType ty = m_tree->type(node); if(m_opts.force_flow_spc()) ty |= FLOW_SPC; m_flow_pws.start(ty, m_opts.max_cols()); return true; } template C4_NODISCARD typename Emitter::flow_pws Emitter::setup_flow_pws_sl_(id_type node) noexcept { flow_pws ret = {}; if(m_flow_pws.active) { ret = m_flow_pws; } else { NodeType ty = m_tree->type(node); if(m_opts.force_flow_spc()) ty |= FLOW_SPC; ret.start(ty, 0); } return ret; } template void Emitter::flow_pws::start(NodeType ty, size_t max_cols_) noexcept { max_cols = 0; pend_after_comma = (ty.m_bits & FLOW_SPC) ? PWS_SPACE_ : PWS_NONE_; if(ty.m_bits & FLOW_MLN) { max_cols_ = max_cols_ >= 2 ? max_cols_ : 2; // subtract 1 for the comma, and maybe the space from pend_after_comma max_cols = max_cols_ - 1 - pend_after_comma; // line above only works if: static_assert((size_t)PWS_NONE_ == 0 && (size_t)PWS_SPACE_ == 1, "invalid assumptions"); active = true; } else if(ty.m_bits & FLOW_ML1) { pend_after_comma = PWS_NEWL_; } } template void Emitter::flow_close_entry_sl_(id_type node, id_type last_sibling, Pws_e pend_after) { if(node != last_sibling) { write_pws_and_pend_(pend_after); write_(','); } } template void Emitter::flow_close_entry_ml_(id_type node, id_type last_sibling, Pws_e pend_after) { if(node != last_sibling) { write_pws_and_pend_(pend_after); write_(','); } else { pend_newl_(); } } //----------------------------------------------------------------------------- template void Emitter::blck_seq_open_entry_(id_type node) { NodeType ty = m_tree->type(node); write_pws_and_pend_(PWS_NONE_); write_pws_and_pend_(PWS_SPACE_); // pend the space after the following dash write_('-'); bool has_tag_or_anchor = false; if(ty.m_bits & VALANCH) { has_tag_or_anchor = true; write_pws_and_pend_(PWS_SPACE_); write_('&'); write_(m_tree->val_anchor(node)); } if(ty.m_bits & VALTAG) { has_tag_or_anchor = true; write_pws_and_pend_(PWS_SPACE_); write_tag_(m_tree->val_tag(node)); } if(has_tag_or_anchor && ty.is_container()) { if(!(ty.m_bits & CONTAINER_STYLE)) ty |= BLOCK; if((ty.m_bits & BLOCK) && m_tree->has_children(node)) pend_newl_(); } } //----------------------------------------------------------------------------- template void Emitter::blck_map_open_entry_(id_type node) { NodeType ty = m_tree->type(node); RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), ty.has_key(), m_tree, node); csubstr key = m_tree->key(node); if(!(ty.m_bits & (KEY_STYLE|KEYREF))) ty.m_bits |= (scalar_style_choose_block(key).m_bits & KEY_STYLE); write_pws_and_pend_(PWS_NONE_); if(ty.m_bits & KEYANCH) { write_pws_and_pend_(PWS_SPACE_); write_('&'); write_(m_tree->key_anchor(node)); } if(ty.m_bits & KEYTAG) { write_pws_and_pend_(PWS_SPACE_); write_tag_(m_tree->key_tag(node)); } if(ty.m_bits & KEYREF) { write_pws_and_pend_(PWS_SPACE_); write_ref_(key); } else { write_pws_and_pend_(PWS_NONE_); const type_bits use_qmrk = ty.m_bits & detail::styles_block_key_; if(!use_qmrk) { blck_write_scalar_(key, ty.m_bits & KEY_STYLE); } else { write_("? "); blck_write_scalar_(key, ty.m_bits & KEY_STYLE); pend_newl_(); } } write_pws_and_pend_(PWS_SPACE_); // pend the space after the colon write_(':'); if(ty.m_bits & VALANCH) { write_pws_and_pend_(PWS_SPACE_); write_('&'); write_(m_tree->val_anchor(node)); } if(ty.m_bits & VALTAG) { write_pws_and_pend_(PWS_SPACE_); write_tag_(m_tree->val_tag(node)); } if(ty.is_container() && m_tree->has_children(node)) { if(!(ty.m_bits & CONTAINER_STYLE)) ty |= BLOCK; if(ty.is_block()) pend_newl_(); } } //----------------------------------------------------------------------------- template void Emitter::blck_close_entry_(id_type node) { (void)node; pend_newl_(); } //----------------------------------------------------------------------------- template void Emitter::visit_blck_seq_(id_type node) { RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), m_tree->is_seq(node), m_tree, node); bool empty = true; for(id_type child = m_tree->first_child(node); child != NONE; child = m_tree->next_sibling(child)) { empty = false; NodeType ty = m_tree->type(child); RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), ty.is_val() || ty.is_container() || ty == NOTYPE, m_tree, node); blck_seq_open_entry_(child); if(ty.is_val()) { write_pws_and_pend_(PWS_NONE_); csubstr val = m_tree->val(child); if(!ty.is_val_ref()) { if(!(ty.m_bits & VAL_STYLE)) ty.m_bits |= (scalar_style_choose_block(val).m_bits & VAL_STYLE); blck_write_scalar_(val, ty.m_bits & VAL_STYLE); } else { write_ref_(val); } } else if(ty.is_container()) { ++m_depth; ++m_ilevel; visit_blck_container_(child); --m_depth; --m_ilevel; } blck_close_entry_(child); } if(empty) { write_pws_and_pend_(PWS_NONE_); write_("[]"); } } //----------------------------------------------------------------------------- template void Emitter::visit_blck_map_(id_type node) { RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), m_tree->is_map(node), m_tree, node); bool empty = true; for(id_type child = m_tree->first_child(node); child != NONE; child = m_tree->next_sibling(child)) { empty = false; NodeType ty = m_tree->type(child); RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), ty.is_keyval() || ty.is_container() || ty == NOTYPE, m_tree, node); blck_map_open_entry_(child); // also writes the key if(ty.is_keyval()) { write_pws_and_pend_(PWS_NONE_); csubstr val = m_tree->val(child); if(!ty.is_val_ref()) { if(!(ty.m_bits & VAL_STYLE)) ty |= (scalar_style_choose_block(val).m_bits & VAL_STYLE); blck_write_scalar_(val, ty.m_bits & VAL_STYLE); } else { write_ref_(val); } } else if(ty.is_container()) { ++m_depth; ++m_ilevel; visit_blck_container_(child); --m_depth; --m_ilevel; } blck_close_entry_(child); } if(empty) { write_pws_and_pend_(PWS_NONE_); write_("{}"); } } //----------------------------------------------------------------------------- template void Emitter::visit_flow_sl_seq_(id_type node) { RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), m_tree->is_seq(node), m_tree, node); const flow_pws pws = setup_flow_pws_sl_(node); write_('['); for(id_type child = m_tree->first_child(node), last = m_tree->last_child(node); child != NONE; child = m_tree->next_sibling(child)) { NodeType ty = m_tree->type(child); RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), (ty & (VAL|SEQ|MAP)) || ty == NOTYPE, m_tree, node); flow_seq_open_entry_(child); if(ty.m_bits & VAL) { write_pws_and_pend_(PWS_NONE_); csubstr val = m_tree->val(child); if(!ty.is_val_ref()) { if(!(ty.m_bits & detail::styles_flow_val_)) ty.m_bits |= (scalar_style_choose_flow(val).m_bits & detail::styles_flow_val_); flow_write_scalar_(val, ty.m_bits & detail::styles_flow_val_); } else { write_ref_(val); } } else if(ty.m_bits & (SEQ|MAP)) { ++m_depth; visit_flow_container_(child); --m_depth; } flow_close_entry_sl_(child, last, pws.next_pws(m_col)); } write_(']'); } //----------------------------------------------------------------------------- template void Emitter::visit_flow_ml_seq_(id_type node) { RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), m_tree->is_seq(node), m_tree, node); write_('['); pend_newl_(); if(m_opts.indent_flow_ml()) ++m_ilevel; const bool stop_at_end = maybe_start_flow_pws_ml_(node); for(id_type child = m_tree->first_child(node), last = m_tree->last_child(node); child != NONE; child = m_tree->next_sibling(child)) { NodeType ty = m_tree->type(child); RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), ty.is_val() || ty.is_container() || ty == NOTYPE, m_tree, node); flow_seq_open_entry_(child); if(ty.is_val()) { write_pws_and_pend_(PWS_NONE_); csubstr val = m_tree->val(child); if(!ty.is_val_ref()) { if(!(ty.m_bits & detail::styles_flow_val_)) ty.m_bits |= (scalar_style_choose_flow(val).m_bits & detail::styles_flow_val_); flow_write_scalar_(val, ty.m_bits & detail::styles_flow_val_); } else { write_ref_(val); } } else if(ty.is_container()) { ++m_depth; visit_flow_container_(child); --m_depth; } flow_close_entry_ml_(child, last, m_flow_pws.next_pws(m_col)); } if(stop_at_end) m_flow_pws.stop(); if(m_opts.indent_flow_ml()) --m_ilevel; write_pws_and_pend_(PWS_NONE_); write_(']'); } //----------------------------------------------------------------------------- template void Emitter::visit_flow_sl_map_(id_type node) { RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), m_tree->is_map(node), m_tree, node); flow_pws pws = setup_flow_pws_sl_(node); write_('{'); for(id_type child = m_tree->first_child(node), last = m_tree->last_child(node); child != NONE; child = m_tree->next_sibling(child)) { NodeType ty = m_tree->type(child); RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), ty.has_key() && (ty.has_val() || ty.is_container() || ty == NOTYPE), m_tree, node); flow_map_open_entry_(child); if(ty.has_val()) { write_pws_and_pend_(PWS_NONE_); csubstr val = m_tree->val(child); if(!ty.is_val_ref()) { if(!(ty.m_bits & detail::styles_flow_val_)) ty.m_bits |= (scalar_style_choose_flow(val).m_bits & detail::styles_flow_val_); flow_write_scalar_(val, ty.m_bits & detail::styles_flow_val_); } else { write_ref_(val); } } else if(ty.is_container()) { ++m_depth; visit_flow_container_(child); --m_depth; } flow_close_entry_sl_(child, last, pws.next_pws(m_col)); } write_pws_and_pend_(PWS_NONE_); write_('}'); } //----------------------------------------------------------------------------- template void Emitter::visit_flow_ml_map_(id_type node) { RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), m_tree->is_map(node), m_tree, node); write_('{'); pend_newl_(); if(m_opts.indent_flow_ml()) ++m_ilevel; const bool stop_at_end = maybe_start_flow_pws_ml_(node); for(id_type child = m_tree->first_child(node), last = m_tree->last_child(node); child != NONE; child = m_tree->next_sibling(child)) { NodeType ty = m_tree->type(child); RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), ty.has_key() && (ty.has_val() || ty.is_container() || ty == NOTYPE), m_tree, node); flow_map_open_entry_(child); if(ty.has_val()) { write_pws_and_pend_(PWS_NONE_); csubstr val = m_tree->val(child); if(!ty.is_val_ref()) { if(!(ty.m_bits & detail::styles_flow_val_)) ty.m_bits |= (scalar_style_choose_flow(val).m_bits & detail::styles_flow_val_); flow_write_scalar_(val, ty.m_bits & detail::styles_flow_val_); } else { write_ref_(val); } } else if(ty.is_container()) { ++m_depth; visit_flow_container_(child); --m_depth; } flow_close_entry_ml_(child, last, m_flow_pws.next_pws(m_col)); } if(stop_at_end) m_flow_pws.stop(); if(m_opts.indent_flow_ml()) --m_ilevel; write_pws_and_pend_(PWS_NONE_); write_('}'); } //----------------------------------------------------------------------------- template void Emitter::visit_blck_(id_type node) { const NodeType ty = m_tree->type(node); RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), !ty.is_stream(), m_tree, node); RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), ty.is_container() || ty.is_doc(), m_tree, node); RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), m_tree->is_root(node) || (m_tree->parent_is_map(node) || m_tree->parent_is_seq(node)), m_tree, node); if C4_UNLIKELY(m_depth > m_opts.max_depth()) RYML_ERR_VISIT_CB_(m_tree->callbacks(), m_tree, node, "max depth exceeded"); if(ty.is_seq()) { visit_blck_seq_(node); } else { RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), ty.is_map(), m_tree, node); visit_blck_map_(node); } } //----------------------------------------------------------------------------- template void Emitter::visit_flow_sl_(id_type node) { const NodeType ty = m_tree->type(node); RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), !ty.is_stream(), m_tree, node); RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), ty.is_container() || ty.is_doc(), m_tree, node); RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), m_tree->is_root(node) || (m_tree->parent_is_map(node) || m_tree->parent_is_seq(node)), m_tree, node); if C4_UNLIKELY(m_depth > m_opts.max_depth()) RYML_ERR_VISIT_CB_(m_tree->callbacks(), m_tree, node, "max depth exceeded"); if(ty.m_bits & SEQ) { visit_flow_sl_seq_(node); } else { RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), ty.is_map(), m_tree, node); visit_flow_sl_map_(node); } } //----------------------------------------------------------------------------- template void Emitter::visit_flow_ml_(id_type node) { const NodeType ty = m_tree->type(node); RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), !ty.is_stream(), m_tree, node); RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), ty.is_container() || ty.is_doc(), m_tree, node); RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), m_tree->is_root(node) || (m_tree->parent_is_map(node) || m_tree->parent_is_seq(node)), m_tree, node); if C4_UNLIKELY(m_depth > m_opts.max_depth()) RYML_ERR_VISIT_CB_(m_tree->callbacks(), m_tree, node, "max depth exceeded"); if(ty.m_bits & SEQ) { visit_flow_ml_seq_(node); } else { RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), ty.is_map(), m_tree, node); visit_flow_ml_map_(node); } } //----------------------------------------------------------------------------- template void Emitter::flow_write_scalar_(csubstr str, type_bits ty) { RYML_ASSERT_BASIC_CB_(m_tree->callbacks(), !(ty & detail::styles_block_)); if((ty & detail::styles_plain_) || !(ty & SCALAR_STYLE)) { write_scalar_plain_(str, m_ilevel); } else if(ty & detail::styles_squo_) { write_scalar_squo_(str, m_ilevel); } else // if(ty & detail::styles_dquo_) { write_scalar_dquo_(str, m_ilevel); } } template void Emitter::blck_write_scalar_(csubstr str, type_bits ty) { if((ty & detail::styles_plain_) || !(ty & SCALAR_STYLE)) { write_scalar_plain_(str, m_ilevel); } else if(ty & detail::styles_squo_) { write_scalar_squo_(str, m_ilevel); } else if(ty & detail::styles_dquo_) { write_scalar_dquo_(str, m_ilevel); } else if(ty & detail::styles_literal_) { write_scalar_literal_(str, m_ilevel); } else // if(ty & detail::styles_folded_) { write_scalar_folded_(str, m_ilevel); } } template size_t Emitter::write_escaped_newlines_(csubstr s, size_t i) { RYML_ASSERT_BASIC_CB_(m_tree->callbacks(), s.len > i); RYML_ASSERT_BASIC_CB_(m_tree->callbacks(), s.str[i] == '\n'); //_c4dbgpf("nl@i={} rem=[{}]~~~{}~~~", i, s.sub(i).len, s.sub(i)); // add an extra newline for each sequence of consecutive // newline/whitespace newl_(); do { newl_(); // write the newline again ++i; // increase the outer loop counter! } while(i < s.len && s.str[i] == '\n'); RYML_ASSERT_BASIC_CB_(m_tree->callbacks(), i > 0); --i; RYML_ASSERT_BASIC_CB_(m_tree->callbacks(), s.str[i] == '\n'); return i; } inline bool _is_indented_block(csubstr s, size_t prev, size_t i) noexcept { if(prev == 0 && s.begins_with_any(" \t")) return true; const size_t pos = s.first_not_of('\n', i); return (pos != npos) && (s.str[pos] == ' ' || s.str[pos] == '\t'); } template size_t Emitter::write_indented_block_(csubstr s, size_t i, id_type ilevel) { //_c4dbgpf("indblock@i={} rem=[{}]~~~\n{}~~~", i, s.sub(i).len, s.sub(i)); RYML_ASSERT_BASIC_CB_(m_tree->callbacks(), i > 0); RYML_ASSERT_BASIC_CB_(m_tree->callbacks(), s.str[i-1] == '\n'); RYML_ASSERT_BASIC_CB_(m_tree->callbacks(), i < s.len); RYML_ASSERT_BASIC_CB_(m_tree->callbacks(), s.str[i] == ' ' || s.str[i] == '\t' || s.str[i] == '\n'); again: size_t pos = s.find("\n ", i); if(pos == npos) pos = s.find("\n\t", i); if(pos != npos) { ++pos; //_c4dbgpf("indblock line@i={} rem=[{}]~~~\n{}~~~", i, s.range(i, pos).len, s.range(i, pos)); indent_(ilevel + 1); write_(s.range(i, pos)); i = pos; goto again; // NOLINT } // consume the newlines after the indented block // to prevent them from being escaped pos = s.find('\n', i); if(pos != npos) { const size_t pos2 = s.first_not_of('\n', pos); pos = (pos2 != npos) ? pos2 : pos; //_c4dbgpf("indblock line@i={} rem=[{}]~~~\n{}~~~", i, s.range(i, pos).len, s.range(i, pos)); indent_(ilevel + 1); write_(s.range(i, pos)); i = pos; } return i; } template void Emitter::write_scalar_literal_(csubstr s, id_type ilevel) { RYML_ASSERT_BASIC_CB_(m_tree->callbacks(), s.find("\r") == csubstr::npos); csubstr trimmed = s.trimr('\n'); const size_t numnewlines_at_end = s.len - trimmed.len; const bool is_newline_only = (trimmed.len == 0 && (s.len > 0)); const bool explicit_indentation = s.triml("\n\r").begins_with_any(" \t"); // write_('|'); if(explicit_indentation) write_('2'); // if(numnewlines_at_end > 1 || is_newline_only) write_('+'); else if(numnewlines_at_end == 0) write_('-'); // if(trimmed.len) { newl_(); size_t pos = 0; // tracks the last character that was already written for(size_t i = 0; i < trimmed.len; ++i) { if(trimmed[i] != '\n') continue; // write everything up to this point csubstr since_pos = trimmed.range(pos, i+1); // include the newline indent_(ilevel + 1); write_(since_pos); pos = i+1; // already written } if(pos < trimmed.len) { indent_(ilevel + 1); write_(trimmed.sub(pos)); } } for(size_t i = !is_newline_only; i < numnewlines_at_end; ++i) newl_(); } template void Emitter::write_scalar_folded_(csubstr s, id_type ilevel) { RYML_ASSERT_BASIC_CB_(m_tree->callbacks(), s.find("\r") == csubstr::npos); csubstr trimmed = s.trimr('\n'); const size_t numnewlines_at_end = s.len - trimmed.len; const bool is_newline_only = (trimmed.len == 0 && (s.len > 0)); const bool explicit_indentation = s.triml("\n\r").begins_with_any(" \t"); // write_('>'); if(explicit_indentation) write_('2'); // if(numnewlines_at_end == 0) write_('-'); else if(numnewlines_at_end > 1 || is_newline_only) write_('+'); // if(trimmed.len) { newl_(); size_t pos = 0; // tracks the last character that was already written for(size_t i = 0; i < trimmed.len; ++i) { if(trimmed[i] != '\n') continue; // escape newline sequences if( ! _is_indented_block(s, pos, i)) { if(pos < i) { indent_(ilevel + 1); write_(s.range(pos, i)); i = write_escaped_newlines_(s, i); pos = i + 1; } else { if(i+1 < s.len) { if(s.str[i+1] == '\n') { ++i; i = write_escaped_newlines_(s, i); pos = i+1; } else { newl_(); pos = i+1; } } } } else // do not escape newlines in indented blocks { ++i; indent_(ilevel + 1); write_(s.range(pos, i)); if(pos > 0 || !s.begins_with_any(" \t")) i = write_indented_block_(s, i, ilevel); pos = i; } } if(pos < trimmed.len) { indent_(ilevel + 1); write_(trimmed.sub(pos)); } } for(size_t i = !is_newline_only; i < numnewlines_at_end; ++i) newl_(); } template void Emitter::write_scalar_squo_(csubstr s, id_type ilevel) { size_t pos = 0; // tracks the last character that was already written write_('\''); for(size_t i = 0; i < s.len; ++i) { if(s[i] == '\n') { write_(s.range(pos, i)); // write everything up to (excluding) this char //_c4dbgpf("newline at {}. writing ~~~{}~~~", i, s.range(pos, i)); i = write_escaped_newlines_(s, i); //_c4dbgpf("newline --> {}", i); if(i < s.len) indent_(ilevel + 1); pos = i+1; } else if(s[i] == '\'') { csubstr sub = s.range(pos, i+1); //_c4dbgpf("squote at {}. writing ~~~{}~~~", i, sub); write_(sub); // write everything up to (including) this squote write_('\''); // write the squote again pos = i+1; } } // write remaining characters at the end of the string if(pos < s.len) write_(s.sub(pos)); write_('\''); } template void Emitter::write_scalar_dquo_(csubstr s, id_type ilevel) { size_t pos = 0; // tracks the last character that was already written write_('"'); for(size_t i = 0; i < s.len; ++i) { const char curr = s.str[i]; switch(curr) // NOLINT { case '"': case '\\': { csubstr sub = s.range(pos, i); write_(sub); // write everything up to (excluding) this char write_('\\'); // write the escape write_(curr); // write the char pos = i+1; break; } #ifndef prefer_writing_newlines_as_double_newlines case '\n': { csubstr sub = s.range(pos, i); write_(sub); // write everything up to (excluding) this char write_("\\n"); // write the escape pos = i+1; (void)ilevel; break; } #else case '\n': { // write everything up to (excluding) this newline //_c4dbgpf("nl@i={} rem=[{}]~~~{}~~~", i, s.sub(i).len, s.sub(i)); _write(s.range(pos, i)); i = _write_escaped_newlines(s, i); ++i; pos = i; // as for the next line... if(i < s.len) { _indent(ilevel + 1); // indent the next line // escape leading whitespace, and flush it size_t first = s.first_not_of(" \t", i); //_c4dbgpf("@i={} first={} rem=[{}]~~~{}~~~", i, first, s.sub(i).len, s.sub(i)); if(first > i) { if(first == npos) first = s.len; _write('\\'); _write(s.range(i, first)); _write('\\'); i = first-1; pos = first; } } break; } // escape trailing whitespace before a newline case ' ': case '\t': { const size_t next = s.first_not_of(" \t\r", i); if(next != npos && s.str[next] == '\n') { csubstr sub = s.range(pos, i); _write(sub); // write everything up to (excluding) this char _write('\\'); // escape the whitespace pos = i; } break; } #endif case '\r': { csubstr sub = s.range(pos, i); write_(sub); // write everything up to (excluding) this char write_("\\r"); // write the escaped char pos = i+1; break; } case '\b': { csubstr sub = s.range(pos, i); write_(sub); // write everything up to (excluding) this char write_("\\b"); // write the escaped char pos = i+1; break; } } } // write remaining characters at the end of the string if(pos < s.len) write_(s.sub(pos)); write_('"'); } template void Emitter::write_scalar_plain_(csubstr s, id_type ilevel) { if C4_UNLIKELY(ilevel == 0 && (s.begins_with("...") || s.begins_with("---"))) { indent_(ilevel + 1); // indent the next line ++ilevel; } size_t pos = 0; // tracks the last character that was already written for(size_t i = 0; i < s.len; ++i) { const char curr = s.str[i]; if(curr == '\n') { csubstr sub = s.range(pos, i); write_(sub); // write everything up to (including) this newline i = write_escaped_newlines_(s, i); pos = i+1; if(pos < s.len) indent_(ilevel + 1); // indent the next line } } // write remaining characters at the end of the string if(pos < s.len) write_(s.sub(pos)); } //----------------------------------------------------------------------------- namespace detail { inline type_bits json_type_(type_bits ty) { enum : type_bits { // NOLINT ml_bits = (BLOCK|(STREAM & ~SEQ)), // remove SEQ from STREAM to test sl_bits = (CONTAINER_STYLE & ~FLOW_SPC), }; if(ty & ml_bits) { ty &= ~BLOCK; ty |= FLOW_ML1; } else if((ty & (SEQ|MAP)) && !(ty & sl_bits)) { ty |= FLOW_SL; } return ty; } } // namespace detail template void Emitter::json_emit_(id_type id) { NodeType ty = m_tree->type(id); // JSON does not have streams if C4_UNLIKELY(ty.is_stream() && m_opts.json_err_on_stream()) RYML_ERR_VISIT_CB_(m_tree->callbacks(), m_tree, id, "found stream node"); static_assert(STREAM & SEQ, "STREAM must be a SEQ"); ty = detail::json_type_(ty); if(ty.is_flow_mlx()) { json_visit_ml_(id, ty, 0); newl_(); } else { json_visit_sl_(id, ty, 0); } } template void Emitter::json_visit_sl_(id_type id, NodeType ty, id_type depth) { if C4_UNLIKELY(depth > m_opts.max_depth()) RYML_ERR_VISIT_CB_(m_tree->callbacks(), m_tree, id, "max depth exceeded"); if(ty.is_val()) { json_writev_(id, ty); } else if(ty.is_keyval()) { json_writek_(id, ty); write_(": "); json_writev_(id, ty); } else if(ty.is_container()) { ty = detail::json_type_(ty); if(ty.has_key()) { json_writek_(id, ty); write_(": "); } if(ty.is_seq()) write_('['); else if(ty.is_map()) write_('{'); for(id_type child = m_tree->first_child(id); child != NONE; child = m_tree->next_sibling(child)) { if(child != m_tree->first_child(id)) { if((ty & FLOW_SPC) || m_opts.force_flow_spc()) write_(", "); else write_(','); } json_visit_sl_(child, m_tree->type(child), depth+1); } if(ty.is_seq()) write_(']'); else if(ty.is_map()) write_('}'); } // container } template void Emitter::json_visit_ml_(id_type id, NodeType ty, id_type depth) { if C4_UNLIKELY(depth > m_opts.max_depth()) RYML_ERR_VISIT_CB_(m_tree->callbacks(), m_tree, id, "max depth exceeded"); if(ty.is_val()) { json_writev_(id, ty); } else if(ty.is_keyval()) { json_writek_(id, ty); write_(": "); json_writev_(id, ty); } else if(ty.is_container()) { ty = detail::json_type_(ty); if(ty.has_key()) { json_writek_(id, ty); write_(": "); } if(ty.is_seq()) write_('['); else if(ty.is_map()) write_('{'); if(m_tree->has_children(id)) { ++depth; if(m_opts.indent_flow_ml()) ++m_ilevel; newl_(); indent_(m_ilevel); for(id_type first = m_tree->first_child(id), child = first; child != NONE; child = m_tree->next_sibling(child)) { if(child != first) { write_(','); const size_t maxcols = m_opts.max_cols(); if((ty.m_bits & FLOW_MLN) && (m_col+1 < maxcols)) { if((ty.m_bits & FLOW_SPC) || m_opts.force_flow_spc()) write_(' '); } else if((ty.m_bits & FLOW_ML1) || (m_col+1 >= maxcols)) { newl_(); indent_(m_ilevel); } } NodeType chty = m_tree->type(child); if(chty.is_flow_sl()) json_visit_sl_(child, chty, depth); else json_visit_ml_(child, chty, depth); } if(m_opts.indent_flow_ml()) --m_ilevel; --depth; newl_(); indent_(m_ilevel); } if(ty.is_seq()) write_(']'); else if(ty.is_map()) write_('}'); } } template bool Emitter::json_maybe_write_naninf_(csubstr s) { switch(s.len) { case 3: case 4: case 5: // inf, nan, .nan, -.inf case 8: case 9: // infinity, -infinity break; default: return false; } const char first = s.str[0]; csubstr rest = s.sub(1); if(s.len == 4 && first == '.') { if(scalar_is_inf3(rest.str)) goto write_inf_positive; // NOLINT else if(scalar_is_nan3(rest.str)) goto write_nan; // NOLINT } else if(first == '-' || first == '+') // begins with sign: must be inf { // match [-+].inf if((rest.len == 4 && rest.str[0] == '.' && scalar_is_inf3(rest.str + 1)) // match [-+]inf || (rest.len == 3 && scalar_is_inf3(rest.str)) // match [-+]infinity || (rest.len == 8 && (0 == memcmp(rest.str, "infinity", 8)))) { if(first == '-') goto write_inf_negative; // NOLINT else goto write_inf_positive; // NOLINT } } else if(s.len == 8 && (0 == memcmp(s.str, "infinity", 8))) { goto write_inf_positive; // NOLINT } else if(s.len == 3) { if(scalar_is_inf3(s.str)) goto write_inf_positive; // NOLINT else if(scalar_is_nan3(s.str)) goto write_nan; // NOLINT } return false; write_inf_positive: write_("\".inf\""); return true; write_inf_negative: write_("\"-.inf\""); return true; write_nan: write_("\".nan\""); return true; } template void Emitter::json_writek_(id_type id, NodeType ty) { if C4_UNLIKELY(ty.has_key_tag() && m_opts.json_err_on_tag()) RYML_ERR_VISIT_CB_(m_tree->callbacks(), m_tree, id, "JSON does not have tags"); if C4_UNLIKELY(ty.has_key_anchor() && m_opts.json_err_on_anchor()) RYML_ERR_VISIT_CB_(m_tree->callbacks(), m_tree, id, "JSON does not have anchors"); csubstr key = m_tree->key(id); if(key.len) { if(json_maybe_write_naninf_(key)) ; else json_write_scalar_dquo_(key); } else { write_("\"\""); } } template void Emitter::json_writev_(id_type id, NodeType ty) { if C4_UNLIKELY(ty.has_val_tag() && m_opts.json_err_on_tag()) RYML_ERR_VISIT_CB_(m_tree->callbacks(), m_tree, id, "JSON does not have tags"); if C4_UNLIKELY(ty.has_val_anchor() && m_opts.json_err_on_anchor()) RYML_ERR_VISIT_CB_(m_tree->callbacks(), m_tree, id, "JSON does not have anchors"); csubstr val = m_tree->val(id); if(val.len) { // use double quoted style if the style is marked quoted bool dquoted = ((ty.m_bits & VALQUO) || (scalar_style_choose_json(val).m_bits & SCALAR_DQUO)); // choose the style if(dquoted) json_write_scalar_dquo_(val); else if(json_maybe_write_naninf_(val)) ; else if(val.is_number()) json_write_number_(val); else write_(val); } else { if(val.str || (ty.m_bits & (VALQUO|VALTAG))) write_("\"\""); else write_("null"); } } template void Emitter::json_write_scalar_dquo_(csubstr s) { size_t pos = 0; write_('"'); for(size_t i = 0; i < s.len; ++i) { switch(s.str[i]) { case '"': write_(s.range(pos, i)); write_("\\\""); pos = i + 1; break; case '\n': write_(s.range(pos, i)); write_("\\n"); pos = i + 1; break; case '\t': write_(s.range(pos, i)); write_("\\t"); pos = i + 1; break; case '\\': write_(s.range(pos, i)); write_("\\\\"); pos = i + 1; break; case '\r': write_(s.range(pos, i)); write_("\\r"); pos = i + 1; break; case '\b': write_(s.range(pos, i)); write_("\\b"); pos = i + 1; break; case '\f': write_(s.range(pos, i)); write_("\\f"); pos = i + 1; break; } } if(pos < s.len) { csubstr sub = s.sub(pos); write_(sub); } write_('"'); } template void Emitter::json_write_number_(csubstr s) { if(s.is_integer()) { write_(s); } else { if(s.begins_with('-') && s.len > 1) { csubstr rest = s.sub(1); if(rest.begins_with('.')) { write_("-0"); write_(rest); } else if(rest.ends_with('.')) { write_(s); write_('0'); } else { write_(s); } } else if(s.begins_with('.')) { write_('0'); write_(s); } else if(s.ends_with('.')) { write_(s); write_('0'); } else { write_(s); } } } /** @endcond */ } // namespace yml } // namespace c4 // NOLINTEND(modernize-avoid-c-style-cast) C4_SUPPRESS_WARNING_GCC_CLANG_POP #endif /* C4_YML_EMITTTER_DEF_HPP_ */ // (end src/c4/yml/emitter.def.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/emit_buf.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_EMIT_BUF_HPP_ #define C4_YML_EMIT_BUF_HPP_ /** @file emit_buf.hpp Utilities to emit YAML and JSON to buffers or containers. */ #ifndef C4_YML_COMMON_HPP_ //#include "c4/yml/common.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/common.hpp must have been amalgamated before this point" #endif namespace c4 { namespace yml { /** @cond dev */ // fwd declarations template class Emitter; struct WriterBuf; class Tree; class ConstNodeRef; struct EmitOptions; /** @endcond */ /** @ingroup doc_emit_to_buffer */ using EmitterBuf = Emitter; // emit from root ------------------------- /** @addtogroup doc_emit_to_buffer_from_root * * @{ */ /** (1) emit YAML to the given buffer. Return a substr trimmed to the emitted YAML. * @param t the tree; will be emitted from the root node. * @param opts emit options. * @param buf the output buffer. * @param error_on_excess Raise an error if the space in the buffer is insufficient. * @return a substr trimmed to the result in the output buffer. If the * buffer is insufficient (when error_on_excess is false), the string * pointer of the result will be set to null, and the length will * report the required buffer size. For example usage, see @ref * emitrs_yaml() . */ RYML_EXPORT substr emit_yaml(Tree const& t, EmitOptions const& opts, substr buf, bool error_on_excess=true); /** (2) like (1), but use default emit options */ RYML_EXPORT substr emit_yaml(Tree const& t, substr buf, bool error_on_excess=true); /** (1) emit JSON to the given buffer. Return a substr trimmed to the emitted JSON. * @param t the tree; will be emitted from the root node. * @param opts emit options. * @param buf the output buffer. * @param error_on_excess Raise an error if the space in the buffer is insufficient. * @return a substr trimmed to the result in the output buffer. If the buffer is * insufficient (when error_on_excess is false), the string pointer of the * result will be set to null, and the length will report the required buffer size. */ RYML_EXPORT substr emit_json(Tree const& t, EmitOptions const& opts, substr buf, bool error_on_excess=true); /** (2) like (1), but use default emit options */ RYML_EXPORT substr emit_json(Tree const& t, substr buf, bool error_on_excess=true); /** @} */ // emit from tree and node id ----------------------- /** @addtogroup doc_emit_to_buffer_from_node_id * * @{ */ /** (1) emit YAML to the given buffer. Return a substr trimmed to the emitted YAML. * @param t the tree to emit. * @param id the node where to start emitting. * @param opts emit options. * @param buf the output buffer. * @param error_on_excess Raise an error if the space in the buffer is insufficient. * @return a substr trimmed to the result in the output buffer. If the buffer is * insufficient (when error_on_excess is false), the string pointer of the * result will be set to null, and the length will report the required buffer size. */ RYML_EXPORT substr emit_yaml(Tree const& t, id_type id, EmitOptions const& opts, substr buf, bool error_on_excess=true); /** (2) like (1), but use default emit options */ RYML_EXPORT substr emit_yaml(Tree const& t, id_type id, substr buf, bool error_on_excess=true); /** (1) emit JSON to the given buffer. Return a substr trimmed to the emitted JSON. * @param t the tree to emit. * @param id the node where to start emitting. * @param opts emit options. * @param buf the output buffer. * @param error_on_excess Raise an error if the space in the buffer is insufficient. * @return a substr trimmed to the result in the output buffer. If the buffer is * insufficient (when error_on_excess is false), the string pointer of the * result will be set to null, and the length will report the required buffer size. */ RYML_EXPORT substr emit_json(Tree const& t, id_type id, EmitOptions const& opts, substr buf, bool error_on_excess=true); /** (2) like (1), but use default emit options */ RYML_EXPORT substr emit_json(Tree const& t, id_type id, substr buf, bool error_on_excess=true); /** @} */ // emit from ConstNodeRef ------------------------ /** @addtogroup doc_emit_to_buffer_from_noderef * * @{ */ /** (1) emit YAML to the given buffer. Return a substr trimmed to the emitted YAML. * @param r the starting node. * @param buf the output buffer. * @param opts emit options. * @param error_on_excess Raise an error if the space in the buffer is insufficient. * @return a substr trimmed to the result in the output buffer. If the buffer is * insufficient (when error_on_excess is false), the string pointer of the * result will be set to null, and the length will report the required buffer size. */ RYML_EXPORT substr emit_yaml(ConstNodeRef const& r, EmitOptions const& opts, substr buf, bool error_on_excess=true); /** (2) like (1), but use default emit options */ RYML_EXPORT substr emit_yaml(ConstNodeRef const& r, substr buf, bool error_on_excess=true); /** (1) emit JSON to the given buffer. Return a substr trimmed to the emitted JSON. * @param r the starting node. * @param buf the output buffer. * @param opts emit options. * @param error_on_excess Raise an error if the space in the buffer is insufficient. * @return a substr trimmed to the result in the output buffer. If the buffer is * insufficient (when error_on_excess is false), the string pointer of the * result will be set to null, and the length will report the required buffer size. */ RYML_EXPORT substr emit_json(ConstNodeRef const& r, EmitOptions const& opts, substr buf, bool error_on_excess=true); /** (2) like (1), but use default emit options */ RYML_EXPORT substr emit_json(ConstNodeRef const& r, substr buf, bool error_on_excess=true); /** @} */ } // namespace yml } // namespace c4 #endif /* C4_YML_EMIT_HPP_ */ // (end src/c4/yml/emit_buf.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/emit_container.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_EMIT_CONTAINER_HPP_ #define C4_YML_EMIT_CONTAINER_HPP_ /** @file emit.hpp Utilities to emit YAML and JSON to resizeable containers. */ #ifndef C4_YML_EMIT_BUF_HPP_ //#include "c4/yml/emit_buf.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/emit_buf.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_EMIT_OPTIONS_HPP_ //#include "c4/yml/emit_options.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/emit_options.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_NODE_HPP_ //#include "c4/yml/node.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/node.hpp must have been amalgamated before this point" #endif namespace c4 { namespace yml { // emit from tree and node id --------------------------- /** @addtogroup doc_emit_to_container_from_node_id * * @{ */ /** (1) emit+resize: emit YAML to the given `std::string`/`std::vector`-like * container, resizing it as needed to fit the emitted YAML. If @p append is * set to true, the emitted YAML is appended at the end of the container. * * @return a substr trimmed to the emitted YAML (excluding the initial contents, when appending) */ template substr emitrs_yaml(Tree const& t, id_type id, EmitOptions const& opts, CharOwningContainer * cont, bool append=false) { const size_t startpos = append ? cont->size() : 0u; cont->resize(cont->capacity()); // otherwise the first emit would be certain to fail substr buf = to_substr(*cont).sub(startpos); substr ret = emit_yaml(t, id, opts, buf, /*error_on_excess*/false); cont->resize(startpos + ret.len); if(ret.len && !ret.str) { buf = to_substr(*cont).sub(startpos); ret = emit_yaml(t, id, opts, buf, /*error_on_excess*/true); } return ret; } /** (2) like (1), but use default emit options */ template substr emitrs_yaml(Tree const& t, id_type id, CharOwningContainer * cont, bool append=false) { return emitrs_yaml(t, id, EmitOptions{}, cont, append); } /** (1) emit+resize: emit JSON to the given `std::string`/`std::vector`-like * container, resizing it as needed to fit the emitted JSON. If @p append is * set to true, the emitted YAML is appended at the end of the container. * * @return a substr trimmed to the emitted JSON (excluding the initial contents, when appending) */ template substr emitrs_json(Tree const& t, id_type id, EmitOptions const& opts, CharOwningContainer * cont, bool append=false) { const size_t startpos = append ? cont->size() : 0u; cont->resize(cont->capacity()); // otherwise the first emit would be certain to fail substr buf = to_substr(*cont).sub(startpos); substr ret = emit_json(t, id, opts, buf, /*error_on_excess*/false); cont->resize(startpos + ret.len); if(ret.len && !ret.str) { buf = to_substr(*cont).sub(startpos); ret = emit_json(t, id, opts, buf, /*error_on_excess*/true); } return ret; } /** (2) like (1), but use default emit options */ template substr emitrs_json(Tree const& t, id_type id, CharOwningContainer * cont, bool append=false) { return emitrs_json(t, id, EmitOptions{}, cont, append); } /** (3) emit+resize: YAML to a newly-created `std::string`/`std::vector`-like container. */ template CharOwningContainer emitrs_yaml(Tree const& t, id_type id, EmitOptions const& opts={}) { CharOwningContainer c; emitrs_yaml(t, id, opts, &c); return c; } /** (3) emit+resize: JSON to a newly-created `std::string`/`std::vector`-like container. */ template CharOwningContainer emitrs_json(Tree const& t, id_type id, EmitOptions const& opts={}) { CharOwningContainer c; emitrs_json(t, id, opts, &c); return c; } /** @} */ // emit from root ------------------------- /** @addtogroup doc_emit_to_container_from_root * * @{ */ /** (1) emit+resize: YAML to the given `std::string`/`std::vector`-like * container, resizing it as needed to fit the emitted YAML. * @return a substr trimmed to the new emitted contents. */ template substr emitrs_yaml(Tree const& t, EmitOptions const& opts, CharOwningContainer * cont, bool append=false) { return emitrs_yaml(t, t.root_id_maybe(), opts, cont, append); } /** (2) like (1), but use default emit options */ template substr emitrs_yaml(Tree const& t, CharOwningContainer * cont, bool append=false) { return emitrs_yaml(t, t.root_id_maybe(), EmitOptions{}, cont, append); } /** (1) emit+resize: JSON to the given `std::string`/`std::vector`-like * container, resizing it as needed to fit the emitted JSON. * @return a substr trimmed to the new emitted contents. */ template substr emitrs_json(Tree const& t, EmitOptions const& opts, CharOwningContainer * cont, bool append=false) { return emitrs_json(t, t.root_id_maybe(), opts, cont, append); } /** (2) like (1), but use default emit options */ template substr emitrs_json(Tree const& t, CharOwningContainer * cont, bool append=false) { return emitrs_json(t, t.root_id_maybe(), EmitOptions{}, cont, append); } /** (3) emit+resize: YAML to a newly-created `std::string`/`std::vector`-like container. */ template CharOwningContainer emitrs_yaml(Tree const& t, EmitOptions const& opts={}) { CharOwningContainer c; emitrs_yaml(t, t.root_id_maybe(), opts, &c); return c; } /** (3) emit+resize: JSON to a newly-created `std::string`/`std::vector`-like container. */ template CharOwningContainer emitrs_json(Tree const& t, EmitOptions const& opts={}) { CharOwningContainer c; emitrs_json(t, t.root_id_maybe(), opts, &c); return c; } /** @} */ // emit from ConstNodeRef ------------------------ /** @addtogroup doc_emit_to_container_from_noderef * * @{ */ /** (1) emit+resize: YAML to the given `std::string`/`std::vector`-like container, * resizing it as needed to fit the emitted YAML. * @return a substr trimmed to the new emitted contents */ template substr emitrs_yaml(ConstNodeRef const& n, EmitOptions const& opts, CharOwningContainer * cont, bool append=false) { if(!n.readable()) return {}; return emitrs_yaml(*n.tree(), n.id(), opts, cont, append); } /** (2) like (1), but use default emit options */ template substr emitrs_yaml(ConstNodeRef const& n, CharOwningContainer * cont, bool append=false) { if(!n.readable()) return {}; return emitrs_yaml(*n.tree(), n.id(), EmitOptions{}, cont, append); } /** (1) emit+resize: JSON to the given `std::string`/`std::vector`-like container, * resizing it as needed to fit the emitted JSON. * @return a substr trimmed to the new emitted contents */ template substr emitrs_json(ConstNodeRef const& n, EmitOptions const& opts, CharOwningContainer * cont, bool append=false) { if(!n.readable()) return {}; return emitrs_json(*n.tree(), n.id(), opts, cont, append); } /** (2) like (1), but use default emit options */ template substr emitrs_json(ConstNodeRef const& n, CharOwningContainer * cont, bool append=false) { if(!n.readable()) return {}; return emitrs_json(*n.tree(), n.id(), EmitOptions{}, cont, append); } /** (3) emit+resize: YAML to a newly-created `std::string`/`std::vector`-like container. */ template CharOwningContainer emitrs_yaml(ConstNodeRef const& n, EmitOptions const& opts={}) { CharOwningContainer c; if(n.readable()) emitrs_yaml(*n.tree(), n.id(), opts, &c); return c; } /** (3) emit+resize: JSON to a newly-created `std::string`/`std::vector`-like container. */ template CharOwningContainer emitrs_json(ConstNodeRef const& n, EmitOptions const& opts={}) { CharOwningContainer c; if(n.readable()) emitrs_json(*n.tree(), n.id(), opts, &c); return c; } /** @} */ } // namespace yml } // namespace c4 #endif /* C4_YML_EMIT_CONTAINER_HPP_ */ // (end src/c4/yml/emit_container.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/emit_file.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_EMIT_FILE_HPP_ #define C4_YML_EMIT_FILE_HPP_ /** @file emit_file.hpp */ //#include // amalgamate: included above #ifndef C4_YML_COMMON_HPP_ //#include "c4/yml/common.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/common.hpp must have been amalgamated before this point" #endif namespace c4 { namespace yml { // fwd declarations /** @cond dev */ template class Emitter; struct WriterFile; class Tree; class ConstNodeRef; struct EmitOptions; /** @endcond */ /** @ingroup doc_emit_to_file */ using EmitterFile = Emitter; // emit from root ------------------------- /** @addtogroup doc_emit_to_file_from_root * * @{ */ /** (1) emit YAML to the given file, starting at the root node. A null file defaults to stdout. */ RYML_EXPORT void emit_yaml(Tree const& t, EmitOptions const& opts, FILE *f=nullptr); /** (2) like (1), but use default emit options */ RYML_EXPORT void emit_yaml(Tree const& t, FILE *f=nullptr); /** (1) emit JSON to the given file. A null file defaults to stdout. */ RYML_EXPORT void emit_json(Tree const& t, EmitOptions const& opts, FILE *f=nullptr); /** (2) like (1), but use default emit options */ RYML_EXPORT void emit_json(Tree const& t, FILE *f=nullptr); /** @} */ // emit from tree and node id ----------------------- /** @addtogroup doc_emit_to_file_from_node_id * * @{ */ /** (1) emit YAML to the given file, starting at the given node. A null * file defaults to stdout. */ RYML_EXPORT void emit_yaml(Tree const& t, id_type id, EmitOptions const& opts, FILE *f); /** (2) like (1), but use default emit options */ RYML_EXPORT void emit_yaml(Tree const& t, id_type id, FILE *f); /** (1) emit JSON to the given file, starting at the given node. A null * file defaults to stdout. */ RYML_EXPORT void emit_json(Tree const& t, id_type id, EmitOptions const& opts, FILE *f); /** (2) like (1), but use default emit options */ RYML_EXPORT void emit_json(Tree const& t, id_type id, FILE *f); /** @} */ // emit from ConstNodeRef ------------------------ /** @addtogroup doc_emit_to_file_from_noderef * * @{ */ /** (1) emit YAML to the given file. A null file defaults to stdout. * Return the number of bytes written. */ RYML_EXPORT void emit_yaml(ConstNodeRef const& r, EmitOptions const& opts, FILE *f=nullptr); /** (2) like (1), but use default emit options */ RYML_EXPORT void emit_yaml(ConstNodeRef const& r, FILE *f=nullptr); /** (1) emit JSON to the given file. A null file defaults to stdout. * Return the number of bytes written. */ RYML_EXPORT void emit_json(ConstNodeRef const& r, EmitOptions const& opts, FILE *f=nullptr); /** (2) like (1), but use default emit options */ RYML_EXPORT void emit_json(ConstNodeRef const& r, FILE *f=nullptr); /** @} */ } // namespace yml } // namespace c4 #endif /* C4_YML_EMIT_FILE_HPP_ */ // (end src/c4/yml/emit_file.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/emit_ostream.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_EMIT_OSTREAM_HPP_ #define C4_YML_EMIT_OSTREAM_HPP_ /** @file emit_ostream.hpp emit to STL-like ostreams */ #ifndef C4_YML_NODE_HPP_ //#include "c4/yml/node.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/node.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_EMITTER_HPP_ //#include "c4/yml/emitter.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/emitter.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_EMITTER_DEF_HPP_ //#include "c4/yml/emitter.def.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/emitter.def.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_WRITER_OSTREAM_HPP_ //#include "c4/yml/writer_ostream.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/writer_ostream.hpp must have been amalgamated before this point" #endif namespace c4 { namespace yml { /** @addtogroup doc_emit_to_ostream * * @{ */ template using EmitterOStream = Emitter>; /** tag type to mark a tree or node to be emitted as yaml when using * @ref operator<<, with options. For example: * * ```cpp * Tree t = parse_in_arena("{foo: bar}"); * std::cout << t; // emits YAML * std::cout << as_yaml(t, id); // emits YAML from nested node * std::cout << as_yaml(t, EmitOptions{}.flow_spc(true)); // emits YAML forcing spaces after flow commas * ``` */ struct as_json { Tree const* tree; id_type node; EmitOptions options; as_json(Tree const& t, EmitOptions const& opts={}) noexcept : tree(&t), node(t.root_id_maybe()), options(opts) {} as_json(Tree const& t, id_type id, EmitOptions const& opts={}) noexcept : tree(&t), node(id), options(opts) {} as_json(ConstNodeRef const& n, EmitOptions const& opts={}) noexcept : tree(n.tree()), node(n.id()), options(opts) {} }; /** tag type to mark a tree or node to be emitted as yaml when using * @ref operator<< . For example: * * ```cpp * Tree t = parse_in_arena("{foo: bar}"); * std::cout << t; // emits YAML * std::cout << as_yaml(t); // emits JSON * std::cout << as_yaml(t, id); // emits JSON from nested node * std::cout << as_json(t, EmitOptions{}.flow_spc(true)); // emits JSON forcing spaces after commas * ``` */ struct as_yaml { Tree const* tree; id_type node; EmitOptions options; as_yaml(Tree const& t, EmitOptions const& opts={}) noexcept : tree(&t), node(t.root_id_maybe()), options(opts) {} as_yaml(Tree const& t, id_type id, EmitOptions const& opts={}) noexcept : tree(&t), node(id), options(opts) {} as_yaml(ConstNodeRef const& n, EmitOptions const& opts={}) noexcept : tree(n.tree()), node(n.id()), options(opts) {} }; /** emit YAML to an STL-like ostream */ template OStream& operator<< (OStream& stream, Tree const& tree) { EmitterOStream em(EmitOptions{}, &stream); em.emit_as(EMIT_YAML, &tree); return stream; } /** emit YAML to an STL-like ostream * @overload */ template OStream& operator<< (OStream& stream, ConstNodeRef const& node) { EmitterOStream em(EmitOptions{}, &stream); em.emit_as(EMIT_YAML, node.tree(), node.id()); return stream; } /** emit JSON to an STL-like ostream */ template OStream& operator<< (OStream& stream, as_json const& json_spec) { if(json_spec.tree && !json_spec.tree->empty()) { EmitterOStream em(json_spec.options, &stream); id_type node_id = json_spec.node != NONE ? json_spec.node : json_spec.tree->root_id(); em.emit_as(EMIT_JSON, json_spec.tree, node_id); } return stream; } /** emit YAML to an STL-like ostream */ template OStream& operator<< (OStream& stream, as_yaml const& yaml_spec) { if(yaml_spec.tree && !yaml_spec.tree->empty()) { EmitterOStream em(yaml_spec.options, &stream); id_type node_id = yaml_spec.node != NONE ? yaml_spec.node : yaml_spec.tree->root_id(); em.emit_as(EMIT_YAML, yaml_spec.tree, node_id); } return stream; } /** @} */ } // namespace yml } // namespace c4 #endif /* C4_YML_EMIT_OSTREAM_HPP_ */ // (end src/c4/yml/emit_ostream.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/emit.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_EMIT_HPP_ #define C4_YML_EMIT_HPP_ /** @file emit.hpp Umbrella header with all utilities to emit YAML and JSON. */ #ifndef C4_YML_EMIT_BUF_HPP_ //#include "c4/yml/emit_buf.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/emit_buf.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_EMIT_CONTAINER_HPP_ //#include "c4/yml/emit_container.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/emit_container.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_EMIT_FILE_HPP_ //#include "c4/yml/emit_file.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/emit_file.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_EMIT_OSTREAM_HPP_ //#include "c4/yml/emit_ostream.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/emit_ostream.hpp must have been amalgamated before this point" #endif namespace c4 { namespace yml { //------------------------------------------------- // deprecated code /** @cond dev */ // LCOV_EXCL_START #define RYML_DEPRECATE_EMIT \ RYML_DEPRECATED("use emit_yaml() instead. " \ "See https://github.com/biojppm/rapidyaml/issues/120") #define RYML_DEPRECATE_EMITRS \ RYML_DEPRECATED("use emitrs_yaml() instead. " \ "See https://github.com/biojppm/rapidyaml/issues/120") // workaround for Qt emit which is a macro; // see https://github.com/biojppm/rapidyaml/issues/120. // emit is defined in qobjectdefs.h (as an empty define). #ifdef emit #define RYML_TMP_EMIT_ emit #undef emit #endif RYML_DEPRECATE_EMIT inline void emit(Tree const& t, id_type id, FILE *f) { emit_yaml(t, id, f); } RYML_DEPRECATE_EMIT inline void emit(Tree const& t, FILE *f=nullptr) { emit_yaml(t, f); } RYML_DEPRECATE_EMIT inline void emit(ConstNodeRef const& r, FILE *f=nullptr) { emit_yaml(r, f); } RYML_DEPRECATE_EMIT inline substr emit(Tree const& t, id_type id, substr buf, bool error_on_excess=true) { return emit_yaml(t, id, buf, error_on_excess); } RYML_DEPRECATE_EMIT inline substr emit(Tree const& t, substr buf, bool error_on_excess=true) { return emit_yaml(t, buf, error_on_excess); } RYML_DEPRECATE_EMIT inline substr emit(ConstNodeRef const& r, substr buf, bool error_on_excess=true) { return emit_yaml(r, buf, error_on_excess); } #ifdef RYML_TMP_EMIT_ #define emit RYML_TMP_EMIT_ #undef RYML_TMP_EMIT_ #endif template RYML_DEPRECATE_EMITRS substr emitrs(Tree const& t, id_type id, CharOwningContainer * cont) { return emitrs_yaml(t, id, cont); } template RYML_DEPRECATE_EMITRS CharOwningContainer emitrs(Tree const& t, id_type id) { return emitrs_yaml(t, id); } template RYML_DEPRECATE_EMITRS substr emitrs(Tree const& t, CharOwningContainer * cont) { return emitrs_yaml(t, cont); } template RYML_DEPRECATE_EMITRS CharOwningContainer emitrs(Tree const& t) { return emitrs_yaml(t); } template RYML_DEPRECATE_EMITRS substr emitrs(ConstNodeRef const& n, CharOwningContainer * cont) { return emitrs_yaml(n, cont); } template RYML_DEPRECATE_EMITRS CharOwningContainer emitrs(ConstNodeRef const& n) { return emitrs_yaml(n); } #undef RYML_DEPRECATE_EMIT #undef RYML_DEPRECATE_EMITRS /** @endcond */ // LCOV_EXCL_STOP } // namespace yml } // namespace c4 #endif /* C4_YML_EMIT_HPP_ */ // (end src/c4/yml/emit.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/filter_processor.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_FILTER_PROCESSOR_HPP_ #define C4_YML_FILTER_PROCESSOR_HPP_ #ifndef C4_YML_ERROR_HPP_ //#include "c4/yml/error.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/error.hpp must have been amalgamated before this point" #endif #ifdef RYML_DBG #ifndef C4_CHARCONV_HPP_ //#include "c4/charconv.hpp" // amalgamate: remove include #error "amalgamate: c4/charconv.hpp must have been amalgamated before this point" #endif /* C4_CHARCONV_HPP_ */ #ifndef C4_YML_DETAIL_DBGPRINT_HPP_ //#include "c4/yml/detail/dbgprint.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/detail/dbgprint.hpp must have been amalgamated before this point" #endif /* C4_YML_DETAIL_DBGPRINT_HPP_ */ #endif namespace c4 { namespace yml { /** @addtogroup doc_scalar_filter */ /** @{ */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** Result for filtering a scalar which not fit in the intended * memory. */ struct FilterResult { C4_ALWAYS_INLINE bool valid() const noexcept { return str.str != nullptr; } C4_ALWAYS_INLINE size_t required_len() const noexcept { return str.len; } C4_ALWAYS_INLINE csubstr get() const { RYML_ASSERT_BASIC_(valid()); return str; } csubstr str; }; /** Result for filtering a scalar which not fit in the intended * memory. */ struct FilterResultExtending { C4_ALWAYS_INLINE bool valid() const noexcept { return str.str != nullptr; } C4_ALWAYS_INLINE size_t required_len() const noexcept { return reqlen; } C4_ALWAYS_INLINE csubstr get() const { RYML_ASSERT_BASIC_(valid()); return str; } csubstr str; size_t reqlen; }; //----------------------------------------------------------------------------- /** Filters an input string into a different output string */ struct FilterProcessorSrcDst { csubstr src; substr dst; size_t rpos; ///< read position size_t wpos; ///< write position C4_ALWAYS_INLINE FilterProcessorSrcDst(csubstr src_, substr dst_) noexcept : src(src_) , dst(dst_) , rpos(0) , wpos(0) { RYML_ASSERT_BASIC_(!dst.overlaps(src)); } C4_ALWAYS_INLINE void setwpos(size_t wpos_) noexcept { wpos = wpos_; } C4_ALWAYS_INLINE void setpos(size_t rpos_, size_t wpos_) noexcept { rpos = rpos_; wpos = wpos_; } C4_ALWAYS_INLINE void set_at_end() noexcept { skip(src.len - rpos); } C4_ALWAYS_INLINE bool has_more_chars() const noexcept { return rpos < src.len; } C4_ALWAYS_INLINE bool has_more_chars(size_t maxpos) const noexcept { RYML_ASSERT_BASIC_(maxpos <= src.len); return rpos < maxpos; } C4_ALWAYS_INLINE csubstr rem() const noexcept { return src.sub(rpos); } C4_ALWAYS_INLINE csubstr sofar() const noexcept { return csubstr(dst.str, wpos <= dst.len ? wpos : dst.len); } C4_ALWAYS_INLINE FilterResult result() const noexcept { FilterResult ret; ret.str.str = wpos <= dst.len ? dst.str : nullptr; ret.str.len = wpos; return ret; } C4_ALWAYS_INLINE char curr() const noexcept { RYML_ASSERT_BASIC_(rpos < src.len); return src[rpos]; } C4_ALWAYS_INLINE char next() const noexcept { return rpos+1 < src.len ? src[rpos+1] : '\0'; } C4_ALWAYS_INLINE bool skipped_chars() const noexcept { return wpos != rpos; } C4_ALWAYS_INLINE void skip() noexcept { ++rpos; } C4_ALWAYS_INLINE void skip(size_t num) noexcept { rpos += num; } C4_ALWAYS_INLINE void set_at(size_t pos, char c) noexcept // NOLINT(readability-make-member-function-const) { RYML_ASSERT_BASIC_(pos < wpos); dst.str[pos] = c; } C4_ALWAYS_INLINE void set(char c) noexcept { if(wpos < dst.len) dst.str[wpos] = c; ++wpos; } C4_ALWAYS_INLINE void set(char c, size_t num) noexcept { RYML_ASSERT_BASIC_(num > 0); if(wpos + num <= dst.len) memset(dst.str + wpos, c, num); wpos += num; } C4_ALWAYS_INLINE void copy() noexcept { RYML_ASSERT_BASIC_(rpos < src.len); if(wpos < dst.len) dst.str[wpos] = src.str[rpos]; ++wpos; ++rpos; } C4_ALWAYS_INLINE void copy(size_t num) noexcept { RYML_ASSERT_BASIC_(num); RYML_ASSERT_BASIC_(rpos+num <= src.len); if(wpos + num <= dst.len) memcpy(dst.str + wpos, src.str + rpos, num); wpos += num; rpos += num; } C4_ALWAYS_INLINE void translate_esc(char c) noexcept { if(wpos < dst.len) dst.str[wpos] = c; ++wpos; rpos += 2; } C4_ALWAYS_INLINE void translate_esc_bulk(const char *C4_RESTRICT s, size_t nw, size_t nr) noexcept { RYML_ASSERT_BASIC_(nw > 0); RYML_ASSERT_BASIC_(nr > 0); RYML_ASSERT_BASIC_(rpos+nr <= src.len); if(wpos+nw <= dst.len) memcpy(dst.str + wpos, s, nw); wpos += nw; rpos += 1 + nr; } C4_ALWAYS_INLINE void translate_esc_extending(const char *C4_RESTRICT s, size_t nw, size_t nr) noexcept { translate_esc_bulk(s, nw, nr); } }; //----------------------------------------------------------------------------- // filter in place // debugging scaffold /** @cond dev */ #if defined(RYML_DBG) && 0 #define _c4dbgip(...) _c4dbgpf(__VA_ARGS__) #else #define _c4dbgip(...) #endif /** @endcond */ /** Filters in place. While the result may be larger than the source, * any extending happens only at the end of the string. Consequently, * it's impossible for characters to be left unfiltered. * * @see FilterProcessorInplaceMidExtending */ struct FilterProcessorInplaceEndExtending { substr src; ///< the subject string size_t wcap; ///< write capacity - the capacity of the subject string's buffer size_t rpos; ///< read position size_t wpos; ///< write position C4_ALWAYS_INLINE FilterProcessorInplaceEndExtending(substr src_, size_t wcap_) noexcept : src(src_) , wcap(wcap_) , rpos(0) , wpos(0) { RYML_ASSERT_BASIC_(wcap >= src.len); } C4_ALWAYS_INLINE void setwpos(size_t wpos_) noexcept { wpos = wpos_; } C4_ALWAYS_INLINE void setpos(size_t rpos_, size_t wpos_) noexcept { rpos = rpos_; wpos = wpos_; } C4_ALWAYS_INLINE void set_at_end() noexcept { skip(src.len - rpos); } C4_ALWAYS_INLINE bool has_more_chars() const noexcept { return rpos < src.len; } C4_ALWAYS_INLINE bool has_more_chars(size_t maxpos) const noexcept { RYML_ASSERT_BASIC_(maxpos <= src.len); return rpos < maxpos; } C4_ALWAYS_INLINE FilterResult result() const noexcept { _c4dbgip("inplace: wpos={} wcap={} small={}", wpos, wcap, wpos > rpos); FilterResult ret; ret.str.str = (wpos <= wcap) ? src.str : nullptr; ret.str.len = wpos; return ret; } C4_ALWAYS_INLINE csubstr sofar() const noexcept { return csubstr(src.str, wpos <= wcap ? wpos : wcap); } C4_ALWAYS_INLINE csubstr rem() const noexcept { return src.sub(rpos); } C4_ALWAYS_INLINE char curr() const noexcept { RYML_ASSERT_BASIC_(rpos < src.len); return src[rpos]; } C4_ALWAYS_INLINE char next() const noexcept { return rpos+1 < src.len ? src[rpos+1] : '\0'; } C4_ALWAYS_INLINE void skip() noexcept { ++rpos; } C4_ALWAYS_INLINE void skip(size_t num) noexcept { rpos += num; } void set_at(size_t pos, char c) noexcept { RYML_ASSERT_BASIC_(pos < wpos); const size_t save = wpos; wpos = pos; set(c); wpos = save; } void set(char c) noexcept { if(wpos < wcap) // respect write-capacity src.str[wpos] = c; ++wpos; } void set(char c, size_t num) noexcept { RYML_ASSERT_BASIC_(num); if(wpos + num <= wcap) // respect write-capacity memset(src.str + wpos, c, num); wpos += num; } void copy() noexcept { RYML_ASSERT_BASIC_(wpos <= rpos); RYML_ASSERT_BASIC_(rpos < src.len); if(wpos < wcap) // respect write-capacity src.str[wpos] = src.str[rpos]; ++rpos; ++wpos; } void copy(size_t num) noexcept { RYML_ASSERT_BASIC_(num); RYML_ASSERT_BASIC_(rpos+num <= src.len); RYML_ASSERT_BASIC_(wpos <= rpos); if(wpos + num <= wcap) // respect write-capacity { if(wpos + num <= rpos) // there is no overlap memcpy(src.str + wpos, src.str + rpos, num); else // there is overlap memmove(src.str + wpos, src.str + rpos, num); } rpos += num; wpos += num; } void translate_esc(char c) noexcept { RYML_ASSERT_BASIC_(rpos + 2 <= src.len); RYML_ASSERT_BASIC_(wpos <= rpos); if(wpos < wcap) // respect write-capacity src.str[wpos] = c; rpos += 2; // add 1u to account for the escape character ++wpos; } void translate_esc_bulk(const char *C4_RESTRICT s, size_t nw, size_t nr) noexcept { RYML_ASSERT_BASIC_(nw > 0); RYML_ASSERT_BASIC_(nr > 0); RYML_ASSERT_BASIC_(nw <= nr + 1u); RYML_ASSERT_BASIC_(rpos+nr <= src.len); RYML_ASSERT_BASIC_(wpos <= rpos); const size_t wpos_next = wpos + nw; const size_t rpos_next = rpos + nr + 1u; // add 1u to account for the escape character RYML_ASSERT_BASIC_(wpos_next <= rpos_next); if(wpos_next <= wcap) memcpy(src.str + wpos, s, nw); rpos = rpos_next; wpos = wpos_next; } C4_ALWAYS_INLINE void translate_esc_extending(const char *C4_RESTRICT s, size_t nw, size_t nr) noexcept { translate_esc_bulk(s, nw, nr); } }; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** Filters in place. The result may be larger than the source, and * extending may happen anywhere. As a result some characters may be * left unfiltered when there is no slack in the buffer and the * write-position would overlap the read-position. Consequently, it's * possible for characters to be left unfiltered. In YAML, this * happens only with double-quoted strings, and only with a small * number of escape sequences such as `\L` which is substituted by three * bytes. These escape sequences cause a call to translate_esc_extending() * which is the only entry point to this unfiltered situation. * * @see FilterProcessorInplaceEndExtending */ struct FilterProcessorInplaceMidExtending { substr src; ///< the subject string size_t wcap; ///< write capacity - the capacity of the subject string's buffer size_t rpos; ///< read position size_t wpos; ///< write position size_t maxcap; ///< the max capacity needed for filtering the string. This may be larger than the final string size. bool unfiltered_chars; ///< number of characters that were not added to wpos from lack of capacity C4_ALWAYS_INLINE FilterProcessorInplaceMidExtending(substr src_, size_t wcap_) noexcept : src(src_) , wcap(wcap_) , rpos(0) , wpos(0) , maxcap(src.len) , unfiltered_chars(false) { RYML_ASSERT_BASIC_(wcap >= src.len); } C4_ALWAYS_INLINE void setwpos(size_t wpos_) noexcept { wpos = wpos_; } C4_ALWAYS_INLINE void setpos(size_t rpos_, size_t wpos_) noexcept { rpos = rpos_; wpos = wpos_; } C4_ALWAYS_INLINE void set_at_end() noexcept { skip(src.len - rpos); } C4_ALWAYS_INLINE bool has_more_chars() const noexcept { return rpos < src.len; } C4_ALWAYS_INLINE bool has_more_chars(size_t maxpos) const noexcept { RYML_ASSERT_BASIC_(maxpos <= src.len); return rpos < maxpos; } C4_ALWAYS_INLINE FilterResultExtending result() const noexcept { _c4dbgip("inplace: wpos={} wcap={} unfiltered={} maxcap={}", this->wpos, this->wcap, this->unfiltered_chars, this->maxcap); FilterResultExtending ret; ret.str.str = (wpos <= wcap && !unfiltered_chars) ? src.str : nullptr; ret.str.len = wpos; ret.reqlen = maxcap; return ret; } C4_ALWAYS_INLINE csubstr sofar() const noexcept { return csubstr(src.str, wpos <= wcap ? wpos : wcap); } C4_ALWAYS_INLINE csubstr rem() const noexcept { return src.sub(rpos); } C4_ALWAYS_INLINE char curr() const noexcept { RYML_ASSERT_BASIC_(rpos < src.len); return src[rpos]; } C4_ALWAYS_INLINE char next() const noexcept { return rpos+1 < src.len ? src[rpos+1] : '\0'; } C4_ALWAYS_INLINE void skip() noexcept { ++rpos; } C4_ALWAYS_INLINE void skip(size_t num) noexcept { rpos += num; } void set_at(size_t pos, char c) noexcept { RYML_ASSERT_BASIC_(pos < wpos); const size_t save = wpos; wpos = pos; set(c); wpos = save; } void set(char c) noexcept { if(wpos < wcap) // respect write-capacity { if((wpos <= rpos) && !unfiltered_chars) src.str[wpos] = c; } else { _c4dbgip("inplace: add unwritten {}->{} maxcap={}->{}!", unfiltered_chars, true, maxcap, (wpos+1u > maxcap ? wpos+1u : maxcap)); unfiltered_chars = true; } ++wpos; maxcap = wpos > maxcap ? wpos : maxcap; } void set(char c, size_t num) noexcept { RYML_ASSERT_BASIC_(num); if(wpos + num <= wcap) // respect write-capacity { if((wpos <= rpos) && !unfiltered_chars) memset(src.str + wpos, c, num); } else { _c4dbgip("inplace: add unwritten {}->{} maxcap={}->{}!", unfiltered_chars, true, maxcap, (wpos+num > maxcap ? wpos+num : maxcap)); unfiltered_chars = true; } wpos += num; maxcap = wpos > maxcap ? wpos : maxcap; } void copy() noexcept { RYML_ASSERT_BASIC_(rpos < src.len); if(wpos < wcap) // respect write-capacity { if((wpos < rpos) && !unfiltered_chars) // write only if wpos is behind rpos src.str[wpos] = src.str[rpos]; } else { _c4dbgip("inplace: add unwritten {}->{} (wpos={}!=rpos={})={} (wpos={}{}!", unfiltered_chars, true, wpos, rpos, wpos!=rpos, wpos, wcap, wpos maxcap ? wpos+1u : maxcap)); unfiltered_chars = true; } ++rpos; ++wpos; maxcap = wpos > maxcap ? wpos : maxcap; } void copy(size_t num) noexcept { RYML_ASSERT_BASIC_(num); RYML_ASSERT_BASIC_(rpos+num <= src.len); if(wpos + num <= wcap) // respect write-capacity { if((wpos < rpos) && !unfiltered_chars) // write only if wpos is behind rpos { if(wpos + num <= rpos) // there is no overlap memcpy(src.str + wpos, src.str + rpos, num); else // there is overlap memmove(src.str + wpos, src.str + rpos, num); } } else { _c4dbgip("inplace: add unwritten {}->{} (wpos={}!=rpos={})={} (wpos={}{}!", unfiltered_chars, true, wpos, rpos, wpos!=rpos, wpos, wcap, wpos maxcap ? wpos : maxcap; } void translate_esc(char c) noexcept { RYML_ASSERT_BASIC_(rpos + 2 <= src.len); if(wpos < wcap) // respect write-capacity { if((wpos <= rpos) && !unfiltered_chars) src.str[wpos] = c; } else { _c4dbgip("inplace: add unfiltered {}->{} maxcap={}->{}!", unfiltered_chars, true, maxcap, (wpos+1u > maxcap ? wpos+1u : maxcap)); unfiltered_chars = true; } rpos += 2; ++wpos; maxcap = wpos > maxcap ? wpos : maxcap; } C4_NO_INLINE void translate_esc_bulk(const char *C4_RESTRICT s, size_t nw, size_t nr) noexcept { RYML_ASSERT_BASIC_(nw > 0); RYML_ASSERT_BASIC_(nr > 0); RYML_ASSERT_BASIC_(nr+1u >= nw); const size_t wpos_next = wpos + nw; const size_t rpos_next = rpos + nr + 1u; // add 1u to account for the escape character if(wpos_next <= wcap) // respect write-capacity { if((wpos <= rpos) && !unfiltered_chars) // write only if wpos is behind rpos memcpy(src.str + wpos, s, nw); } else { _c4dbgip("inplace: add unwritten {}->{} (wpos={}!=rpos={})={} (wpos={}{}!", unfiltered_chars, true, wpos, rpos, wpos!=rpos, wpos, wcap, wpos maxcap ? wpos : maxcap; } C4_NO_INLINE void translate_esc_extending(const char *C4_RESTRICT s, size_t nw, size_t nr) noexcept { RYML_ASSERT_BASIC_(nw > 0); RYML_ASSERT_BASIC_(nr > 0); RYML_ASSERT_BASIC_(rpos+nr <= src.len); const size_t wpos_next = wpos + nw; const size_t rpos_next = rpos + nr + 1u; // add 1u to account for the escape character if(wpos_next <= rpos_next) // read and write do not overlap. just do a vanilla copy. { if((wpos_next <= wcap) && !unfiltered_chars) memcpy(src.str + wpos, s, nw); rpos = rpos_next; wpos = wpos_next; maxcap = wpos > maxcap ? wpos : maxcap; } else // there is overlap. move the (to-be-read) string to the right. { const size_t excess = wpos_next - rpos_next; RYML_ASSERT_BASIC_(wpos_next > rpos_next); if(src.len + excess <= wcap) // ensure we do not go past the end { RYML_ASSERT_BASIC_(rpos+nr+excess <= src.len); if(wpos_next <= wcap) { if(!unfiltered_chars) { memmove(src.str + wpos_next, src.str + rpos_next, src.len - rpos_next); memcpy(src.str + wpos, s, nw); } rpos = wpos_next; // wpos, not rpos } else { rpos = rpos_next; //const size_t unw = nw > (nr + 1u) ? nw - (nr + 1u) : 0; _c4dbgip("inplace: add unfiltered {}->{} maxcap={}->{}!", unfiltered_chars, true); unfiltered_chars = true; } wpos = wpos_next; // extend the string up to capacity src.len += excess; maxcap = wpos > maxcap ? wpos : maxcap; } else { //const size_t unw = nw > (nr + 1u) ? nw - (nr + 1u) : 0; RYML_ASSERT_BASIC_(rpos_next <= src.len); const size_t required_size = wpos_next + (src.len - rpos_next); _c4dbgip("inplace: add unfiltered {}->{} maxcap={}->{}!", unfiltered_chars, true, maxcap, required_size > maxcap ? required_size : maxcap); RYML_ASSERT_BASIC_(required_size > wcap); unfiltered_chars = true; maxcap = required_size > maxcap ? required_size : maxcap; wpos = wpos_next; rpos = rpos_next; } } } }; #undef _c4dbgip /** @} */ } // namespace yml } // namespace c4 #endif /* C4_YML_FILTER_PROCESSOR_HPP_ */ // (end src/c4/yml/filter_processor.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/parser_state.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_PARSER_STATE_HPP_ #define C4_YML_PARSER_STATE_HPP_ #ifndef C4_YML_ERROR_HPP_ //#include "c4/yml/error.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/error.hpp must have been amalgamated before this point" #endif // NOLINTBEGIN(hicpp-signed-bitwise) namespace c4 { namespace yml { /** data type for @ref ParserState_e */ using ParserFlag_t = int; /** Enumeration of the state flags for the parser */ typedef enum : ParserFlag_t { // NOLINT RTOP = 0x01 << 0, ///< reading at top level RUNK = 0x01 << 1, ///< reading unknown state (when starting): must determine whether scalar, map or seq RMAP = 0x01 << 2, ///< reading a map RSEQ = 0x01 << 3, ///< reading a seq RFLOW = 0x01 << 4, ///< reading is inside explicit flow chars: [] or {} RBLCK = 0x01 << 5, ///< reading in block mode QMRK = 0x01 << 6, ///< reading an explicit key (`? key`) RKEY = 0x01 << 7, ///< reading a key RVAL = 0x01 << 9, ///< reading a val RKCL = 0x01 << 8, ///< reading the key colon (ie the : after the key in the map) RNXT = 0x01 << 10, ///< read next sibling SSCL = 0x01 << 11, ///< there's a stored scalar QSCL = 0x01 << 12, ///< stored scalar was quoted RSET = 0x01 << 13, ///< the (implicit) map being read is a !!set. @see https://yaml.org/type/set.html RDOC = 0x01 << 14, ///< reading a document NDOC = 0x01 << 15, ///< no document mode. a document has ended and another has not started yet. USTY = 0x01 << 16, ///< reading in unknown style mode - must determine FLOW or BLCK //! reading an implicit map nested in an explicit seq. //! eg, {key: [key2: value2, key3: value3]} //! is parsed as {key: [{key2: value2}, {key3: value3}]} RSEQIMAP = 0x01 << 17, } ParserState_e; /** @cond dev */ #ifdef RYML_DBG namespace detail { RYML_EXPORT csubstr _parser_flags_to_str(substr buf, ParserFlag_t flags); } // namespace detail #endif /** @endcond */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** Helper to control the line contents while parsing a buffer */ struct LineContents { substr rem; ///< current line remainder, without newline characters substr full; ///< full line, including newline characters `\n` and `\r` size_t num_cols; ///< number of columns in the line, excluding newline ///< characters (ie the initial size of rem) size_t indentation; ///< number of spaces on the beginning of the line. LineContents() RYML_NOEXCEPT = default; void reset_with_next_line(substr buf, size_t start) RYML_NOEXCEPT { RYML_ASSERT_BASIC_(start <= buf.len); size_t end = start; // get the current line stripped of newline chars while((end < buf.len) && (buf.str[end] != '\n')) ++end; if(end < buf.len) { RYML_ASSERT_BASIC_(buf[end] == '\n'); full = buf.range(start, end + 1); rem = buf.range(start, end); } else { // buffer ends without newline full = rem = buf.sub(start); } size_t pos = rem.last_not_of('\r'); rem.len = (pos != npos) ? pos + 1 : 0; num_cols = rem.len; RYML_ASSERT_BASIC_(rem.find('\r') == npos); // TODO move this to the parser state indentation = rem.first_not_of(' '); // find the first column where the character is not a space } C4_ALWAYS_INLINE size_t current_col() const RYML_NOEXCEPT { RYML_ASSERT_BASIC_(rem.str >= full.str); return static_cast(rem.str - full.str); } C4_ALWAYS_INLINE size_t current_col(csubstr s) const RYML_NOEXCEPT { RYML_ASSERT_BASIC_(s.str >= full.str); RYML_ASSERT_BASIC_(s.str <= rem.end()); return static_cast(s.str - full.str); } }; static_assert(std::is_standard_layout::value, "LineContents not standard"); //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- struct ParserState { LineContents line_contents; Location pos; ParserFlag_t flags; size_t indref; ///< the reference indentation in the current block scope id_type level; id_type node_id; ///< don't hold a pointer to the node as it will be relocated during tree resizes size_t scalar_col; // the column where the scalar (or its quotes) begin bool more_indented; bool has_children; ParserState() = default; void start_parse(const char *file, id_type node_id_) { level = 0; pos.name = to_csubstr(file); pos.offset = 0; pos.line = 1; pos.col = 1; node_id = node_id_; more_indented = false; scalar_col = 0; indref = 0; has_children = false; } void reset_after_push() { node_id = NONE; indref = npos; more_indented = false; ++level; has_children = false; } C4_ALWAYS_INLINE void reset_before_pop(ParserState const& to_pop) { pos = to_pop.pos; line_contents = to_pop.line_contents; } public: C4_ALWAYS_INLINE bool at_line_beginning() const noexcept { return line_contents.rem.str == line_contents.full.str; } C4_ALWAYS_INLINE bool at_first_token() const noexcept { RYML_ASSERT_BASIC_(line_contents.indentation != npos); return pos.col == line_contents.indentation + 1; } C4_ALWAYS_INLINE bool indentation_eq() const noexcept { RYML_ASSERT_BASIC_(indref != npos); return line_contents.indentation != npos && line_contents.indentation == indref; } C4_ALWAYS_INLINE bool indentation_eq_extra() const noexcept { RYML_ASSERT_BASIC_(indref != npos); return line_contents.indentation != npos && line_contents.indentation == indref + 1u; } C4_ALWAYS_INLINE bool indentation_ge() const noexcept { RYML_ASSERT_BASIC_(indref != npos); return line_contents.indentation != npos && line_contents.indentation >= indref; } C4_ALWAYS_INLINE bool indentation_ge_extra() const noexcept { RYML_ASSERT_BASIC_(indref != npos); return line_contents.indentation != npos && line_contents.indentation >= indref + 1u; } C4_ALWAYS_INLINE bool indentation_gt() const noexcept { RYML_ASSERT_BASIC_(indref != npos); return line_contents.indentation != npos && line_contents.indentation > indref; } C4_ALWAYS_INLINE bool indentation_gt_extra() const noexcept { RYML_ASSERT_BASIC_(indref != npos); return line_contents.indentation != npos && line_contents.indentation > indref + 1u; } C4_ALWAYS_INLINE bool indentation_lt() const noexcept { RYML_ASSERT_BASIC_(indref != npos); return line_contents.indentation != npos && line_contents.indentation < indref; } C4_ALWAYS_INLINE bool indentation_lt_extra() const noexcept { RYML_ASSERT_BASIC_(indref != npos); return line_contents.indentation != npos && line_contents.indentation < indref + 1u; } }; static_assert(std::is_standard_layout::value, "ParserState not standard"); } // namespace yml } // namespace c4 // NOLINTEND(hicpp-signed-bitwise) #endif /* C4_YML_PARSER_STATE_HPP_ */ // (end src/c4/yml/parser_state.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/event_handler_stack.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_EVENT_HANDLER_STACK_HPP_ #define C4_YML_EVENT_HANDLER_STACK_HPP_ #ifndef C4_YML_DETAIL_STACK_HPP_ //#include "c4/yml/detail/stack.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/detail/stack.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_NODE_TYPE_HPP_ //#include "c4/yml/node_type.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/node_type.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_DETAIL_DBGPRINT_HPP_ //#include "c4/yml/detail/dbgprint.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/detail/dbgprint.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_PARSER_STATE_HPP_ //#include "c4/yml/parser_state.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/parser_state.hpp must have been amalgamated before this point" #endif #ifdef RYML_DBG #ifndef C4_YML_DETAIL_PRINT_HPP_ //#include "c4/yml/detail/print.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/detail/print.hpp must have been amalgamated before this point" #endif #endif // NOLINTBEGIN(hicpp-signed-bitwise) namespace c4 { namespace yml { /** @addtogroup doc_event_handlers * @{ */ /** Use this class a base of implementations of event handler to * simplify the stack logic. */ template struct EventHandlerStack { static_assert(std::is_base_of::value, "ParserState must be a base of HandlerState"); using state = HandlerState; public: detail::stack m_stack; state *C4_RESTRICT m_curr; ///< current stack level: top of the stack. cached here for easier access. state *C4_RESTRICT m_parent; ///< parent of the current stack level. substr m_src; protected: EventHandlerStack() : m_stack(), m_curr(), m_parent(), m_src() {} // NOLINT EventHandlerStack(Callbacks const& cb) : m_stack(cb), m_curr(), m_parent(), m_src() {} // NOLINT protected: void _stack_start_parse(const char *filename, substr ymlsrc) { RYML_ASSERT_BASIC_CB_(m_stack.m_callbacks, m_curr != nullptr); m_curr->start_parse(filename, m_curr->node_id); m_src = ymlsrc; } void _stack_finish_parse() { } protected: void _stack_reset_root() { m_stack.clear(); m_stack.push({}); m_parent = nullptr; m_curr = &m_stack.top(); } void _stack_reset_non_root() { m_stack.clear(); m_stack.push({}); // parent m_stack.push({}); // node m_parent = &m_stack.top(1); m_curr = &m_stack.top(); } void _stack_push() { m_stack.push_top(); m_parent = &m_stack.top(1); // don't use m_curr. watch out for relocations inside the prev push m_curr = &m_stack.top(); m_curr->reset_after_push(); } void _stack_pop() { RYML_ASSERT_BASIC_CB_(m_stack.m_callbacks, m_parent); RYML_ASSERT_BASIC_CB_(m_stack.m_callbacks, m_stack.size() > 1); m_parent->reset_before_pop(*m_curr); m_stack.pop(); m_parent = m_stack.size() > 1 ? &m_stack.top(1) : nullptr; m_curr = &m_stack.top(); #ifdef RYML_DBG if(m_parent) _c4dbgpf("popped! top is now node={} (parent={})", m_curr->node_id, m_parent->node_id); else _c4dbgpf("popped! top is now node={} @ ROOT", m_curr->node_id); #endif } protected: // undefined below #define ryml_has_any_(bits) (static_cast(this)->template has_any_()) // FIXME. Not happy about where these functions are. They should // be defined and called by the parser, passing the bool result to // begin_doc()/end_doc() as well as begin_doc_expl()/end_doc_expl(). bool _stack_should_push_on_begin_doc() const { const bool is_root = (m_stack.size() == 1u); return is_root && (m_curr->has_children || ryml_has_any_(DOC|VAL|MAP|SEQ)); } bool _stack_should_pop_on_end_doc() const { const bool is_root = (m_stack.size() == 1u); return !is_root && ryml_has_any_(DOC); } #undef ryml_has_any_ }; /** @} */ } // namespace yml } // namespace c4 // NOLINTEND(hicpp-signed-bitwise) #endif /* C4_YML_EVENT_HANDLER_STACK_HPP_ */ // (end src/c4/yml/event_handler_stack.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/event_handler_tree.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_EVENT_HANDLER_TREE_HPP_ #define C4_YML_EVENT_HANDLER_TREE_HPP_ #ifndef C4_YML_TREE_HPP_ //#include "c4/yml/tree.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/tree.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_EVENT_HANDLER_STACK_HPP_ //#include "c4/yml/event_handler_stack.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/event_handler_stack.hpp must have been amalgamated before this point" #endif C4_SUPPRESS_WARNING_GCC_PUSH C4_SUPPRESS_WARNING_MSVC_PUSH C4_SUPPRESS_WARNING_MSVC(4702) // unreachable code #if defined(__GNUC__) && __GNUC__ >= 6 C4_SUPPRESS_WARNING_GCC("-Wnull-dereference") #endif // NOLINTBEGIN(hicpp-signed-bitwise) namespace c4 { namespace yml { /** @addtogroup doc_event_handlers_tree * * An event handler used by @ref ParseEngine to create the @ref Tree * (see @ref Parser). * * @{ */ /** @cond dev */ struct EventHandlerTreeState : public ParserState { NodeData *tr_data; }; /** @endcond */ /** The event handler to create a ryml @ref Tree. See the * documentation for @ref doc_event_handlers, which has important * notes about the event model used by rapidyaml. */ struct EventHandlerTree : public EventHandlerStack { /** @name types * @{ */ using state = EventHandlerTreeState; enum { requires_strings_on_buffers = false }; // NOLINT /** @} */ public: /** @cond dev */ Tree *C4_RESTRICT m_tree; id_type m_curr_doc; TagCache m_tag_cache; #ifdef RYML_DBG #define ryml_enable_(bits) enable_(); _c4dbgpf("node[{}]: enable {}", m_curr->node_id, #bits) #define ryml_disable_(bits) disable_(); _c4dbgpf("node[{}]: disable {}", m_curr->node_id, #bits) #else #define ryml_enable_(bits) enable_() #define ryml_disable_(bits) disable_() #endif #define ryml_hasany_(bits) has_any_() /** @endcond */ public: /** @name construction and resetting * @{ */ EventHandlerTree() noexcept : EventHandlerStack(), m_tree(), m_curr_doc() {} EventHandlerTree(Callbacks const& cb) noexcept : EventHandlerStack(cb), m_tree(), m_curr_doc() {} EventHandlerTree(Tree *tree, id_type id) /*except!*/ : EventHandlerStack(tree->callbacks()), m_tree(tree), m_curr_doc() { reset(tree, id); } void reset(Tree *tree, id_type id) { if C4_UNLIKELY(!tree) RYML_ERR_BASIC_CB_(m_stack.m_callbacks, "null tree"); if C4_UNLIKELY(id >= tree->capacity()) RYML_ERR_VISIT_CB_(tree->callbacks(), tree, id, "invalid node"); if C4_UNLIKELY(!tree->is_root(id)) if C4_UNLIKELY(tree->is_map(tree->parent(id))) if C4_UNLIKELY(!tree->has_key(id)) RYML_ERR_BASIC_CB_(tree->callbacks(), "destination node belongs to a map and has no key"); m_tree = tree; if(m_tree->is_root(id)) { _stack_reset_root(); _reset_parser_state(m_curr, id, m_tree->root_id()); } else { _stack_reset_non_root(); _reset_parser_state(m_parent, id, m_tree->parent(id)); _reset_parser_state(m_curr, id, id); } m_curr_doc = m_tree->ancestor_doc(id); m_tag_cache.clear(); } Callbacks const& callbacks() const { return m_stack.m_callbacks; } C4_ALWAYS_INLINE TagDirectives& tag_directives() { return m_tree->m_tag_directives; } // NOLINT(readability-make-member-function-const) C4_ALWAYS_INLINE TagCache &tag_cache() { return m_tag_cache; } /** @} */ public: /** @name parse events * @{ */ void start_parse(const char* filename, substr ymlsrc) { RYML_ASSERT_BASIC_CB_(m_stack.m_callbacks, m_tree != nullptr); this->_stack_start_parse(filename, ymlsrc); } void finish_parse() { RYML_ASSERT_BASIC_CB_(m_stack.m_callbacks, m_tree != nullptr); this->_stack_finish_parse(); /* This pointer is temporary. Remember that: * * - this handler object may be held by the user * - it may be used with a temporary tree inside the parse function * - when the parse function returns the temporary tree, its address * will change * * As a result, the user could try to read the tree from m_tree, and * end up reading the stale temporary object. * * So it is better to clear it here; then the user will get an obvious * segfault if reading from m_tree. */ m_tree = nullptr; } void cancel_parse() { m_tree = nullptr; } /** @} */ public: /** @name YAML stream events */ /** @{ */ C4_ALWAYS_INLINE void begin_stream() const noexcept { /* nothing to do */ } C4_ALWAYS_INLINE void end_stream() const noexcept { /* nothing to do */ } /** @} */ public: /** @name YAML document events */ /** @{ */ /** implicit doc start (without ---) */ void begin_doc() { _c4dbgp("begin_doc"); if(_stack_should_push_on_begin_doc()) { _c4dbgp("push!"); _set_root_as_stream(); _push(); ryml_enable_(DOC); } m_curr_doc = m_curr->node_id; } /** implicit doc end (without ...) */ void end_doc() { _c4dbgp("end_doc"); m_curr_doc = m_tree->size(); if(_stack_should_pop_on_end_doc()) { _remove_speculative(); _c4dbgp("pop!"); _pop(); } } /** explicit doc start, with --- */ void begin_doc_expl() { _c4dbgp("begin_doc_expl"); RYML_ASSERT_VISIT_CB_(m_stack.m_callbacks, m_tree->root_id() == m_curr->node_id, m_tree, m_curr->node_id); if(m_tree->is_stream(m_tree->root_id())) //if(_should_push_on_begin_doc()) { _c4dbgp("push!"); _push(); } else { _c4dbgp("ensure stream"); _set_root_as_stream(); const id_type root = m_tree->root_id(); const id_type first = m_tree->first_child(root); RYML_ASSERT_VISIT_CB_(m_stack.m_callbacks, m_tree->is_stream(root), m_tree, root); RYML_ASSERT_VISIT_CB_(m_stack.m_callbacks, m_tree->num_children(root) == 1u, m_tree, root); if(m_tree->is_container(first) || m_tree->is_val(first)) { _c4dbgp("push!"); _push(); #ifdef RYML_WITH_COMMENTS m_tree->_p(root)->m_first_comment = NONE; m_tree->_p(root)->m_last_comment = NONE; #endif } else { _c4dbgp("tweak"); _push(); _remove_speculative(); m_curr->node_id = m_tree->last_child(root); m_curr->tr_data = m_tree->_p(m_curr->node_id); } } ryml_enable_(DOC); m_curr_doc = m_curr->node_id; } /** explicit doc end, with ... */ void end_doc_expl() { _c4dbgp("end_doc_expl"); m_curr_doc = m_tree->size(); _remove_speculative(); if(_stack_should_pop_on_end_doc()) { _c4dbgp("pop!"); _pop(); } } /** @} */ public: /** @name YAML map events */ /** @{ */ C4_NORETURN void begin_map_key_flow() { RYML_ERR_PARSE_CB_(m_stack.m_callbacks, m_curr->pos, "ryml trees cannot handle containers as keys"); } C4_NORETURN void begin_map_key_block() { RYML_ERR_PARSE_CB_(m_stack.m_callbacks, m_curr->pos, "ryml trees cannot handle containers as keys"); } void begin_map_val_flow() { _c4dbgpf("node[{}]: begin_map_val_flow", m_curr->node_id); RYML_CHECK_BASIC_CB_(m_stack.m_callbacks, !ryml_hasany_(VAL)); ryml_enable_(MAP|FLOW_SL); _save_loc(); _push(); } void begin_map_val_block() { _c4dbgpf("node[{}]: begin_map_val_block", m_curr->node_id); RYML_CHECK_BASIC_CB_(m_stack.m_callbacks, !ryml_hasany_(VAL)); ryml_enable_(MAP|BLOCK); _save_loc(); _push(); } void end_map_block() { _c4dbgpf("node[{}]: end_map_block", m_parent->node_id, m_parent->pos.line, m_curr->pos.line); _pop(); } void end_map_flow(bool multiline, type_bits multiline_style=FLOW_ML1) { _c4dbgpf("node[{}]: end_map. multiline={} startline={} endline={}", m_parent->node_id, multiline, m_parent->pos.line, m_curr->pos.line); _pop(); if(multiline) { ryml_disable_(FLOW_SL); enable_(multiline_style); } } /** @} */ public: /** @name YAML seq events */ /** @{ */ C4_NORETURN void begin_seq_key_flow() { RYML_ERR_PARSE_CB_(m_stack.m_callbacks, m_curr->pos, "ryml trees cannot handle containers as keys"); } C4_NORETURN void begin_seq_key_block() { RYML_ERR_PARSE_CB_(m_stack.m_callbacks, m_curr->pos, "ryml trees cannot handle containers as keys"); } void begin_seq_val_flow() { _c4dbgpf("node[{}]: begin_seq_val_flow", m_curr->node_id); RYML_CHECK_BASIC_CB_(m_stack.m_callbacks, !ryml_hasany_(VAL)); ryml_enable_(SEQ|FLOW_SL); _save_loc(); _push(); } void begin_seq_val_block() { _c4dbgpf("node[{}]: begin_seq_val_block", m_curr->node_id); RYML_CHECK_BASIC_CB_(m_stack.m_callbacks, !ryml_hasany_(VAL)); ryml_enable_(SEQ|BLOCK); _save_loc(); _push(); } void end_seq_block() { _c4dbgpf("node[{}]: end_seq_block", m_parent->node_id, m_parent->pos.line, m_curr->pos.line); _pop(); } void end_seq_flow(bool multiline, type_bits multiline_style=FLOW_ML1) { _c4dbgpf("node[{}]: end_seq. multiline={} startline={} endline={}", m_parent->node_id, multiline, m_parent->pos.line, m_curr->pos.line); _pop(); if(multiline) { ryml_disable_(FLOW_SL); enable_(multiline_style); } } /** @} */ public: /** @name YAML structure events */ /** @{ */ void add_sibling() { #if defined(__GNUC__) && (__GNUC__ >= 6) C4_SUPPRESS_WARNING_GCC_WITH_PUSH("-Wnull-dereference") #endif RYML_ASSERT_BASIC_CB_(m_stack.m_callbacks, m_tree); RYML_ASSERT_BASIC_CB_(m_stack.m_callbacks, m_parent); RYML_ASSERT_VISIT_CB_(m_stack.m_callbacks, m_tree->has_children(m_parent->node_id), m_tree, m_parent->node_id); NodeData const* const prev = m_tree->m_buf; // watchout against relocation of the tree nodes _set_state_(m_curr, m_tree->_append_child__unprotected(m_parent->node_id)); if(prev != m_tree->m_buf) _refresh_after_relocation(); _c4dbgpf("node[{}]: added sibling={} prev={}", m_parent->node_id, m_curr->node_id, m_tree->prev_sibling(m_curr->node_id)); #if defined(__GNUC__) && (__GNUC__ >= 6) C4_SUPPRESS_WARNING_GCC_POP #endif } /** reset the previous val as the first key of a new map, with flow style. * * See the documentation for @ref doc_event_handlers, which has * important notes about this event. */ void actually_val_is_first_key_of_new_map_flow() { if C4_UNLIKELY(m_tree->is_container(m_curr->node_id)) RYML_ERR_PARSE_CB_(m_stack.m_callbacks, m_curr->pos, "ryml trees cannot handle containers as keys"); RYML_ASSERT_BASIC_CB_(m_stack.m_callbacks, m_parent); RYML_ASSERT_VISIT_CB_(m_stack.m_callbacks, m_tree->is_seq(m_parent->node_id), m_tree, m_parent->node_id); RYML_ASSERT_VISIT_CB_(m_stack.m_callbacks, !m_tree->is_container(m_curr->node_id), m_tree, m_curr->node_id); RYML_ASSERT_VISIT_CB_(m_stack.m_callbacks, !m_tree->has_key(m_curr->node_id), m_tree, m_curr->node_id); const NodeData tmp = _val2key_(*m_curr->tr_data); ryml_disable_(VALMASK_|VAL_STYLE|VALNIL); m_curr->tr_data->m_val = {}; begin_map_val_flow(); m_curr->tr_data->m_type = tmp.m_type; m_curr->tr_data->m_key = tmp.m_key; } /** like its flow counterpart, but this function can only be * called after the end of a flow-val at root or doc level. * * See the documentation for @ref doc_event_handlers, which has * important notes about this event. */ C4_NORETURN void actually_val_is_first_key_of_new_map_block() { RYML_ERR_PARSE_CB_(m_stack.m_callbacks, m_curr->pos, "ryml trees cannot handle containers as keys"); } /** @} */ public: /** @name YAML scalar events */ /** @{ */ C4_ALWAYS_INLINE void set_key_scalar_plain_empty() noexcept { _c4dbgpf("node[{}]: set key scalar plain as empty", m_curr->node_id); m_curr->tr_data->m_key.scalar = {}; ryml_enable_(KEY|KEY_PLAIN|KEYNIL); } C4_ALWAYS_INLINE void set_val_scalar_plain_empty() noexcept { _c4dbgpf("node[{}]: set val scalar plain as empty", m_curr->node_id); m_curr->tr_data->m_val.scalar = {}; ryml_enable_(VAL|VAL_PLAIN|VALNIL); } C4_ALWAYS_INLINE void set_key_scalar_plain(csubstr scalar) noexcept { _c4dbgpf("node[{}]: set key scalar plain: [{}]~~~{}~~~", m_curr->node_id, scalar.len, scalar); m_curr->tr_data->m_key.scalar = scalar; ryml_enable_(KEY|KEY_PLAIN); } C4_ALWAYS_INLINE void set_val_scalar_plain(csubstr scalar) noexcept { _c4dbgpf("node[{}]: set val scalar plain: [{}]~~~{}~~~", m_curr->node_id, scalar.len, scalar); m_curr->tr_data->m_val.scalar = scalar; ryml_enable_(VAL|VAL_PLAIN); } C4_ALWAYS_INLINE void set_key_scalar_dquoted(csubstr scalar) noexcept { _c4dbgpf("node[{}]: set key scalar dquot: [{}]~~~{}~~~", m_curr->node_id, scalar.len, scalar); m_curr->tr_data->m_key.scalar = scalar; ryml_enable_(KEY|KEY_DQUO); } C4_ALWAYS_INLINE void set_val_scalar_dquoted(csubstr scalar) noexcept { _c4dbgpf("node[{}]: set val scalar dquot: [{}]~~~{}~~~", m_curr->node_id, scalar.len, scalar); m_curr->tr_data->m_val.scalar = scalar; ryml_enable_(VAL|VAL_DQUO); } C4_ALWAYS_INLINE void set_key_scalar_squoted(csubstr scalar) noexcept { _c4dbgpf("node[{}]: set key scalar squot: [{}]~~~{}~~~", m_curr->node_id, scalar.len, scalar); m_curr->tr_data->m_key.scalar = scalar; ryml_enable_(KEY|KEY_SQUO); } C4_ALWAYS_INLINE void set_val_scalar_squoted(csubstr scalar) noexcept { _c4dbgpf("node[{}]: set val scalar squot: [{}]~~~{}~~~", m_curr->node_id, scalar.len, scalar); m_curr->tr_data->m_val.scalar = scalar; ryml_enable_(VAL|VAL_SQUO); } C4_ALWAYS_INLINE void set_key_scalar_literal(csubstr scalar) noexcept { _c4dbgpf("node[{}]: set key scalar literal: [{}]~~~{}~~~", m_curr->node_id, scalar.len, scalar); m_curr->tr_data->m_key.scalar = scalar; ryml_enable_(KEY|KEY_LITERAL); } C4_ALWAYS_INLINE void set_val_scalar_literal(csubstr scalar) noexcept { _c4dbgpf("node[{}]: set val scalar literal: [{}]~~~{}~~~", m_curr->node_id, scalar.len, scalar); m_curr->tr_data->m_val.scalar = scalar; ryml_enable_(VAL|VAL_LITERAL); } C4_ALWAYS_INLINE void set_key_scalar_folded(csubstr scalar) noexcept { _c4dbgpf("node[{}]: set key scalar folded: [{}]~~~{}~~~", m_curr->node_id, scalar.len, scalar); m_curr->tr_data->m_key.scalar = scalar; ryml_enable_(KEY|KEY_FOLDED); } C4_ALWAYS_INLINE void set_val_scalar_folded(csubstr scalar) noexcept { _c4dbgpf("node[{}]: set val scalar folded: [{}]~~~{}~~~", m_curr->node_id, scalar.len, scalar); m_curr->tr_data->m_val.scalar = scalar; ryml_enable_(VAL|VAL_FOLDED); } C4_ALWAYS_INLINE void mark_key_scalar_unfiltered() noexcept { ryml_enable_(KEY_UNFILT); } C4_ALWAYS_INLINE void mark_val_scalar_unfiltered() noexcept { ryml_enable_(VAL_UNFILT); } /** @} */ public: /** @name YAML anchor/reference events */ /** @{ */ void set_key_anchor(csubstr anchor) { _c4dbgpf("node[{}]: set key anchor: [{}]~~~{}~~~", m_curr->node_id, anchor.len, anchor); RYML_ASSERT_BASIC_CB_(m_stack.m_callbacks, m_tree); RYML_ASSERT_BASIC_CB_(m_stack.m_callbacks, !ryml_hasany_(KEYREF)); RYML_ASSERT_PARSE_CB_(m_tree->callbacks(), !anchor.begins_with('&'), m_curr->pos); ryml_enable_(KEYANCH); m_curr->tr_data->m_key.anchor = anchor; } void set_val_anchor(csubstr anchor) { _c4dbgpf("node[{}]: set val anchor: [{}]~~~{}~~~", m_curr->node_id, anchor.len, anchor); RYML_ASSERT_BASIC_CB_(m_stack.m_callbacks, m_tree); RYML_ASSERT_BASIC_CB_(m_stack.m_callbacks, !ryml_hasany_(VALREF)); RYML_ASSERT_PARSE_CB_(m_tree->callbacks(), !anchor.begins_with('&'), m_curr->pos); ryml_enable_(VALANCH); m_curr->tr_data->m_val.anchor = anchor; } void set_key_ref(csubstr ref) { _c4dbgpf("node[{}]: set key ref: [{}]~~~{}~~~", m_curr->node_id, ref.len, ref); RYML_ASSERT_PARSE_CB_(m_stack.m_callbacks, ref.begins_with('*'), m_curr->pos); RYML_ASSERT_PARSE_CB_(m_stack.m_callbacks, !ryml_hasany_(KEYANCH), m_curr->pos); ryml_enable_(KEY|KEYREF); m_curr->tr_data->m_key.anchor = ref.sub(1); m_curr->tr_data->m_key.scalar = ref; } void set_val_ref(csubstr ref) { _c4dbgpf("node[{}]: set val ref: [{}]~~~{}~~~", m_curr->node_id, ref.len, ref); RYML_ASSERT_PARSE_CB_(m_stack.m_callbacks, ref.begins_with('*'), m_curr->pos); RYML_ASSERT_PARSE_CB_(m_stack.m_callbacks, !ryml_hasany_(VALANCH), m_curr->pos); ryml_enable_(VAL|VALREF); m_curr->tr_data->m_val.anchor = ref.sub(1); m_curr->tr_data->m_val.scalar = ref; } /** @} */ public: /** @name YAML tag events */ /** @{ */ void set_key_tag(csubstr tag) { _c4dbgpf("node[{}]: set key tag: [{}]~~~{}~~~", m_curr->node_id, tag.len, tag); ryml_enable_(KEYTAG); m_curr->tr_data->m_key.tag = tag; } void set_val_tag(csubstr tag) { _c4dbgpf("node[{}]: set val tag: [{}]~~~{}~~~", m_curr->node_id, tag.len, tag); ryml_enable_(VALTAG); m_curr->tr_data->m_val.tag = tag; } /** @} */ public: /** @name YAML directive events */ /** @{ */ void add_directive_yaml(csubstr yaml_version) // NOLINT(readability-convert-member-functions-to-static) { _c4dbgpf("%YAML directive! version={}", yaml_version); (void)yaml_version; } void add_directive_tag(csubstr handle, csubstr prefix) { _c4dbgpf("%TAG directive! handle={} prefix={} id={}", handle, prefix, m_curr_doc); if C4_UNLIKELY(!m_tree->m_tag_directives.add(handle, prefix, m_curr_doc)) RYML_ERR_PARSE_CB_(m_stack.m_callbacks, m_curr->pos, "too many %TAG directives"); } /** @} */ public: /** @name arena functions */ /** @{ */ substr arena() { RYML_ASSERT_BASIC_CB_(m_stack.m_callbacks, m_tree); return m_tree->m_arena.first(m_tree->m_arena_pos); } substr arena_rem() { RYML_ASSERT_BASIC_CB_(m_stack.m_callbacks, m_tree); return m_tree->m_arena.sub(m_tree->m_arena_pos); } substr alloc_arena(size_t len) // NOLINT(readability-make-member-function-const) { return m_tree->alloc_arena(len); } /** @} */ public: /** @cond dev */ void _reset_parser_state(state* st, id_type parse_root, id_type node) { RYML_ASSERT_BASIC_CB_(m_stack.m_callbacks, m_tree); _set_state_(st, node); const NodeType type = m_tree->type(node); #ifdef RYML_DBG char flagbuf[80]; _c4dbgpf("resetting state: initial flags={}", detail::_parser_flags_to_str(flagbuf, st->flags)); #endif if(type == NOTYPE) { _c4dbgpf("node[{}] is notype", node); if(m_tree->is_root(parse_root)) { _c4dbgpf("node[{}] is root", node); st->flags |= RUNK|RTOP; } else { _c4dbgpf("node[{}] is not root. setting USTY", node); st->flags |= USTY; } } else if(type.is_map()) { _c4dbgpf("node[{}] is map", node); st->flags |= RMAP|USTY; } else if(type.is_seq()) { _c4dbgpf("node[{}] is map", node); st->flags |= RSEQ|USTY; } else if(type.has_key()) { _c4dbgpf("node[{}] has key. setting USTY", node); st->flags |= USTY; } else { RYML_ERR_VISIT_CB_(m_tree->callbacks(), m_tree, node, "cannot append to node"); // LCOV_EXCL_LINE } if(type.is_doc()) { _c4dbgpf("node[{}] is doc", node); st->flags |= RDOC; } #ifdef RYML_DBG _c4dbgpf("resetting state: final flags={}", detail::_parser_flags_to_str(flagbuf, st->flags)); #endif } /** push a new parent, add a child to the new parent, and set the * child as the current node */ void _push() { _stack_push(); NodeData const* prev = m_tree->m_buf; // watch out against relocation of the tree nodes m_curr->node_id = m_tree->_append_child__unprotected(m_parent->node_id); m_curr->tr_data = m_tree->_p(m_curr->node_id); if(prev != m_tree->m_buf) _refresh_after_relocation(); _c4dbgpf("pushed! level={}. top is now node={} (parent={})", m_curr->level, m_curr->node_id, m_parent ? m_parent->node_id : NONE); } /** end the current scope */ void _pop() { _remove_speculative_with_parent(); _stack_pop(); } public: C4_ALWAYS_INLINE void enable_(type_bits bits) noexcept { m_curr->tr_data->m_type.m_bits |= bits; } template C4_HOT C4_ALWAYS_INLINE void enable_() noexcept { m_curr->tr_data->m_type.m_bits |= bits; } template C4_HOT C4_ALWAYS_INLINE void disable_() noexcept { m_curr->tr_data->m_type.m_bits &= ~bits; } template C4_HOT C4_ALWAYS_INLINE bool has_any_() const noexcept { return (m_curr->tr_data->m_type.m_bits & bits) != 0; } public: C4_ALWAYS_INLINE void _set_state_(state *C4_RESTRICT s, id_type id) const noexcept { s->node_id = id; s->tr_data = m_tree->_p(id); } void _refresh_after_relocation() { _c4dbgp("tree: refreshing stack data after tree data relocation"); for(auto &st : m_stack) st.tr_data = m_tree->_p(st.node_id); } void _set_root_as_stream() { _c4dbgp("set root as stream"); RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), m_tree->root_id() == 0u, m_tree, m_tree->root_id()); RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), m_curr->node_id == 0u, m_tree, m_curr->node_id); m_tree->set_root_as_stream(); RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), m_tree->is_stream(m_tree->root_id()), m_tree, m_tree->root_id()); RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), m_tree->has_children(m_tree->root_id()), m_tree, m_tree->root_id()); RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), m_tree->is_doc(m_tree->first_child(m_tree->root_id())), m_tree, m_tree->root_id()); _set_state_(m_curr, m_tree->root_id()); } static NodeData _val2key_(NodeData const& C4_RESTRICT d) noexcept { NodeData r = d; r.m_key = d.m_val; r.m_val = {}; r.m_type = d.m_type; static_assert((VALMASK_ >> 1u) == KEYMASK_, "required for this function to work"); static_assert((VAL_STYLE >> 1u) == KEY_STYLE, "required for this function to work"); r.m_type.m_bits = ((d.m_type.m_bits & (VALMASK_|VAL_STYLE)) >> 1u); r.m_type.m_bits = (r.m_type.m_bits & ~(VALMASK_|VAL_STYLE)); r.m_type.m_bits = (r.m_type.m_bits | KEY); if(d.m_type.m_bits & VALNIL) r.m_type.m_bits = (r.m_type.m_bits | KEYNIL); return r; } void _remove_speculative() { RYML_ASSERT_BASIC_CB_(m_stack.m_callbacks, m_tree); RYML_ASSERT_BASIC_CB_(m_tree->callbacks(), !m_tree->empty()); const id_type last_added = m_tree->size() - 1; const NodeData *C4_RESTRICT d = m_tree->_p(last_added); if(d->m_parent != NONE && d->m_type == NOTYPE) { _c4dbgpf("remove speculative: currparent={} node={} parent(node)={}", m_parent->node_id, last_added, d->m_parent); m_tree->remove(last_added); --m_curr->node_id; } } void _remove_speculative_with_parent() { RYML_ASSERT_BASIC_CB_(m_stack.m_callbacks, m_tree); RYML_ASSERT_BASIC_CB_(m_tree->callbacks(), !m_tree->empty()); const id_type last_added = m_tree->size() - 1; RYML_ASSERT_VISIT_CB_(m_tree->callbacks(), m_tree->has_parent(last_added), m_tree, last_added); if(m_tree->_p(last_added)->m_type == NOTYPE) { _c4dbgpf("remove speculative node with parent. parent={} node={} parent(node)={}", m_parent->node_id, last_added, m_tree->parent(last_added)); m_tree->remove(last_added); --m_curr->node_id; } } C4_ALWAYS_INLINE void _save_loc() { RYML_ASSERT_BASIC_CB_(m_stack.m_callbacks, m_tree); RYML_ASSERT_BASIC_CB_(m_tree->callbacks(), m_tree->_p(m_curr->node_id)->m_val.scalar.len == 0); m_tree->_p(m_curr->node_id)->m_val.scalar.str = m_curr->line_contents.rem.str; } #undef ryml_enable_ #undef ryml_disable_ #undef ryml_has_any_ /** @endcond */ }; /** @} */ } // namespace yml } // namespace c4 // NOLINTEND(hicpp-signed-bitwise) C4_SUPPRESS_WARNING_MSVC_POP C4_SUPPRESS_WARNING_GCC_POP #endif /* C4_YML_EVENT_HANDLER_TREE_HPP_ */ // (end src/c4/yml/event_handler_tree.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/parse_engine.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_PARSE_ENGINE_HPP_ #define C4_YML_PARSE_ENGINE_HPP_ #ifndef C4_YML_PARSER_STATE_HPP_ //#include "c4/yml/parser_state.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/parser_state.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_PARSE_OPTIONS_HPP_ //#include "c4/yml/parse_options.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/parse_options.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_FWD_HPP_ //#include "c4/yml/fwd.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/fwd.hpp must have been amalgamated before this point" #endif #if defined(_MSC_VER) # pragma warning(push) # pragma warning(disable: 4251/*needs to have dll-interface to be used by clients of struct*/) #endif // NOLINTBEGIN(hicpp-signed-bitwise) namespace c4 { namespace yml { /** @addtogroup doc_parse * @{ */ /** @addtogroup doc_event_handlers Event Handlers * * @brief rapidyaml implements its parsing logic with a two-level * model, where a @ref ParseEngine object reads through the YAML * source, and dispatches events to an EventHandler bound to the @ref * ParseEngine. Because @ref ParseEngine is templated on the event * handler, the binding uses static polymorphism, without any virtual * functions. The actual handler object can be changed at run time, * (but of course needs to be the type of the template parameter). * This is thus a very efficient architecture, and further enables the * user to provide his own custom handler if he wishes to bypass the * rapidyaml @ref Tree. * * The following handlers are implemented in this project: * * - @ref EventHandlerTree is the handler responsible for creating the * ryml @ref Tree . This is part of the library. * * - Extra handlers (not part of the library, but provided as extra classes): * * - @ref extra::EventHandlerInts parses YAML into a contiguous * integer array representing the YAML structure. * - [play.yaml.com](https://play.yaml.com/) * - [matrix.yaml.info/](https://matrix.yaml.info/) * - the CI of this project. * * * ### Event model * * The event model used by the parse engine and event handlers follows * very closely the event model in the [YAML test * suite](https://github.com/yaml/yaml-test-suite). * * Consider for example this YAML, * ```yaml * {foo: bar,foo2: bar2} * ``` * which would produce these events in the test-suite parlance: * ``` * +STR * +DOC * +MAP {} * =VAL :foo * =VAL :bar * =VAL :foo2 * =VAL :bar2 * -MAP * -DOC * -STR * ``` * * For reference, the @ref ParseEngine object will produce this * sequence of calls to its bound EventHandler: * ```cpp * handler.begin_stream(); * handler.begin_doc(); * handler.begin_map_val_flow(); * handler.set_key_scalar_plain("foo"); * handler.set_val_scalar_plain("bar"); * handler.add_sibling(); * handler.set_key_scalar_plain("foo2"); * handler.set_val_scalar_plain("bar2"); * handler.end_map(); * handler.end_doc(); * handler.end_stream(); * ``` * * For many other examples of all areas of YAML and how ryml's parse * model corresponds to the YAML standard model, refer to the [unit * tests for the parse * engine](https://github.com/biojppm/rapidyaml/tree/master/test/test_parse_engine.cpp). * * * ### Special events * * Most of the parsing events adopted by rapidyaml in its event model * are fairly obvious, but there are two less-obvious events requiring * some explanation. * * These events exist to make it easier to parse some special YAML * cases. They are called by the parser when a just-handled * value/container is actually the first key of a new map: * * - `actually_val_is_first_key_of_new_map_flow()` (@ref EventHandlerTree::actually_val_is_first_key_of_new_map_flow() "see implementation in EventHandlerTree" / @ref extra::EventHandlerInts::actually_val_is_first_key_of_new_map_flow() "see implementation in EventHandlerInts") * - `actually_val_is_first_key_of_new_map_block()` (@ref EventHandlerTree::actually_val_is_first_key_of_new_map_block() "see implementation in EventHandlerTree" / @ref extra::EventHandlerInts::actually_val_is_first_key_of_new_map_block() "see implementation in EventHandlerInts") * * For example, consider an implicit map inside a seq: `[a: b, c: * d]` which is parsed as `[{a: b}, {c: d}]`. The standard event * sequence for this YAML would be the following: * ```cpp * handler.begin_seq_val_flow(); * handler.begin_map_val_flow(); * handler.set_key_scalar_plain("a"); * handler.set_val_scalar_plain("b"); * handler.end_map(); * handler.add_sibling(); * handler.begin_map_val_flow(); * handler.set_key_scalar_plain("c"); * handler.set_val_scalar_plain("d"); * handler.end_map(); * handler.end_seq(); * ``` * The problem with this event sequence is that it forces the * parser to delay setting the val scalar (in this case "a" and * "c") until it knows whether the scalar is a key or a val. This * would require the parser to store the scalar until this * time. For instance, in the example above, the parser should * delay setting "a" and "c", because they are in fact keys and * not vals. Until then, the parser would have to store "a" and * "c" in its internal state. The downside is that this complexity * cost would apply even if there is no implicit map -- every val * in a seq would have to be delayed until one of the * disambiguating subsequent tokens `,-]:` is found. * By calling this function, the parser can avoid this complexity, * by preemptively setting the scalar as a val. Then a call to * this function will create the map and rearrange the scalar as * key. Now the cost applies only once: when a seqimap starts. So * the following (easier and cheaper) event sequence below has the * same effect as the event sequence above: * ```cpp * handler.begin_seq_val_flow(); * handler.set_val_scalar_plain("notmap"); * handler.set_val_scalar_plain("a"); // preemptively set "a" as val! * handler.actually_as_new_map_key(); // create a map, move the "a" val as the key of the first child of the new map * handler.set_val_scalar_plain("b"); // now "a" is a key and "b" the val * handler.end_map(); * handler.set_val_scalar_plain("c"); // "c" also as val! * handler.actually_as_block_flow(); // likewise * handler.set_val_scalar_plain("d"); // now "c" is a key and "b" the val * handler.end_map(); * handler.end_seq(); * ``` * This also applies to container keys (although ryml's tree * cannot accomodate these): the parser can preemptively set a * container as a val, and call this event to turn that container * into a key. For example, consider this yaml: * ```yaml * [aa, bb]: [cc, dd] * # ^ ^ ^ * # | | | * # (2) (1) (3) <- event sequence * ``` * The standard event sequence for this YAML would be the * following: * ```cpp * handler.begin_map_val_block(); // (1) * handler.begin_seq_key_flow(); // (2) * handler.set_val_scalar_plain("aa"); * handler.add_sibling(); * handler.set_val_scalar_plain("bb"); * handler.end_seq(); * handler.begin_seq_val_flow(); // (3) * handler.set_val_scalar_plain("cc"); * handler.add_sibling(); * handler.set_val_scalar_plain("dd"); * handler.end_seq(); * handler.end_map(); * ``` * The problem with the sequence above is that, reading from * left-to-right, the parser can only detect the proper calls at * (1) and (2) once it reaches (1) in the YAML source. So, the * parser would have to buffer the entire event sequence starting * from the beginning until it reaches (1). Using this function, * the parser can do instead: * ```cpp * handler.begin_seq_val_flow(); // (2) -- preemptively as val! * handler.set_val_scalar_plain("aa"); * handler.add_sibling(); * handler.set_val_scalar_plain("bb"); * handler.end_seq(); * handler.actually_as_new_map_key(); // (1) -- adjust when finding that the prev val was actually a key. * handler.begin_seq_val_flow(); // (3) -- go on as before * handler.set_val_scalar_plain("cc"); * handler.add_sibling(); * handler.set_val_scalar_plain("dd"); * handler.end_seq(); * handler.end_map(); * ``` * @{ * @} */ /** Quickly inspect the source to estimate the number of nodes the * resulting tree is likely to have. If a tree is empty before * parsing, considerable time will be spent growing it, so calling * this to reserve the tree size prior to parsing is likely to * result in a time gain. We encourage using this method before * parsing, but as always measure its impact in performance to * obtain a good trade-off. * * @note since this method is meant for optimizing performance, it * is approximate. The result may be actually smaller than the * resulting number of nodes, notably if the YAML uses implicit * maps as flow seq members as in `[these: are, individual: * maps]`. */ RYML_EXPORT id_type estimate_tree_capacity(csubstr src); // NOLINT(readability-redundant-declaration) /** @cond dev */ struct FilterResult; struct FilterResultExtending; typedef enum BlockChomp_ { // NOLINT CHOMP_CLIP, //!< single newline at end (default) CHOMP_STRIP, //!< no newline at end (-) CHOMP_KEEP //!< all newlines from end (+) } BlockChomp_e; struct ScannedBlock { substr scalar; size_t indentation; BlockChomp_e chomp; }; struct ScannedScalar { substr scalar; bool needs_filter; }; /** store pending tag or anchor/ref annotations */ struct Annotation { struct Entry { csubstr str; size_t indentation; size_t line; csubstr orig; }; Entry annotations[2]; uint8_t num_entries; }; /** @endcond */ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** This is the main driver of parsing logic: it scans the YAML or * JSON source for tokens, and emits the appropriate sequence of * parsing events to its event handler. The parse engine itself has no * special limitations, and *can* accomodate containers as keys; it is the * event handler may introduce additional constraints. * * There are two implemented handlers (see @ref doc_event_handlers, * which has important notes about the event model): * * - @ref EventHandlerTree (see @ref doc_event_handlers_tree) is the * handler responsible for creating the ryml @ref Tree * * - @ref extra::EventHandlerInts (see @ref doc_event_handlers_ints) * is the handler responsible for emitting integer-coded events. It * is intended for implementing fully-conformant parsing in other * programming languages (integration is currently under work for * [YamlScript](https://github.com/yaml/yamlscript) and * [go-yaml](https://github.com/yaml/go-yaml/)). It is not part of * the library and is not installed. * */ template class ParseEngine { public: using handler_type = EventHandler; public: /** @name construction and assignment */ /** @{ */ ParseEngine(EventHandler *evt_handler, ParserOptions const& opts={}); ~ParseEngine() noexcept; ParseEngine(ParseEngine &&) noexcept; ParseEngine(ParseEngine const&); ParseEngine& operator=(ParseEngine &&) noexcept; ParseEngine& operator=(ParseEngine const&); /** @} */ public: /** @name modifiers */ /** @{ */ /** Reserve a certain capacity for the parsing stack. * This should be larger than the expected depth of the parsed * YAML tree. * * The parsing stack is the only (potential) heap memory used * directly by the parser. * * If the requested capacity is below the default * stack size of 16, the memory is used directly in the parser * object; otherwise it will be allocated from the heap. * * @note this reserves memory only for the parser itself; all the * allocations for the parsed tree will go through the tree's * allocator (when different). * * @note for maximum efficiency, the tree and the arena can (and * should) also be reserved. */ void reserve_stack(id_type capacity) { RYML_ASSERT_BASIC_(m_evt_handler); m_evt_handler->m_stack.reserve(capacity); } /** Reserve a certain capacity for the array used to track node * locations in the source buffer. */ void reserve_locations(size_t num_source_lines) { _resize_locations(num_source_lines); } /** @} */ public: /** @name getters */ /** @{ */ /** Get the options used to build this parser object. */ ParserOptions const& options() const { return m_options; } /** Get the current callbacks in the parser. */ Callbacks const& callbacks() const { RYML_ASSERT_BASIC_(m_evt_handler); return m_evt_handler->m_stack.m_callbacks; } /** Get the name of the latest file parsed by this object. */ csubstr filename() const { return m_evt_handler->m_curr ? m_evt_handler->m_curr->pos.name : csubstr{}; } /** Get the latest YAML buffer parsed by this object. */ csubstr source() const { return m_evt_handler ? m_evt_handler->m_src : csubstr{}; } /** Get the encoding of the latest YAML buffer parsed by this object. * If no encoding was specified, UTF8 is assumed as per the YAML standard. */ Encoding_e encoding() const { return m_encoding != NOBOM ? m_encoding : UTF8; } id_type stack_capacity() const { RYML_ASSERT_BASIC_(m_evt_handler); return m_evt_handler->m_stack.capacity(); } size_t locations_capacity() const { return m_newline_offsets_capacity; } /** @} */ public: /** @name parse methods */ /** @{ */ /** parse YAML in place, emitting events to the current handler */ void parse_in_place_ev(csubstr filename, substr src); /** parse JSON in place, emitting events to the current handler */ void parse_json_in_place_ev(csubstr filename, substr src); /** @} */ public: /** @name locations */ /** @{ */ /** Get the string starting at a particular location, to the end * of the parsed source buffer. */ csubstr location_contents(Location const& loc) const; /** Given a pointer to a buffer position, get the location. * @param[in] val must be pointing to somewhere in the source * buffer that was last parsed by this object. */ Location val_location(const char *val) const; /** @} */ public: /** @name scalar filtering */ /** @{*/ /** filter a plain scalar */ FilterResult filter_scalar_plain(csubstr scalar, substr dst, size_t indentation); /** filter a plain scalar in place */ FilterResult filter_scalar_plain_in_place(substr scalar, size_t cap, size_t indentation); /** filter a single-quoted scalar */ FilterResult filter_scalar_squoted(csubstr scalar, substr dst); /** filter a single-quoted scalar in place */ FilterResult filter_scalar_squoted_in_place(substr scalar, size_t cap); /** filter a double-quoted scalar */ FilterResult filter_scalar_dquoted(csubstr scalar, substr dst); /** filter a double-quoted scalar in place */ FilterResultExtending filter_scalar_dquoted_in_place(substr scalar, size_t cap); /** filter a block-literal scalar */ FilterResult filter_scalar_block_literal(csubstr scalar, substr dst, size_t indentation, BlockChomp_e chomp); /** filter a block-literal scalar in place */ FilterResult filter_scalar_block_literal_in_place(substr scalar, size_t cap, size_t indentation, BlockChomp_e chomp); /** filter a block-folded scalar */ FilterResult filter_scalar_block_folded(csubstr scalar, substr dst, size_t indentation, BlockChomp_e chomp); /** filter a block-folded scalar in place */ FilterResult filter_scalar_block_folded_in_place(substr scalar, size_t cap, size_t indentation, BlockChomp_e chomp); /** @} */ private: bool _is_doc_begin(csubstr s); bool _is_doc_end(csubstr s); bool _scan_scalar_plain_blck(ScannedScalar *C4_RESTRICT sc, size_t indentation); bool _scan_scalar_plain_seq_flow(ScannedScalar *C4_RESTRICT sc); bool _scan_scalar_plain_seq_blck(ScannedScalar *C4_RESTRICT sc); bool _scan_scalar_plain_map_flow(ScannedScalar *C4_RESTRICT sc); bool _scan_scalar_plain_map_blck(ScannedScalar *C4_RESTRICT sc); bool _scan_scalar_map_json(ScannedScalar *C4_RESTRICT sc); bool _scan_scalar_seq_json(ScannedScalar *C4_RESTRICT sc); bool _scan_scalar_plain_unk(ScannedScalar *C4_RESTRICT sc); bool _is_valid_start_scalar_plain_flow(csubstr s); bool _is_valid_start_scalar_plain_flow_check_block_token(csubstr s); bool _is_valid_start_scalar_plain_flow_check_qmrk(csubstr s); bool _scan_scalar_plain_handle_newline(csubstr s, size_t offs); void _check_valid_newline_in_quoted_scalar(); ScannedScalar _scan_scalar_squot(); ScannedScalar _scan_scalar_dquot(); void _scan_block(ScannedBlock *C4_RESTRICT sb, size_t indref); csubstr _scan_anchor(); csubstr _scan_ref_seq(); csubstr _scan_ref_map(); csubstr _scan_tag(); csubstr _scan_tag(csubstr *orig); public: // exposed for testing /** @cond dev */ csubstr _filter_scalar_plain(substr s, size_t indentation); csubstr _filter_scalar_squot(substr s); csubstr _filter_scalar_dquot(substr s); csubstr _filter_scalar_literal(substr s, size_t indentation, BlockChomp_e chomp); csubstr _filter_scalar_folded(substr s, size_t indentation, BlockChomp_e chomp); csubstr _move_scalar_left_and_add_newline(substr s); csubstr _maybe_filter_key_scalar_plain(ScannedScalar const& sc, size_t indendation); csubstr _maybe_filter_val_scalar_plain(ScannedScalar const& sc, size_t indendation); csubstr _maybe_filter_key_scalar_squot(ScannedScalar const& sc); csubstr _maybe_filter_val_scalar_squot(ScannedScalar const& sc); csubstr _maybe_filter_key_scalar_dquot(ScannedScalar const& sc); csubstr _maybe_filter_val_scalar_dquot(ScannedScalar const& sc); csubstr _maybe_filter_key_scalar_literal(ScannedBlock const& sb); csubstr _maybe_filter_val_scalar_literal(ScannedBlock const& sb); csubstr _maybe_filter_key_scalar_folded(ScannedBlock const& sb); csubstr _maybe_filter_val_scalar_folded(ScannedBlock const& sb); /** @endcond */ private: void _handle_map_block(); bool _handle_map_block_qmrk(); bool _handle_map_block_rkcl(); void _handle_seq_block(); void _handle_map_flow(); void _handle_seq_flow(); void _handle_seq_imap(); void _handle_map_json(); void _handle_seq_json(); void _handle_unk(); void _handle_unk_json(); void _handle_usty(); void _handle_flow_skip_whitespace(); void _handle_flow_line_beginning(); size_t _handle_unk_check_left_tokens(size_t realindent, size_t col, bool skip_annotations=true); void _handle_unk_get_first_non_pending_token_pos(csubstr s, size_t *indent, size_t *first_non_token_pos); void _handle_unk_begin_doc(); size_t _handle_block_skip_leading_whitespace(); C4_ALWAYS_INLINE size_t _handle_block_get_whitespace_mark() const noexcept { return m_evt_handler->m_curr->pos.offset; } void _handle_block_check_leading_tabs(size_t prev_mark) { return _handle_block_check_leading_tabs(prev_mark, m_evt_handler->m_curr->pos.offset); } void _handle_block_check_leading_tabs(size_t start_mark, size_t end_mark); void _end_map_flow(); void _end_seq_flow(); void _end_map_blck(); void _end_seq_blck(); void _end2_map(); void _end2_seq(); void _end_flow_container(size_t orig_indent, bool multiline); void _flow_container_was_a_key(size_t orig_indent); void _begin2_doc(); void _begin2_doc_expl(); void _end2_doc(); void _end2_doc_expl(); void _check_doc_end_tokens() const; void _maybe_begin_doc(); void _maybe_end_doc(); void _start_doc_suddenly(); void _end_doc_suddenly(); void _end_doc_suddenly__pop(); void _check_trailing_doc_token(); void _end_stream(); void _set_indentation(size_t indentation) noexcept; void _save_indentation(); void _mark_seqflow_val_end() noexcept; void _handle_indentation_pop_from_block_seq(); void _handle_indentation_pop_from_block_map(); void _handle_indentation_pop(ParserState const* dst); void _maybe_skip_comment(); void _maybe_skip_comment_strict(); void _skip_comment(); void _maybe_skip_whitespace_tokens(); void _maybe_skipchars(char c); template void _skipchars(const char (&chars)[N]); bool _maybe_scan_following_colon() noexcept; public: /** @cond dev */ template auto _filter_plain(FilterProcessor &C4_RESTRICT proc, size_t indentation) -> decltype(proc.result()); template auto _filter_squoted(FilterProcessor &C4_RESTRICT proc) -> decltype(proc.result()); template auto _filter_dquoted(FilterProcessor &C4_RESTRICT proc) -> decltype(proc.result()); template auto _filter_block_literal(FilterProcessor &C4_RESTRICT proc, size_t indentation, BlockChomp_e chomp) -> decltype(proc.result()); template auto _filter_block_folded(FilterProcessor &C4_RESTRICT proc, size_t indentation, BlockChomp_e chomp) -> decltype(proc.result()); /** @endcond */ public: /** @cond dev */ template void _filter_nl_plain(FilterProcessor &C4_RESTRICT proc, size_t indentation); template void _filter_nl_squoted(FilterProcessor &C4_RESTRICT proc); template void _filter_nl_dquoted(FilterProcessor &C4_RESTRICT proc); template bool _filter_ws_handle_to_first_non_space(FilterProcessor &C4_RESTRICT proc); template void _filter_ws_copy_trailing(FilterProcessor &C4_RESTRICT proc); template void _filter_ws_skip_trailing(FilterProcessor &C4_RESTRICT proc); template void _filter_dquoted_backslash(FilterProcessor &C4_RESTRICT proc); template void _filter_dquoted_backslash_decode(FilterProcessor &C4_RESTRICT proc, size_t sz); template void _filter_chomp(FilterProcessor &C4_RESTRICT proc, BlockChomp_e chomp, size_t indentation); template size_t _handle_all_whitespace(FilterProcessor &C4_RESTRICT proc, BlockChomp_e chomp); template size_t _extend_to_chomp(FilterProcessor &C4_RESTRICT proc, size_t contents_len); template void _filter_block_indentation(FilterProcessor &C4_RESTRICT proc, size_t indentation); template void _filter_block_folded_newlines(FilterProcessor &C4_RESTRICT proc, size_t indentation, size_t len); template size_t _filter_block_folded_newlines_compress(FilterProcessor &C4_RESTRICT proc, size_t num_newl, size_t wpos_at_first_newl); template void _filter_block_folded_newlines_leading(FilterProcessor &C4_RESTRICT proc, size_t indentation, size_t len); template void _filter_block_folded_indented_block(FilterProcessor &C4_RESTRICT proc, size_t indentation, size_t len, size_t curr_indentation) noexcept; substr _alloc_arena(size_t len, substr *relocated=nullptr); substr _alloc_arena(size_t len, csubstr *relocated) { return _alloc_arena(len, reinterpret_cast(relocated)); } // NOLINT /** @endcond */ private: void _line_progressed(size_t ahead); void _line_ended(); void _line_ended_undo(); bool _finished_file() const; bool _finished_line() const; void _scan_line(); substr _peek_next_line(size_t pos=npos) const; void _relocate_arena(csubstr prev_arena, substr next_arena, substr *other_string=nullptr); private: C4_ALWAYS_INLINE substr _buf() const noexcept { return m_evt_handler->m_src; } C4_ALWAYS_INLINE bool has_all(ParserFlag_t f) const noexcept { return (m_evt_handler->m_curr->flags & f) == f; } C4_ALWAYS_INLINE bool has_any(ParserFlag_t f) const noexcept { return (m_evt_handler->m_curr->flags & f) != 0; } C4_ALWAYS_INLINE bool has_none(ParserFlag_t f) const noexcept { return (m_evt_handler->m_curr->flags & f) == 0; } static C4_ALWAYS_INLINE bool has_all(ParserFlag_t f, ParserState const* C4_RESTRICT s) noexcept { return (s->flags & f) == f; } static C4_ALWAYS_INLINE bool has_any(ParserFlag_t f, ParserState const* C4_RESTRICT s) noexcept { return (s->flags & f) != 0; } static C4_ALWAYS_INLINE bool has_none(ParserFlag_t f, ParserState const* C4_RESTRICT s) noexcept { return (s->flags & f) == 0; } #ifndef RYML_DBG C4_ALWAYS_INLINE void add_flags(ParserFlag_t on) noexcept { m_evt_handler->m_curr->flags |= on; } C4_ALWAYS_INLINE void addrem_flags(ParserFlag_t on, ParserFlag_t off) noexcept { m_evt_handler->m_curr->flags &= ~off; m_evt_handler->m_curr->flags |= on; } C4_ALWAYS_INLINE void rem_flags(ParserFlag_t off) noexcept { m_evt_handler->m_curr->flags &= ~off; } #else C4_ALWAYS_INLINE void add_flags(ParserFlag_t on); C4_ALWAYS_INLINE void addrem_flags(ParserFlag_t on, ParserFlag_t off); C4_ALWAYS_INLINE void rem_flags(ParserFlag_t off); #endif private: void _prepare_locations(); void _resize_locations(size_t sz); bool _locations_dirty() const; private: void _reset(); void _free(); void _clr(); template C4_NORETURN C4_NO_INLINE void _err(Location const& cpploc, const char *fmt, Args const& ...args) const; template C4_NORETURN C4_NO_INLINE void _err(Location const& cpploc, Location const& ymlloc, const char *fmt, Args const& ...args) const; #ifdef RYML_DBG template C4_NO_INLINE void _dbg(csubstr fmt, Args const& ...args) const; template C4_NO_INLINE void _fmt_msg(DumpFn &&dumpfn) const; C4_NO_INLINE void _print_state_stack() const; C4_NO_INLINE void _print_state_stack(substr buf) const; #endif private: void _handle_colon(); void _add_annotation(Annotation *C4_RESTRICT dst, csubstr str, size_t indentation, size_t line); void _add_annotation(Annotation *C4_RESTRICT dst, csubstr str, size_t indentation, size_t line, csubstr orig); void _add_annotation(Annotation *C4_RESTRICT dst, csubstr str); C4_ALWAYS_INLINE void _clear_annotations(Annotation *C4_RESTRICT dst) noexcept { dst->num_entries = 0; } bool _annotations_require_key_container() const; bool _handle_annotations_before_unexpected_flow_token_rkey(); void _handle_annotations_before_blck_key_scalar(); void _handle_annotations_before_blck_val_scalar(); void _handle_annotations_before_start_mapblck(size_t current_line); void _handle_annotations_before_start_mapblck_as_key(); void _handle_annotations_and_indentation_after_start_mapblck(size_t key_indentation, size_t key_line); size_t _select_indentation_from_annotations(size_t val_indentation, size_t val_line); uint32_t _get_annotations_same_line(csubstr token_soup, csubstr * first, csubstr * second) const; void _handle_keyref(csubstr alias); void _handle_valref(csubstr alias); csubstr _resolve_tag(csubstr tag); void _handle_directive(csubstr rem); bool _validate_directive_yaml(csubstr *C4_RESTRICT directive, csubstr *C4_RESTRICT version) const; bool _validate_directive_tag(csubstr *C4_RESTRICT directive, csubstr *C4_RESTRICT handle, csubstr *C4_RESTRICT prefix) const; bool _handle_bom(); void _handle_bom(Encoding_e enc); private: ParserOptions m_options; public: /** @cond dev */ EventHandler *C4_RESTRICT m_evt_handler; // NOLINT /** @endcond */ private: Annotation m_pending_anchors; Annotation m_pending_tags; bool m_has_directives_yaml; bool m_has_directives; bool m_doc_empty; size_t m_prev_colon; size_t m_prev_val_end; private: size_t m_bom_len; size_t m_bom_line; Encoding_e m_encoding; private: size_t *m_newline_offsets; size_t m_newline_offsets_size; size_t m_newline_offsets_capacity; public: // deprecated methods /** @cond dev */ RYML_DEPRECATED("filter arena no longer needed") size_t filter_arena_capacity() const { return 0u; } // LCOV_EXCL_LINE RYML_DEPRECATED("filter arena no longer needed") void reserve_filter_arena(size_t) {} // LCOV_EXCL_LINE template RYML_DEPRECATED("removed, deliberately undefined. use the function in parse.hpp.") typename std::enable_if::type parse_in_place(csubstr filename, substr yaml, Tree *t, size_t node_id); template RYML_DEPRECATED("removed, deliberately undefined. use the function in parse.hpp.") typename std::enable_if::type parse_in_place( substr yaml, Tree *t, size_t node_id); template RYML_DEPRECATED("removed, deliberately undefined. use the function in parse.hpp.") typename std::enable_if::type parse_in_place(csubstr filename, substr yaml, Tree *t ); template RYML_DEPRECATED("removed, deliberately undefined. use the function in parse.hpp.") typename std::enable_if::type parse_in_place( substr yaml, Tree *t ); template RYML_DEPRECATED("removed, deliberately undefined. use the function in parse.hpp.") typename std::enable_if::type parse_in_place(csubstr filename, substr yaml, NodeRef node ); template RYML_DEPRECATED("removed, deliberately undefined. use the function in parse.hpp.") typename std::enable_if::type parse_in_place( substr yaml, NodeRef node ); template RYML_DEPRECATED("removed, deliberately undefined. use the function in parse.hpp.") typename std::enable_if::type parse_in_place(csubstr filename, substr yaml ); template RYML_DEPRECATED("removed, deliberately undefined. use the function in parse.hpp.") typename std::enable_if::type parse_in_place( substr yaml ); template RYML_DEPRECATED("removed, deliberately undefined. use the function in parse.hpp.") typename std::enable_if::type parse_in_arena(csubstr filename, csubstr yaml, Tree *t, size_t node_id); template RYML_DEPRECATED("removed, deliberately undefined. use the function in parse.hpp.") typename std::enable_if::type parse_in_arena( csubstr yaml, Tree *t, size_t node_id); template RYML_DEPRECATED("removed, deliberately undefined. use the function in parse.hpp.") typename std::enable_if::type parse_in_arena(csubstr filename, csubstr yaml, Tree *t ); template RYML_DEPRECATED("removed, deliberately undefined. use the function in parse.hpp.") typename std::enable_if::type parse_in_arena( csubstr yaml, Tree *t ); template RYML_DEPRECATED("removed, deliberately undefined. use the function in parse.hpp.") typename std::enable_if::type parse_in_arena(csubstr filename, csubstr yaml, NodeRef node ); template RYML_DEPRECATED("removed, deliberately undefined. use the function in parse.hpp.") typename std::enable_if::type parse_in_arena( csubstr yaml, NodeRef node ); template RYML_DEPRECATED("removed, deliberately undefined. use the function in parse.hpp.") typename std::enable_if::type parse_in_arena(csubstr filename, csubstr yaml ); template RYML_DEPRECATED("removed, deliberately undefined. use the function in parse.hpp.") typename std::enable_if::type parse_in_arena( csubstr yaml ); template RYML_DEPRECATED("removed, deliberately undefined. use the csubstr version in parse.hpp.") typename std::enable_if::type parse_in_arena(csubstr filename, substr yaml, Tree *t, size_t node_id); template RYML_DEPRECATED("removed, deliberately undefined. use the csubstr version in parse.hpp.") typename std::enable_if::type parse_in_arena( substr yaml, Tree *t, size_t node_id); template RYML_DEPRECATED("removed, deliberately undefined. use the csubstr version in parse.hpp.") typename std::enable_if::type parse_in_arena(csubstr filename, substr yaml, Tree *t ); template RYML_DEPRECATED("removed, deliberately undefined. use the csubstr version in parse.hpp.") typename std::enable_if::type parse_in_arena( substr yaml, Tree *t ); template RYML_DEPRECATED("removed, deliberately undefined. use the csubstr version in parse.hpp.") typename std::enable_if::type parse_in_arena(csubstr filename, substr yaml, NodeRef node ); template RYML_DEPRECATED("removed, deliberately undefined. use the csubstr version in parse.hpp.") typename std::enable_if::type parse_in_arena( substr yaml, NodeRef node ); template RYML_DEPRECATED("removed, deliberately undefined. use the csubstr version in parse.hpp.") typename std::enable_if::type parse_in_arena(csubstr filename, substr yaml ); template RYML_DEPRECATED("removed, deliberately undefined. use the csubstr version in parse.hpp.") typename std::enable_if::type parse_in_arena( substr yaml ); template RYML_DEPRECATED("moved to Tree::location(Parser const&). deliberately undefined here.") auto location(Tree const&, id_type node) const -> typename std::enable_if::type; template RYML_DEPRECATED("moved to ConstNodeRef::location(Parser const&), deliberately undefined here.") auto location(ConstNodeRef const&) const -> typename std::enable_if::type; /** @endcond */ }; /** @} */ /** @cond dev */ C4_SUPPRESS_WARNING_GCC_WITH_PUSH("-Wattributes") C4_NO_INLINE inline size_t _find_last_newline_and_larger_indentation(csubstr s, size_t indentation) noexcept { if(indentation + 1 > s.len) return npos; for(size_t i = s.len-indentation-1; i != size_t(-1); --i) // NOLINT { if(s.str[i] == '\n') { csubstr rem = s.sub(i + 1); size_t first = rem.first_not_of(' '); first = (first != npos) ? first : rem.len; if(first > indentation) return i; } } return npos; } C4_SUPPRESS_WARNING_GCC_POP /** @endcond */ } // namespace yml } // namespace c4 // NOLINTEND(hicpp-signed-bitwise) #if defined(_MSC_VER) # pragma warning(pop) #endif #endif /* C4_YML_PARSE_ENGINE_HPP_ */ // (end src/c4/yml/parse_engine.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/reference_resolver.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_REFERENCE_RESOLVER_HPP_ #define C4_YML_REFERENCE_RESOLVER_HPP_ #ifndef C4_YML_TREE_HPP_ //#include "c4/yml/tree.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/tree.hpp must have been amalgamated before this point" #endif /* C4_YML_TREE_HPP_ */ #ifndef C4_YML_DETAIL_STACK_HPP_ //#include "c4/yml/detail/stack.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/detail/stack.hpp must have been amalgamated before this point" #endif /* C4_YML_DETAIL_STACK_HPP_ */ namespace c4 { namespace yml { /** @addtogroup doc_ref_utils * @{ */ /** Reusable object to resolve references/aliases in a @ref Tree. */ struct ReferenceResolver { ReferenceResolver() = default; /** Resolve references: for each reference, look for a matching * anchor, and copy its contents to the ref node. * * @p tree the subject tree * * @p clear_anchors whether to clear existing anchors after * resolving * * This method first does a full traversal of the tree to gather * all anchors and references in a separate collection, then it * goes through that collection to locate the names, which it does * by obeying the YAML standard diktat that "an alias node refers * to the most recent node in the serialization having the * specified anchor" * * So, depending on the number of anchor/alias nodes, this is a * potentially expensive operation, with a best-case linear * complexity (from the initial traversal). This potential cost is * one of the reasons for requiring an explicit call. * * The @ref Tree has an `Tree::resolve()` overload set forwarding * here. Previously this operation was done there, using a * discarded object; using this separate class offers opportunity * for reuse of the object. * * @warning resolving references opens an attack vector when the * data is malicious or severely malformed, as the tree can expand * exponentially. See for example the [Billion Laughs * Attack](https://en.wikipedia.org/wiki/Billion_laughs_attack). * */ RYML_EXPORT void resolve(Tree *tree, bool clear_anchors=true); public: /** @cond dev */ struct RefData { NodeType type; id_type node; id_type prev_anchor; id_type target; id_type parent_ref; id_type parent_ref_sibling; }; void reset_(Tree *t_); void resolve_(); void gather_anchors_and_refs_(); void gather_anchors_and_refs_(id_type n); id_type count_anchors_and_refs_(id_type n); id_type lookup_(RefData const* C4_RESTRICT ra); Tree *C4_RESTRICT m_tree; /** We're using this stack purely as an array. */ detail::stack m_refs; /** @endcond */ }; /** @} */ } // namespace ryml } // namespace c4 #endif // C4_YML_REFERENCE_RESOLVER_HPP_ // (end src/c4/yml/reference_resolver.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/parse.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_PARSE_HPP_ #define C4_YML_PARSE_HPP_ #ifndef C4_YML_COMMON_HPP_ //#include "c4/yml/common.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/common.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_PARSE_OPTIONS_HPP_ //#include "c4/yml/parse_options.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/parse_options.hpp must have been amalgamated before this point" #endif namespace c4 { namespace yml { class Tree; class NodeRef; template class ParseEngine; struct EventHandlerTree; RYML_EXPORT id_type estimate_tree_capacity(csubstr src); // NOLINT /** @addtogroup doc_parse * @{ */ /** This is the main ryml parser, where the parser events are handled * to create a ryml tree (see @ref doc_event_handlers). * * @warning This class cannot parse YAML which has container * keys. This is not a limitation of the @ref ParseEngine itself, but of the * @ref EventHandlerTree, which is present because the @ref Tree does * not accept containers as keys. However, the @ref ParseEngine *can* * parse container keys; consult its documentation for more details. * * @see @ref ParserOptions * @see @ref ParseEngine * @see @ref EventHandlerTree * @see @ref doc_event_handlers * */ using Parser = ParseEngine; //----------------------------------------------------------------------------- /** @addtogroup doc_parse_in_place__with_existing_parser * * @brief parse a mutable YAML source buffer (re)using an existing * parser. Scalars requiring filtering are mutated in place (except in * the rare cases where the filtered scalar is longer than the * original scalar, or where filtering was disabled before the * call). These overloads accept an existing parser object, and * provide the opportunity to use special parser options. * * @see ParserOptions * * @{ */ // this is vertically aligned to highlight the parameter differences. RYML_EXPORT void parse_in_place(Parser *parser, csubstr filename, substr yaml, Tree *t, id_type node_id); /**< (1) parse YAML into an existing tree node. * * The filename will be used in any error messages * arising during the parse. The callbacks in the * tree are kept, and used to allocate * the tree members, if any allocation is required. */ RYML_EXPORT void parse_in_place(Parser *parser, substr yaml, Tree *t, id_type node_id); /**< (2) like (1) but no filename will be reported */ RYML_EXPORT void parse_in_place(Parser *parser, csubstr filename, substr yaml, Tree *t ); /**< (3) parse YAML into the root node of an existing tree. * * The filename will be used in any error messages * arising during the parse. The callbacks in the * tree are kept, and used to allocate * the tree members, if any allocation is required. */ RYML_EXPORT void parse_in_place(Parser *parser, substr yaml, Tree *t ); /**< (4) like (3) but no filename will be reported */ RYML_EXPORT void parse_in_place(Parser *parser, csubstr filename, substr yaml, NodeRef node ); /**< (5) like (1) but the node is given as a NodeRef */ RYML_EXPORT void parse_in_place(Parser *parser, substr yaml, NodeRef node ); /**< (6) like (5) but no filename will be reported */ RYML_EXPORT Tree parse_in_place(Parser *parser, csubstr filename, substr yaml ); /**< (7) create a new tree, and parse YAML into its root node. * * The filename will be used in any error messages * arising during the parse. The tree is created with * the callbacks currently in the parser. */ RYML_EXPORT Tree parse_in_place(Parser *parser, substr yaml ); /**< (8) like (7) but no filename will be reported */ // this is vertically aligned to highlight the parameter differences. RYML_EXPORT void parse_json_in_place(Parser *parser, csubstr filename, substr json, Tree *t, id_type node_id); ///< (1) parse JSON into an existing tree node. The filename will be used in any error messages arising during the parse. RYML_EXPORT void parse_json_in_place(Parser *parser, substr json, Tree *t, id_type node_id); ///< (2) like (1) but no filename will be reported RYML_EXPORT void parse_json_in_place(Parser *parser, csubstr filename, substr json, Tree *t ); ///< (3) parse JSON into an existing tree, into its root node. RYML_EXPORT void parse_json_in_place(Parser *parser, substr json, Tree *t ); ///< (4) like (3) but no filename will be reported RYML_EXPORT void parse_json_in_place(Parser *parser, csubstr filename, substr json, NodeRef node ); ///< (5) like (1) but the node is given as a NodeRef RYML_EXPORT void parse_json_in_place(Parser *parser, substr json, NodeRef node ); ///< (6) like (5) but no filename will be reported RYML_EXPORT Tree parse_json_in_place(Parser *parser, csubstr filename, substr json ); ///< (7) create a new tree, and parse JSON into its root node. RYML_EXPORT Tree parse_json_in_place(Parser *parser, substr json ); ///< (8) like (7) but no filename will be reported /** @} */ //----------------------------------------------------------------------------- /** @addtogroup doc_parse_in_place___with_temporary_parser Parse in place with temporary parser * * @brief parse a mutable YAML source buffer. Scalars requiring * filtering are mutated in place (except in the rare cases where the * filtered scalar is longer than the original scalar). * * @note These freestanding functions use a temporary parser object, * and are convenience functions to enable the user to easily parse * YAML without the need to explicitly instantiate a parser and event * handler. Note that some properties (notably node locations in the * original source code) are only available through the parser * class. If you need access to any of these properties, use * the appropriate overload from @ref doc_parse_in_place__with_existing_parser * * @{ */ // this is vertically aligned to highlight the parameter differences. RYML_EXPORT void parse_in_place(csubstr filename, substr yaml, Tree *t, id_type node_id, ParserOptions const& opts={}); ///< (1) parse YAML into an existing tree node. The filename will be used in any error messages arising during the parse. RYML_EXPORT void parse_in_place( substr yaml, Tree *t, id_type node_id, ParserOptions const& opts={}); ///< (2) like (1) but no filename will be reported RYML_EXPORT void parse_in_place(csubstr filename, substr yaml, Tree *t , ParserOptions const& opts={}); ///< (3) parse YAML into an existing tree, into its root node. RYML_EXPORT void parse_in_place( substr yaml, Tree *t , ParserOptions const& opts={}); ///< (4) like (3) but no filename will be reported RYML_EXPORT void parse_in_place(csubstr filename, substr yaml, NodeRef node , ParserOptions const& opts={}); ///< (5) like (1) but the node is given as a NodeRef RYML_EXPORT void parse_in_place( substr yaml, NodeRef node , ParserOptions const& opts={}); ///< (6) like (5) but no filename will be reported RYML_EXPORT Tree parse_in_place(csubstr filename, substr yaml , ParserOptions const& opts={}); ///< (7) create a new tree, and parse YAML into its root node. RYML_EXPORT Tree parse_in_place( substr yaml , ParserOptions const& opts={}); ///< (8) like (7) but no filename will be reported // this is vertically aligned to highlight the parameter differences. RYML_EXPORT void parse_json_in_place(csubstr filename, substr json, Tree *t, id_type node_id, ParserOptions const& opts={}); ///< (1) parse JSON into an existing tree node. The filename will be used in any error messages arising during the parse. RYML_EXPORT void parse_json_in_place( substr json, Tree *t, id_type node_id, ParserOptions const& opts={}); ///< (2) like (1) but no filename will be reported RYML_EXPORT void parse_json_in_place(csubstr filename, substr json, Tree *t , ParserOptions const& opts={}); ///< (3) parse JSON into an existing tree, into its root node. RYML_EXPORT void parse_json_in_place( substr json, Tree *t , ParserOptions const& opts={}); ///< (4) like (3) but no filename will be reported RYML_EXPORT void parse_json_in_place(csubstr filename, substr json, NodeRef node , ParserOptions const& opts={}); ///< (5) like (1) but the node is given as a NodeRef RYML_EXPORT void parse_json_in_place( substr json, NodeRef node , ParserOptions const& opts={}); ///< (6) like (5) but no filename will be reported RYML_EXPORT Tree parse_json_in_place(csubstr filename, substr json , ParserOptions const& opts={}); ///< (7) create a new tree, and parse JSON into its root node. RYML_EXPORT Tree parse_json_in_place( substr json , ParserOptions const& opts={}); ///< (8) like (7) but no filename will be reported /** @} */ //----------------------------------------------------------------------------- /** @addtogroup doc_parse_in_arena__with_existing_parser Parse in arena with existing parser * * @brief parse a read-only (immutable) YAML source buffer. This is * achieved by first copying the contents of the buffer to the tree's * arena, and then calling @ref parse_in_arena() . All the resulting * scalars will be filtered in the arena. These overloads accept an * existing parser object, and provide the opportunity to use special * parser options. * * @see ParserOptions * * * @note These freestanding functions use a temporary parser object, * and are convenience functions to easily parse YAML without the need * to instantiate a separate parser. Note that some properties * (notably node locations in the original source code) are only * available through the parser class. If you need access to any of * these properties, use the appropriate overload from @ref * doc_parse_in_arena__with_existing_parser * * @warning overloads receiving a substr YAML buffer are intentionally * left undefined, such that calling parse_in_arena() with a substr * will cause a linker error. This is to prevent an accidental copy of * the source buffer to the tree's arena, because substr (which is * mutable) is implicitly convertible to csubstr (which is * immutable). If you really intend to parse a mutable buffer in the * tree's arena, convert it first to immutable by assigning the substr * to a csubstr prior to calling parse_in_arena(). This is not needed * for parse_in_place() because csubstr is not implicitly convertible * to substr. To be clear: * ```c++ * substr mutable_buffer = ...; * parser.parse_in_arena(mutable_buffer); // linker error * * csubstr immutable_buffer = mutable_buffer; // convert first to csubstr * parser.parse_in_arena(immutable_buffer); // ok * ``` * * @{ */ /** @cond dev */ #define RYML_DONT_PARSE_SUBSTR_IN_ARENA "" \ "Do not pass a (mutable) substr to parse_in_arena(); " \ "if you have a substr, it should be parsed in place. " \ "Consider using parse_in_place() instead, or convert " \ "the buffer to csubstr prior to calling. This function " \ " is deliberately left undefined, so that calling it " \ "will cause a linker error." /** @endcond */ // this is vertically aligned to highlight the parameter differences. RYML_EXPORT void parse_in_arena(Parser *parser, csubstr filename, csubstr yaml, Tree *t, id_type node_id); ///< (1) parse YAML into an existing tree node. The filename will be used in any error messages arising during the parse. RYML_EXPORT void parse_in_arena(Parser *parser, csubstr yaml, Tree *t, id_type node_id); ///< (2) like (1) but no filename will be reported RYML_EXPORT void parse_in_arena(Parser *parser, csubstr filename, csubstr yaml, Tree *t ); ///< (3) parse YAML into an existing tree, into its root node. RYML_EXPORT void parse_in_arena(Parser *parser, csubstr yaml, Tree *t ); ///< (4) like (3) but no filename will be reported RYML_EXPORT void parse_in_arena(Parser *parser, csubstr filename, csubstr yaml, NodeRef node ); ///< (5) like (1) but the node is given as a NodeRef RYML_EXPORT void parse_in_arena(Parser *parser, csubstr yaml, NodeRef node ); ///< (6) like (5) but no filename will be reported RYML_EXPORT Tree parse_in_arena(Parser *parser, csubstr filename, csubstr yaml ); ///< (7) create a new tree, and parse YAML into its root node. RYML_EXPORT Tree parse_in_arena(Parser *parser, csubstr yaml ); ///< (8) like (7) but no filename will be reported // this is vertically aligned to highlight the parameter differences. RYML_EXPORT void parse_json_in_arena(Parser *parser, csubstr filename, csubstr json, Tree *t, id_type node_id); ///< (1) parse JSON into an existing tree node. The filename will be used in any error messages arising during the parse. RYML_EXPORT void parse_json_in_arena(Parser *parser, csubstr json, Tree *t, id_type node_id); ///< (2) like (1) but no filename will be reported RYML_EXPORT void parse_json_in_arena(Parser *parser, csubstr filename, csubstr json, Tree *t ); ///< (3) parse JSON into an existing tree, into its root node. RYML_EXPORT void parse_json_in_arena(Parser *parser, csubstr json, Tree *t ); ///< (4) like (3) but no filename will be reported RYML_EXPORT void parse_json_in_arena(Parser *parser, csubstr filename, csubstr json, NodeRef node ); ///< (5) like (1) but the node is given as a NodeRef RYML_EXPORT void parse_json_in_arena(Parser *parser, csubstr json, NodeRef node ); ///< (6) like (5) but no filename will be reported RYML_EXPORT Tree parse_json_in_arena(Parser *parser, csubstr filename, csubstr json ); ///< (7) create a new tree, and parse JSON into its root node. RYML_EXPORT Tree parse_json_in_arena(Parser *parser, csubstr json ); ///< (8) like (7) but no filename will be reported /* READ THE DEPRECATION NOTE! * * All of the functions below are intentionally left undefined, to * prevent them being used. * */ /** @cond dev */ RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_in_arena(Parser *parser, substr yaml, Tree *t, id_type node_id); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_in_arena(Parser *parser, csubstr filename, substr yaml, Tree *t, id_type node_id); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_in_arena(Parser *parser, substr yaml, Tree *t ); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_in_arena(Parser *parser, csubstr filename, substr yaml, Tree *t ); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_in_arena(Parser *parser, substr yaml, NodeRef node ); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_in_arena(Parser *parser, csubstr filename, substr yaml, NodeRef node ); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) Tree parse_in_arena(Parser *parser, substr yaml ); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) Tree parse_in_arena(Parser *parser, csubstr filename, substr yaml ); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_json_in_arena(Parser *parser, substr json, Tree *t, id_type node_id); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_json_in_arena(Parser *parser, csubstr filename, substr json, Tree *t, id_type node_id); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_json_in_arena(Parser *parser, substr json, Tree *t ); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_json_in_arena(Parser *parser, csubstr filename, substr json, Tree *t ); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_json_in_arena(Parser *parser, substr json, NodeRef node ); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_json_in_arena(Parser *parser, csubstr filename, substr json, NodeRef node ); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) Tree parse_json_in_arena(Parser *parser, substr json ); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) Tree parse_json_in_arena(Parser *parser, csubstr filename, substr json ); /** @endcond */ /** @} */ //----------------------------------------------------------------------------- /** @addtogroup doc_parse_in_arena__with_temporary_parser Parse in arena with temporary parser * * @brief parse a read-only (immutable) YAML source buffer. This is * achieved by first copying the contents of the buffer to the tree's * arena, and then calling @ref parse_in_arena() . * * @note These freestanding functions use a temporary parser object, * and are convenience functions to easily one-off parse YAML without * the need to instantiate a separate parser. Note that some * properties (notably node locations in the original source code) are * only available through the parser class. If you need access to any * of these properties, use the appropriate overload from @ref * doc_parse_in_arena__with_existing_parser * * @warning overloads receiving a substr YAML buffer are intentionally * left undefined, such that calling parse_in_arena() with a substr * will cause a linker error. This is to prevent an accidental copy of * the source buffer to the tree's arena, because substr (which is * mutable) is implicitly convertible to csubstr (which is * immutable). If you really intend to parse a mutable buffer in the * tree's arena, convert it first to immutable by assigning the substr * to a csubstr prior to calling parse_in_arena(). This is not needed * for parse_in_place() because csubstr is not implicitly convertible * to substr. To be clear: * ```c++ * substr mutable_buffer = ...; * parser.parse_in_arena(mutable_buffer); // linker error * * csubstr immutable_buffer = mutable_buffer; // convert first to csubstr * parser.parse_in_arena(immutable_buffer); // ok now * ``` * * @{ */ // this is vertically aligned to highlight the parameter differences. RYML_EXPORT void parse_in_arena(csubstr filename, csubstr yaml, Tree *t, id_type node_id, ParserOptions const& opts={}); ///< (1) parse YAML into an existing tree node. The filename will be used in any error messages arising during the parse. RYML_EXPORT void parse_in_arena( csubstr yaml, Tree *t, id_type node_id, ParserOptions const& opts={}); ///< (2) like (1) but no filename will be reported RYML_EXPORT void parse_in_arena(csubstr filename, csubstr yaml, Tree *t , ParserOptions const& opts={}); ///< (3) parse YAML into an existing tree, into its root node. RYML_EXPORT void parse_in_arena( csubstr yaml, Tree *t , ParserOptions const& opts={}); ///< (4) like (3) but no filename will be reported RYML_EXPORT void parse_in_arena(csubstr filename, csubstr yaml, NodeRef node , ParserOptions const& opts={}); ///< (5) like (1) but the node is given as a NodeRef RYML_EXPORT void parse_in_arena( csubstr yaml, NodeRef node , ParserOptions const& opts={}); ///< (6) like (5) but no filename will be reported RYML_EXPORT Tree parse_in_arena(csubstr filename, csubstr yaml , ParserOptions const& opts={}); ///< (7) create a new tree, and parse YAML into its root node. RYML_EXPORT Tree parse_in_arena( csubstr yaml , ParserOptions const& opts={}); ///< (8) like (7) but no filename will be reported // this is vertically aligned to highlight the parameter differences. RYML_EXPORT void parse_json_in_arena(csubstr filename, csubstr json, Tree *t, id_type node_id, ParserOptions const& opts={}); ///< (1) parse JSON into an existing tree node. The filename will be used in any error messages arising during the parse. RYML_EXPORT void parse_json_in_arena( csubstr json, Tree *t, id_type node_id, ParserOptions const& opts={}); ///< (2) like (1) but no filename will be reported RYML_EXPORT void parse_json_in_arena(csubstr filename, csubstr json, Tree *t , ParserOptions const& opts={}); ///< (3) parse JSON into an existing tree, into its root node. RYML_EXPORT void parse_json_in_arena( csubstr json, Tree *t , ParserOptions const& opts={}); ///< (4) like (3) but no filename will be reported RYML_EXPORT void parse_json_in_arena(csubstr filename, csubstr json, NodeRef node , ParserOptions const& opts={}); ///< (5) like (1) but the node is given as a NodeRef RYML_EXPORT void parse_json_in_arena( csubstr json, NodeRef node , ParserOptions const& opts={}); ///< (6) like (5) but no filename will be reported RYML_EXPORT Tree parse_json_in_arena(csubstr filename, csubstr json , ParserOptions const& opts={}); ///< (7) create a new tree, and parse JSON into its root node. RYML_EXPORT Tree parse_json_in_arena( csubstr json , ParserOptions const& opts={}); ///< (8) like (7) but no filename will be reported /* READ THE DEPRECATION NOTE! * * All of the functions below are intentionally left undefined, to * prevent them being used. */ /** @cond dev */ RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_in_arena( substr yaml, Tree *t, id_type node_id); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_in_arena(csubstr filename, substr yaml, Tree *t, id_type node_id); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_in_arena( substr yaml, Tree *t ); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_in_arena(csubstr filename, substr yaml, Tree *t ); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_in_arena( substr yaml, NodeRef node ); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_in_arena(csubstr filename, substr yaml, NodeRef node ); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) Tree parse_in_arena( substr yaml ); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) Tree parse_in_arena(csubstr filename, substr yaml ); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_json_in_arena( substr json, Tree *t, id_type node_id); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_json_in_arena(csubstr filename, substr json, Tree *t, id_type node_id); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_json_in_arena( substr json, Tree *t ); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_json_in_arena(csubstr filename, substr json, Tree *t ); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_json_in_arena( substr json, NodeRef node ); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) void parse_json_in_arena(csubstr filename, substr json, NodeRef node ); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) Tree parse_json_in_arena( substr json ); RYML_DEPRECATED(RYML_DONT_PARSE_SUBSTR_IN_ARENA) Tree parse_json_in_arena(csubstr filename, substr json ); /** @endcond */ /** @} */ /** @} */ } // namespace yml } // namespace c4 #endif /* C4_YML_PARSE_HPP_ */ // (end src/c4/yml/parse.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/std/map.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_STD_MAP_HPP_ #define C4_YML_STD_MAP_HPP_ /** @file map.hpp write/read std::map to/from a YAML tree. */ #ifndef C4_YML_NODE_HPP_ //#include "c4/yml/node.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/node.hpp must have been amalgamated before this point" #endif /* C4_YML_NODE_HPP_ */ #include namespace c4 { namespace yml { // std::map requires child nodes in the data // tree hierarchy (a MAP node in ryml parlance). // So it should be serialized via write()/read(). /** serialize a map to a node: implementation for @ref Tree */ template void write(c4::yml::Tree *tree, c4::yml::id_type id, std::map const& m) { tree->set_map(id); for(auto const& C4_RESTRICT p : m) { id_type child = tree->append_child(id); tree->set_key_serialized(child, p.first); tree->set_serialized(child, p.second); } } /** serialize a map to a node: implementation for @ref NodeRef */ template C4_ALWAYS_INLINE void write(c4::yml::NodeRef *n, std::map const& m) { n->set_map(); for(auto const& C4_RESTRICT p : m) { NodeRef ch = n->append_child(); ch.set_key_serialized(p.first); ch.set_serialized(p.second); } } /** deserialize a map from a node: implementation for @ref Tree . * Read the node members, assigning into the existing map. If a key is * already present in the map, then its value will be * move-assigned. The map */ template ReadResult read(c4::yml::Tree const* tree, c4::yml::id_type id, std::map * m) { if C4_UNLIKELY(!tree->is_map(id)) return ReadResult(id); for(id_type child = tree->first_child(id); child != NONE; child = tree->next_sibling(child)) { K k{}; ReadResult result = tree->deserialize_key(child, &k); if C4_UNLIKELY(!result) return result; result = tree->deserialize(child, &(*m)[std::move(k)]); if C4_UNLIKELY(!result) return result; } return ReadResult(); } /** deserialize a map from a node: implementation for @ref ConstNodeRef . read * the node members, assigning into the existing map. If a key is * already present in the map, then its value will be * move-assigned. */ template ReadResult read(c4::yml::ConstNodeRef const& n, std::map * m) { if C4_UNLIKELY(!n.is_map()) return ReadResult(n.id()); for(ConstNodeRef const& C4_RESTRICT ch : n) { K k{}; ReadResult result = ch.deserialize_key(&k); if C4_UNLIKELY(!result) return result; result = ch.deserialize(&(*m)[std::move(k)]); if C4_UNLIKELY(!result) return result; } return ReadResult(); } } // namespace yml } // namespace c4 #endif // C4_YML_STD_MAP_HPP_ // (end src/c4/yml/std/map.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/std/string.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_STD_STRING_HPP_ #define C4_YML_STD_STRING_HPP_ /** @file string.hpp substring conversions for/from std::string */ // everything we need is implemented here: #ifndef C4_STD_STRING_HPP_ //#include // amalgamate: remove include #error "amalgamate: c4/std/string.hpp must have been amalgamated before this point" #endif /* C4_STD_STRING_HPP_ */ #endif // C4_YML_STD_STRING_HPP_ // (end src/c4/yml/std/string.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/std/vector.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_STD_VECTOR_HPP_ #define C4_YML_STD_VECTOR_HPP_ #ifndef C4_YML_NODE_HPP_ //#include "c4/yml/node.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/node.hpp must have been amalgamated before this point" #endif /* C4_YML_NODE_HPP_ */ #ifndef C4_STD_VECTOR_HPP_ //#include // amalgamate: remove include #error "amalgamate: c4/std/vector.hpp must have been amalgamated before this point" #endif /* C4_STD_VECTOR_HPP_ */ //#include // amalgamate: included above namespace c4 { namespace yml { C4_SUPPRESS_WARNING_GCC_WITH_PUSH("-Wuseless-cast") // vector is a sequence-like type, and it requires child nodes // in the data tree hierarchy (a SEQ node in ryml parlance). // So it should be serialized via write()/read(). /** serialize a vector to a node: implementation for @ref Tree */ template void write(Tree *tree, id_type id, std::vector const& vec) { tree->set_seq(id); for(T const& val : vec) tree->set_serialized(tree->append_child(id), val); } /** serialize a vector to a node: implementation for @ref NodeRef */ template void write(NodeRef *n, std::vector const& vec) { // don't defer to the tree impl here (if that were the case, we // wouldn't even need to implement this function, as ryml ends up // calling the tree impl by default). It may be the case that the // serialization of T uses a serialization of a nested type that // is not available in the tree implementation, so we need to // provide this as a hook for that. If that's not required, then // the tree implementation will get called anyway. n->set_seq(); for(T const& val : vec) { NodeRef ch = n->append_child(); // call write() directly. ch.set_serialized() would also work, // but does an additional check (to create the node if it is a // seed). That check is not needed here because we used // .append_child() to create the node. write(&ch, val); } } /** deserialize from a @ref Tree node, overwriting existing vector entries. */ template ReadResult read(Tree const *tree, id_type id, std::vector *vec) { if C4_UNLIKELY(!tree->is_seq(id)) return ReadResult(id); vec->clear(); #if C4_CPP < 17 // prior to C++17, emplace_back() does not return a reference size_t pos = 0; #endif for(id_type child = tree->first_child(id); child != NONE; child = tree->next_sibling(child)) { #if C4_CPP >= 17 T &val = vec->emplace_back(); #else vec->emplace_back(); T &val = (*vec)[pos++]; #endif // do not call read(tree, child, &val) here. we do not know // that the YAML is valid, so we need to do the checks in // child.deserialize() if(!tree->deserialize(child, &val)) return ReadResult(id); } return ReadResult{}; } /** deserialize from a @ref ConstNodeRef node, overwriting existing vector entries. */ template ReadResult read(ConstNodeRef const& node, std::vector *vec) { // don't defer to the tree impl here (if that were the case, we // wouldn't even need to implement this function, as ryml ends up // calling the tree impl by default). It may be the case that the // serialization of T uses a serialization of a nested type that // is not available in the tree implementation, so we need to // provide this as a hook for that. If that's not required, then // the tree implementation will get called anyway. if C4_UNLIKELY(!node.is_seq()) return ReadResult(node.id()); vec->clear(); #if C4_CPP < 17 // prior to C++17, emplace_back() does not return a reference size_t pos = 0; #endif for(ConstNodeRef const& child : node.children()) { #if C4_CPP >= 17 T &val = vec->emplace_back(); #else vec->emplace_back(); T &val = (*vec)[pos++]; #endif // do not call read(child, &val) here. we do not know that the // YAML is valid, so we need to do the checks in // child.deserialize() if(!child.deserialize(&val)) return ReadResult(child.id()); } return ReadResult(); } //----------------------------------------------------- // specialization for std::vector. needed because the return // type of its operator[] is not bool, but std::vector::reference /** deserialize from a @ref Tree node, overwriting existing vector entries. */ template ReadResult read(Tree const* tree, id_type id, std::vector *vec) { if C4_UNLIKELY(!tree->is_seq(id)) return ReadResult(id); vec->clear(); bool tmp = {}; for(id_type child = tree->first_child(id); child != NONE; child = tree->next_sibling(child)) { if(!from_chars(tree->val(child), &tmp)) return ReadResult(child); vec->push_back(tmp); // leave this. gcc4.8 does not have std::vector::emplace_back() } return ReadResult(); } /** deserialize from a @ref ConstNodeRef node, overwriting existing vector entries. */ template ReadResult read(ConstNodeRef const& n, std::vector *vec) { // call the tree implementation, saving the node readability // checks. we can do that here because bool (the value type) is a // final type, so it can't be overrided. return read(n.tree(), n.id(), vec); } C4_SUPPRESS_WARNING_GCC_POP } // namespace yml } // namespace c4 #endif // C4_YML_STD_VECTOR_HPP_ // (end src/c4/yml/std/vector.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/std/std.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_STD_STD_HPP_ #define C4_YML_STD_STD_HPP_ /** @file std.hpp includes all rapidyaml-std interop files */ // bring all of c4core interop #ifndef C4_STD_STD_HPP_ //#include "c4/std/std.hpp" // amalgamate: remove include #error "amalgamate: c4/std/std.hpp must have been amalgamated before this point" #endif /* C4_STD_STD_HPP_ */ // bring all of rapidyaml interop #ifndef C4_YML_STD_STRING_HPP_ //#include "c4/yml/std/string.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/std/string.hpp must have been amalgamated before this point" #endif /* C4_YML_STD_STRING_HPP_ */ #ifndef C4_YML_STD_VECTOR_HPP_ //#include "c4/yml/std/vector.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/std/vector.hpp must have been amalgamated before this point" #endif /* C4_YML_STD_VECTOR_HPP_ */ #ifndef C4_YML_STD_MAP_HPP_ //#include "c4/yml/std/map.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/std/map.hpp must have been amalgamated before this point" #endif /* C4_YML_STD_MAP_HPP_ */ #endif // C4_YML_STD_STD_HPP_ // (end src/c4/yml/std/std.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/detail/checks.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_DETAIL_CHECKS_HPP_ #define C4_YML_DETAIL_CHECKS_HPP_ #ifndef C4_YML_TREE_HPP_ //#include "c4/yml/tree.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/tree.hpp must have been amalgamated before this point" #endif /* C4_YML_TREE_HPP_ */ #ifdef __clang__ # pragma clang diagnostic push #elif defined(__GNUC__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wtype-limits" // error: comparison of unsigned expression >= 0 is always true #elif defined(_MSC_VER) # pragma warning(push) # pragma warning(disable: 4296/*expression is always 'boolean_value'*/) #endif namespace c4 { namespace yml { void check_invariants(Tree const& t, id_type node=NONE); void check_free_list(Tree const& t); void check_arena(Tree const& t); //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- inline void check_invariants(Tree const& t, id_type node) { if(node == NONE) { if(t.empty()) return; node = t.root_id(); } NodeData const& n = *t._p(node); #if defined(RYML_DBG) && 0 if(n.m_first_child != NONE || n.m_last_child != NONE) { printf("check(%zu): fc=%zu lc=%zu\n", node, n.m_first_child, n.m_last_child); } else { printf("check(%zu)\n", node); } #endif C4_CHECK(n.m_parent != node); if(n.m_parent == NONE) { C4_CHECK(t.is_root(node)); } else //if(n.m_parent != NONE) { C4_CHECK(t.has_child(n.m_parent, node)); auto const& p = *t._p(n.m_parent); if(n.m_prev_sibling == NONE) { C4_CHECK(p.m_first_child == node); C4_CHECK(t.first_sibling(node) == node); } else { C4_CHECK(p.m_first_child != node); C4_CHECK(t.first_sibling(node) != node); } if(n.m_next_sibling == NONE) { C4_CHECK(p.m_last_child == node); C4_CHECK(t.last_sibling(node) == node); } else { C4_CHECK(p.m_last_child != node); C4_CHECK(t.last_sibling(node) != node); } } C4_CHECK(n.m_first_child != node); C4_CHECK(n.m_last_child != node); if(n.m_first_child != NONE || n.m_last_child != NONE) { C4_CHECK(n.m_first_child != NONE); C4_CHECK(n.m_last_child != NONE); } C4_CHECK(n.m_prev_sibling != node); C4_CHECK(n.m_next_sibling != node); if(n.m_prev_sibling != NONE) { C4_CHECK(t._p(n.m_prev_sibling)->m_next_sibling == node); C4_CHECK(t._p(n.m_prev_sibling)->m_prev_sibling != node); } if(n.m_next_sibling != NONE) { C4_CHECK(t._p(n.m_next_sibling)->m_prev_sibling == node); C4_CHECK(t._p(n.m_next_sibling)->m_next_sibling != node); } id_type count = 0; for(id_type i = n.m_first_child; i != NONE; i = t.next_sibling(i)) { #if defined(RYML_DBG) && 0 printf("check(%zu): descend to child[%zu]=%zu\n", node, count, i); #endif auto const& ch = *t._p(i); C4_CHECK(ch.m_parent == node); C4_CHECK(ch.m_next_sibling != i); ++count; } C4_CHECK(count == t.num_children(node)); if(n.m_prev_sibling == NONE && n.m_next_sibling == NONE) { if(n.m_parent != NONE) { C4_CHECK(t.num_children(n.m_parent) == 1); C4_CHECK(t.num_siblings(node) == 1); } } if(node == t.root_id()) { C4_CHECK(t.size() == t.m_size); C4_CHECK(t.capacity() == t.m_cap); C4_CHECK(t.m_cap == t.m_size + t.slack()); check_free_list(t); check_arena(t); } for(id_type i = t.first_child(node); i != NONE; i = t.next_sibling(i)) { check_invariants(t, i); } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- inline void check_free_list(Tree const& t) { if(t.m_free_head == NONE) { C4_CHECK(t.m_free_tail == t.m_free_head); return; } C4_CHECK(t.m_free_head >= 0 && t.m_free_head < t.m_cap); C4_CHECK(t.m_free_tail >= 0 && t.m_free_tail < t.m_cap); auto const& head = *t._p(t.m_free_head); //auto const& tail = *t._p(t.m_free_tail); //C4_CHECK(head.m_prev_sibling == NONE); //C4_CHECK(tail.m_next_sibling == NONE); id_type count = 0; for(id_type i = t.m_free_head, prev = NONE; i != NONE; i = t._p(i)->m_next_sibling) { auto const& elm = *t._p(i); if(&elm != &head) { C4_CHECK(elm.m_prev_sibling == prev); } prev = i; ++count; } C4_CHECK(count == t.slack()); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- inline void check_arena(Tree const& t) { C4_CHECK(t.m_arena.len == 0 || (t.m_arena_pos >= 0 && t.m_arena_pos <= t.m_arena.len)); C4_CHECK(t.arena_size() == t.m_arena_pos); C4_CHECK(t.arena_slack() + t.m_arena_pos == t.m_arena.len); } } /* namespace yml */ } /* namespace c4 */ #ifdef __clang__ # pragma clang diagnostic pop #elif defined(__GNUC__) # pragma GCC diagnostic pop #elif defined(_MSC_VER) # pragma warning(pop) #endif #endif /* C4_YML_DETAIL_CHECKS_HPP_ */ // (end src/c4/yml/detail/checks.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/detail/print.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_DETAIL_PRINT_HPP_ #define C4_YML_DETAIL_PRINT_HPP_ #ifndef C4_YML_NODE_HPP_ //#include "c4/yml/node.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/node.hpp must have been amalgamated before this point" #endif #ifdef RYML_DBG #define _c4dbg_tree(...) print_tree(__VA_ARGS__) #define _c4dbg_node(...) print_tree(__VA_ARGS__) #else #define _c4dbg_tree(...) #define _c4dbg_node(...) #endif // NOLINTBEGIN(modernize-avoid-c-style-cast) namespace c4 { namespace yml { C4_SUPPRESS_WARNING_GCC_CLANG_WITH_PUSH("-Wold-style-cast") C4_SUPPRESS_WARNING_GCC("-Wuseless-cast") C4_SUPPRESS_WARNING_GCC("-Wattributes") inline char _scalar_code(NodeType masked) { if(masked & (KEY_LITERAL|VAL_LITERAL)) return '|'; if(masked & (KEY_FOLDED|VAL_FOLDED)) return '>'; if(masked & (KEY_SQUO|VAL_SQUO)) return '\''; if(masked & (KEY_DQUO|VAL_DQUO)) return '"'; if(masked & (KEY_PLAIN|VAL_PLAIN)) return '~'; return '@'; } inline char _scalar_code_key(NodeType t) { return _scalar_code(t & KEY_STYLE); } inline char _scalar_code_val(NodeType t) { return _scalar_code(t & VAL_STYLE); } inline char _scalar_code_key(Tree const& p, id_type node) { return _scalar_code_key(p._p(node)->m_type); } inline char _scalar_code_val(Tree const& p, id_type node) { return _scalar_code_val(p._p(node)->m_type); } inline C4_NO_INLINE id_type print_node(Tree const& p, id_type node, int level, id_type count, bool print_children, bool print_address=false) { NodeType type = p.type(node); if(type.is_doc()) { TagDirectiveRange tagds = p.m_tag_directives.lookup_range(node); for(TagDirective const& td : tagds) { printf("%%TAG[%zd] %.*s %.*s [doc=%zu]\n", &td - p.m_tag_directives.m_directives, (int)td.handle.len, td.handle.str, (int)td.prefix.len, td.prefix.str, td.doc_id); } } printf("[%zu]%*s[%zu]", (size_t)count, (2*level), "", (size_t)node); if(print_address) printf(" %p", (void const*)p.get(node)); if(p.is_root(node)) printf(" [ROOT]"); char typebuf[128]; csubstr typestr = type.type_str_sub(typebuf); RYML_CHECK_BASIC_(typestr.str); printf(" %.*s", (int)typestr.len, typestr.str); NodeType ty = p.type(node); if(ty.has_key()) { if(ty.has_key_anchor()) { csubstr ka = p.key_anchor(node); printf(" &%.*s", (int)ka.len, ka.str); } if(ty.has_key_tag()) { csubstr kt = p.key_tag(node); if(kt.begins_with('<')) printf(" %.*s", (int)kt.len, kt.str); else printf(" <%.*s>", (int)kt.len, kt.str); } const char code = _scalar_code_key(p, node); csubstr k = p.key(node); printf(" %c%.*s%c :", code, (int)k.len, k.str, code); } if(ty.has_val_anchor()) { csubstr a = p.val_anchor(node); printf(" &%.*s", (int)a.len, a.str); } if(ty.has_val_tag()) { csubstr vt = p.val_tag(node); if(vt.begins_with('<')) printf(" %.*s", (int)vt.len, vt.str); else printf(" <%.*s>", (int)vt.len, vt.str); } if(ty.has_val()) { const char code = _scalar_code_val(p, node); csubstr v = p.val(node); printf(" %c%.*s%c", code, (int)v.len, v.str, code); } printf(" (%zu sibs)", (size_t)p.num_siblings(node)); ++count; if(!ty.is_container()) { printf("\n"); } else { printf(" (%zu children)\n", (size_t)p.num_children(node)); if(print_children) { for(id_type i = p.first_child(node); i != NONE; i = p.next_sibling(i)) { count = print_node(p, i, level+1, count, print_children); } } } return count; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- inline void print_node(ConstNodeRef const& p, int level=0, bool print_address=false) { print_node(*p.tree(), p.id(), level, 0, true, print_address); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- inline id_type print_tree(const char *message, Tree const& tree, id_type node=NONE, bool print_address=false) { printf("--------------------------------------\n"); if(message != nullptr) printf("%s:\n", message); id_type ret = 0; if(!tree.empty()) { if(node == NONE) node = tree.root_id(); ret = print_node(tree, node, 0, 0, true, print_address); } printf("#nodes=%zu vs #printed=%zu\n", (size_t)tree.size(), (size_t)ret); printf("--------------------------------------\n"); return ret; } inline id_type print_tree(Tree const& p, id_type node=NONE, bool print_address=false) { return print_tree(nullptr, p, node, print_address); } inline void print_tree(ConstNodeRef const& p, int level=0, bool print_address=false) { print_node(p, level, print_address); for(ConstNodeRef ch : p.children()) { print_tree(ch, level+1, print_address); } } C4_SUPPRESS_WARNING_GCC_CLANG_POP } /* namespace yml */ } /* namespace c4 */ // NOLINTEND(modernize-avoid-c-style-cast) #endif /* C4_YML_DETAIL_PRINT_HPP_ */ // (end src/c4/yml/detail/print.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/yml.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_YML_HPP_ #define C4_YML_YML_HPP_ #ifndef C4_YML_VERSION_HPP_ //#include "c4/yml/version.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/version.hpp must have been amalgamated before this point" #endif /* C4_YML_VERSION_HPP_ */ #ifndef C4_YML_TREE_HPP_ //#include "c4/yml/tree.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/tree.hpp must have been amalgamated before this point" #endif /* C4_YML_TREE_HPP_ */ #ifndef C4_YML_NODE_HPP_ //#include "c4/yml/node.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/node.hpp must have been amalgamated before this point" #endif /* C4_YML_NODE_HPP_ */ #ifndef C4_YML_EMIT_HPP_ //#include "c4/yml/emit.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/emit.hpp must have been amalgamated before this point" #endif /* C4_YML_EMIT_HPP_ */ #ifndef C4_YML_EVENT_HANDLER_TREE_HPP_ //#include "c4/yml/event_handler_tree.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/event_handler_tree.hpp must have been amalgamated before this point" #endif /* C4_YML_EVENT_HANDLER_TREE_HPP_ */ #ifndef C4_YML_PARSE_ENGINE_HPP_ //#include "c4/yml/parse_engine.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/parse_engine.hpp must have been amalgamated before this point" #endif /* C4_YML_PARSE_ENGINE_HPP_ */ #ifndef C4_YML_FILTER_PROCESSOR_HPP_ //#include "c4/yml/filter_processor.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/filter_processor.hpp must have been amalgamated before this point" #endif /* C4_YML_FILTER_PROCESSOR_HPP_ */ #ifndef C4_YML_PARSE_HPP_ //#include "c4/yml/parse.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/parse.hpp must have been amalgamated before this point" #endif /* C4_YML_PARSE_HPP_ */ #ifndef C4_YML_REFERENCE_RESOLVER_HPP_ //#include "c4/yml/reference_resolver.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/reference_resolver.hpp must have been amalgamated before this point" #endif /* C4_YML_REFERENCE_RESOLVER_HPP_ */ #ifndef C4_YML_TAG_HPP_ //#include "c4/yml/tag.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/tag.hpp must have been amalgamated before this point" #endif /* C4_YML_TAG_HPP_ */ #endif // C4_YML_YML_HPP_ // (end src/c4/yml/yml.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/ryml.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef RYML_HPP_ #define RYML_HPP_ #ifndef C4_YML_YML_HPP_ //#include "c4/yml/yml.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/yml.hpp must have been amalgamated before this point" #endif /* C4_YML_YML_HPP_ */ namespace ryml { using namespace c4::yml; using namespace c4; } #endif /* RYML_HPP_ */ // (end src/ryml.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/version.cpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifdef RYML_SINGLE_HDR_DEFINE_NOW #ifndef C4_VERSION_HPP_ //#include "c4/version.hpp" // amalgamate: remove include #error "amalgamate: c4/version.hpp must have been amalgamated before this point" #endif /* C4_VERSION_HPP_ */ namespace c4 { const char* version() { return C4CORE_VERSION; } int version_major() { return C4CORE_VERSION_MAJOR; } int version_minor() { return C4CORE_VERSION_MINOR; } int version_patch() { return C4CORE_VERSION_PATCH; } } // namespace c4 #endif /* RYML_SINGLE_HDR_DEFINE_NOW */ // (end ext/c4core.src/c4/version.cpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/language.cpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifdef RYML_SINGLE_HDR_DEFINE_NOW #ifndef C4_LANGUAGE_HPP_ //#include "c4/language.hpp" // amalgamate: remove include #error "amalgamate: c4/language.hpp must have been amalgamated before this point" #endif /* C4_LANGUAGE_HPP_ */ namespace c4 { namespace detail { #ifndef __GNUC__ void use_char_pointer(char const volatile* v) { C4_UNUSED(v); } #else // to avoid empty file warning from the linker C4_MAYBE_UNUSED void foo() {} // NOLINT(misc-use-internal-linkage) #endif } // namespace detail } // namespace c4 #endif /* RYML_SINGLE_HDR_DEFINE_NOW */ // (end ext/c4core.src/c4/language.cpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/memory_util.cpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifdef RYML_SINGLE_HDR_DEFINE_NOW #ifndef C4_MEMORY_UTIL_HPP_ //#include "c4/memory_util.hpp" // amalgamate: remove include #error "amalgamate: c4/memory_util.hpp must have been amalgamated before this point" #endif /* C4_MEMORY_UTIL_HPP_ */ #ifndef C4_ERROR_HPP_ //#include "c4/error.hpp" // amalgamate: remove include #error "amalgamate: c4/error.hpp must have been amalgamated before this point" #endif /* C4_ERROR_HPP_ */ namespace c4 { /** Fills 'dest' with the first 'pattern_size' bytes at 'pattern', 'num_times'. */ void mem_repeat(void* dest, void const* pattern, size_t pattern_size, size_t num_times) { C4_ASSERT( ! mem_overlaps(dest, pattern, num_times*pattern_size, pattern_size)); if C4_UNLIKELY(num_times == 0) return; char *C4_RESTRICT begin = static_cast(dest); char *C4_RESTRICT end = begin + (num_times * pattern_size); // copy the pattern once ::memcpy(begin, pattern, pattern_size); // now copy from dest to itself, doubling up every time size_t n = pattern_size; size_t n2 = n * 2; while(begin + n2 < end) { ::memcpy(begin + n, begin, n); n = n2; n2 *= 2u; } // copy the missing part if(begin + n < end) { ::memcpy(begin + n, begin, static_cast(end - (begin + n))); } } } // namespace c4 #endif /* RYML_SINGLE_HDR_DEFINE_NOW */ // (end ext/c4core.src/c4/memory_util.cpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/format.cpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifdef RYML_SINGLE_HDR_DEFINE_NOW #ifndef C4_FORMAT_HPP_ //#include "c4/format.hpp" // amalgamate: remove include #error "amalgamate: c4/format.hpp must have been amalgamated before this point" #endif /* C4_FORMAT_HPP_ */ #include // for std::align #ifdef __clang__ # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wformat-nonliteral" # pragma clang diagnostic ignored "-Wold-style-cast" #elif defined(__GNUC__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wformat-nonliteral" # pragma GCC diagnostic ignored "-Wold-style-cast" #endif namespace c4 { size_t to_chars(substr buf, fmt::const_raw_wrapper r) { void * vptr = buf.str; size_t space = buf.len; char * ptr = (char*) std::align(r.alignment, r.len, vptr, space); if(ptr == nullptr) { // if it was not possible to align, return a conservative estimate // of the required space return r.alignment + r.len; } C4_CHECK(ptr >= buf.begin() && ptr <= buf.end()); size_t sz = static_cast(ptr - buf.str) + r.len; if(sz <= buf.len) { memcpy(ptr, r.buf, r.len); } return sz; } bool from_chars(csubstr buf, fmt::raw_wrapper *r) { C4_SUPPRESS_WARNING_GCC_WITH_PUSH("-Wcast-qual") void * vptr = (void*)buf.str; C4_SUPPRESS_WARNING_GCC_POP size_t space = buf.len; char * ptr = (char*) std::align(r->alignment, r->len, vptr, space); C4_CHECK(ptr != nullptr); C4_CHECK(ptr >= buf.begin() && ptr <= buf.end()); C4_SUPPRESS_WARNING_GCC_PUSH #if defined(__GNUC__) && __GNUC__ > 9 C4_SUPPRESS_WARNING_GCC("-Wanalyzer-null-argument") #endif memcpy(r->buf, ptr, r->len); C4_SUPPRESS_WARNING_GCC_POP return true; } } // namespace c4 #ifdef __clang__ # pragma clang diagnostic pop #elif defined(__GNUC__) # pragma GCC diagnostic pop #endif #endif /* RYML_SINGLE_HDR_DEFINE_NOW */ // (end ext/c4core.src/c4/format.cpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/utf.cpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifdef RYML_SINGLE_HDR_DEFINE_NOW #ifndef C4_UTF_HPP_ //#include "c4/utf.hpp" // amalgamate: remove include #error "amalgamate: c4/utf.hpp must have been amalgamated before this point" #endif /* C4_UTF_HPP_ */ #ifndef C4_CHARCONV_HPP_ //#include "c4/charconv.hpp" // amalgamate: remove include #error "amalgamate: c4/charconv.hpp must have been amalgamated before this point" #endif /* C4_CHARCONV_HPP_ */ namespace c4 { C4_SUPPRESS_WARNING_GCC_CLANG_WITH_PUSH("-Wold-style-cast") size_t decode_code_point(uint8_t *C4_RESTRICT buf, size_t buflen, const uint32_t code) { C4_ASSERT(buf); C4_ASSERT(buflen >= 4); C4_UNUSED(buflen); if (code <= UINT32_C(0x7f)) { buf[0] = (uint8_t)code; return 1u; } else if(code <= UINT32_C(0x7ff)) { buf[0] = (uint8_t)(UINT32_C(0xc0) | (code >> 6u)); /* 110xxxxx */ buf[1] = (uint8_t)(UINT32_C(0x80) | (code & UINT32_C(0x3f))); /* 10xxxxxx */ return 2u; } else if(code <= UINT32_C(0xffff)) { buf[0] = (uint8_t)(UINT32_C(0xe0) | ((code >> 12u))); /* 1110xxxx */ // NOLINT buf[1] = (uint8_t)(UINT32_C(0x80) | ((code >> 6u) & UINT32_C(0x3f))); /* 10xxxxxx */ buf[2] = (uint8_t)(UINT32_C(0x80) | ((code ) & UINT32_C(0x3f))); /* 10xxxxxx */ // NOLINT return 3u; } else if(code <= UINT32_C(0x10ffff)) { buf[0] = (uint8_t)(UINT32_C(0xf0) | ((code >> 18u))); /* 11110xxx */ // NOLINT buf[1] = (uint8_t)(UINT32_C(0x80) | ((code >> 12u) & UINT32_C(0x3f))); /* 10xxxxxx */ buf[2] = (uint8_t)(UINT32_C(0x80) | ((code >> 6u) & UINT32_C(0x3f))); /* 10xxxxxx */ buf[3] = (uint8_t)(UINT32_C(0x80) | ((code ) & UINT32_C(0x3f))); /* 10xxxxxx */ // NOLINT return 4u; } return 0; } substr decode_code_point(substr out, csubstr code_point) { C4_ASSERT(out.len >= 4); C4_ASSERT(!code_point.begins_with("U+")); C4_ASSERT(!code_point.begins_with("\\x")); C4_ASSERT(!code_point.begins_with("\\u")); C4_ASSERT(!code_point.begins_with("\\U")); C4_ASSERT(!code_point.begins_with('0')); C4_ASSERT(code_point.len <= 8); C4_ASSERT(code_point.len > 0); uint32_t code_point_val; C4_CHECK(read_hex(code_point, &code_point_val)); size_t ret = decode_code_point((uint8_t*)out.str, out.len, code_point_val); C4_ASSERT(ret <= 4); return out.first(ret); } size_t first_non_bom(csubstr s) { #define c4check2_(s, c0, c1) ((s).len >= 2) && (((s).str[0] == (c0)) && ((s).str[1] == (c1))) #define c4check3_(s, c0, c1, c2) ((s).len >= 3) && (((s).str[0] == (c0)) && ((s).str[1] == (c1)) && ((s).str[2] == (c2))) #define c4check4_(s, c0, c1, c2, c3) ((s).len >= 4) && (((s).str[0] == (c0)) && ((s).str[1] == (c1)) && ((s).str[2] == (c2)) && ((s).str[3] == (c3))) // see https://en.wikipedia.org/wiki/Byte_order_mark#Byte-order_marks_by_encoding if(s.len < 2u) return false; else if(c4check3_(s, '\xef', '\xbb', '\xbf')) // UTF-8 return 3u; else if(c4check4_(s, '\x00', '\x00', '\xfe', '\xff')) // UTF-32BE return 4u; else if(c4check4_(s, '\xff', '\xfe', '\x00', '\x00')) // UTF-32LE return 4u; else if(c4check2_(s, '\xfe', '\xff')) // UTF-16BE return 2u; else if(c4check2_(s, '\xff', '\xfe')) // UTF-16BE return 2u; else if(c4check3_(s, '\x2b', '\x2f', '\x76')) // UTF-7 return 3u; else if(c4check3_(s, '\xf7', '\x64', '\x4c')) // UTF-1 return 3u; else if(c4check4_(s, '\xdd', '\x73', '\x66', '\x73')) // UTF-EBCDIC return 4u; else if(c4check3_(s, '\x0e', '\xfe', '\xff')) // SCSU return 3u; else if(c4check3_(s, '\xfb', '\xee', '\x28')) // BOCU-1 return 3u; else if(c4check4_(s, '\x84', '\x31', '\x95', '\x33')) // GB18030 return 4u; return 0u; #undef c4check2_ #undef c4check3_ #undef c4check4_ } substr get_bom(substr s) { return s.first(first_non_bom(s)); } csubstr get_bom(csubstr s) { return s.first(first_non_bom(s)); } substr skip_bom(substr s) { return s.sub(first_non_bom(s)); } csubstr skip_bom(csubstr s) { return s.sub(first_non_bom(s)); } C4_SUPPRESS_WARNING_GCC_CLANG_POP } // namespace c4 #endif /* RYML_SINGLE_HDR_DEFINE_NOW */ // (end ext/c4core.src/c4/utf.cpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/base64.cpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifdef RYML_SINGLE_HDR_DEFINE_NOW #ifndef C4_BASE64_HPP_ //#include "c4/base64.hpp" // amalgamate: remove include #error "amalgamate: c4/base64.hpp must have been amalgamated before this point" #endif #ifndef C4_ERROR_HPP_ //#include "c4/error.hpp" // amalgamate: remove include #error "amalgamate: c4/error.hpp must have been amalgamated before this point" #endif //#include // amalgamate: included above //#include // amalgamate: included above //#include // amalgamate: included above #define C4_PREFER_BSWAP #if defined(C4_PREFER_BSWAP) && C4_LITTLE_ENDIAN && defined(_MSC_VER) //#include // amalgamate: included above #endif C4_SUPPRESS_WARNING_PUSH C4_SUPPRESS_WARNING_GCC("-Wtype-limits") C4_SUPPRESS_WARNING_GCC("-Wuseless-cast") C4_SUPPRESS_WARNING_GCC_CLANG("-Wold-style-cast") C4_SUPPRESS_WARNING_GCC_CLANG("-Wchar-subscripts") // NOLINTBEGIN(bugprone-signed-char-misuse,cert-str34-c,hicpp-signed-bitwise) namespace c4 { namespace { const char base64_sextet_to_char_[64] = { /* 0/ 65*/ 'A', /* 1/ 66*/ 'B', /* 2/ 67*/ 'C', /* 3/ 68*/ 'D', /* 4/ 69*/ 'E', /* 5/ 70*/ 'F', /* 6/ 71*/ 'G', /* 7/ 72*/ 'H', /* 8/ 73*/ 'I', /* 9/ 74*/ 'J', /*10/ 75*/ 'K', /*11/ 74*/ 'L', /*12/ 77*/ 'M', /*13/ 78*/ 'N', /*14/ 79*/ 'O', /*15/ 78*/ 'P', /*16/ 81*/ 'Q', /*17/ 82*/ 'R', /*18/ 83*/ 'S', /*19/ 82*/ 'T', /*20/ 85*/ 'U', /*21/ 86*/ 'V', /*22/ 87*/ 'W', /*23/ 88*/ 'X', /*24/ 89*/ 'Y', /*25/ 90*/ 'Z', /*26/ 97*/ 'a', /*27/ 98*/ 'b', /*28/ 99*/ 'c', /*29/100*/ 'd', /*30/101*/ 'e', /*31/102*/ 'f', /*32/103*/ 'g', /*33/104*/ 'h', /*34/105*/ 'i', /*35/106*/ 'j', /*36/107*/ 'k', /*37/108*/ 'l', /*38/109*/ 'm', /*39/110*/ 'n', /*40/111*/ 'o', /*41/112*/ 'p', /*42/113*/ 'q', /*43/114*/ 'r', /*44/115*/ 's', /*45/116*/ 't', /*46/117*/ 'u', /*47/118*/ 'v', /*48/119*/ 'w', /*49/120*/ 'x', /*50/121*/ 'y', /*51/122*/ 'z', /*52/ 48*/ '0', /*53/ 49*/ '1', /*54/ 50*/ '2', /*55/ 51*/ '3', /*56/ 52*/ '4', /*57/ 53*/ '5', /*58/ 54*/ '6', /*59/ 55*/ '7', /*60/ 56*/ '8', /*61/ 57*/ '9', /*62/ 43*/ '+', /*63/ 47*/ '/', }; using dectype = uint8_t; #define s_ dectype(-1) // undefined below // https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html const dectype base64_char_to_sextet_[128] = { /* 0 NUL*/ s_, /* 1 SOH*/ s_, /* 2 STX*/ s_, /* 3 ETX*/ s_, /* 4 EOT*/ s_, /* 5 ENQ*/ s_, /* 6 ACK*/ s_, /* 7 BEL*/ s_, /* 8 BS */ s_, /* 9 TAB*/ s_, /* 10 LF */ s_, /* 11 VT */ s_, /* 12 FF */ s_, /* 13 CR */ s_, /* 14 SO */ s_, /* 15 SI */ s_, /* 16 DLE*/ s_, /* 17 DC1*/ s_, /* 18 DC2*/ s_, /* 19 DC3*/ s_, /* 20 DC4*/ s_, /* 21 NAK*/ s_, /* 22 SYN*/ s_, /* 23 ETB*/ s_, /* 24 CAN*/ s_, /* 25 EM */ s_, /* 26 SUB*/ s_, /* 27 ESC*/ s_, /* 28 FS */ s_, /* 29 GS */ s_, /* 30 RS */ s_, /* 31 US */ s_, /* 32 SPC*/ s_, /* 33 ! */ s_, /* 34 " */ s_, /* 35 # */ s_, /* 36 $ */ s_, /* 37 % */ s_, /* 38 & */ s_, /* 39 ' */ s_, /* 40 ( */ s_, /* 41 ) */ s_, /* 42 * */ s_, /* 43 + */ 62, /* 44 , */ s_, /* 45 - */ s_, /* 46 . */ s_, /* 47 / */ 63, /* 48 0 */ 52, /* 49 1 */ 53, /* 50 2 */ 54, /* 51 3 */ 55, /* 52 4 */ 56, /* 53 5 */ 57, /* 54 6 */ 58, /* 55 7 */ 59, /* 56 8 */ 60, /* 57 9 */ 61, /* 58 : */ s_, /* 59 ; */ s_, /* 60 < */ s_, /* 61 = */ s_, /* 62 > */ s_, /* 63 ? */ s_, /* 64 @ */ s_, /* 65 A */ 0, /* 66 B */ 1, /* 67 C */ 2, /* 68 D */ 3, /* 69 E */ 4, /* 70 F */ 5, /* 71 G */ 6, /* 72 H */ 7, /* 73 I */ 8, /* 74 J */ 9, /* 75 K */ 10, /* 76 L */ 11, /* 77 M */ 12, /* 78 N */ 13, /* 79 O */ 14, /* 80 P */ 15, /* 81 Q */ 16, /* 82 R */ 17, /* 83 S */ 18, /* 84 T */ 19, /* 85 U */ 20, /* 86 V */ 21, /* 87 W */ 22, /* 88 X */ 23, /* 89 Y */ 24, /* 90 Z */ 25, /* 91 [ */ s_, /* 92 \ */ s_, /* 93 ] */ s_, /* 94 ^ */ s_, /* 95 _ */ s_, /* 96 ` */ s_, /* 97 a */ 26, /* 98 b */ 27, /* 99 c */ 28, /*100 d */ 29, /*101 e */ 30, /*102 f */ 31, /*103 g */ 32, /*104 h */ 33, /*105 i */ 34, /*106 j */ 35, /*107 k */ 36, /*108 l */ 37, /*109 m */ 38, /*110 n */ 39, /*111 o */ 40, /*112 p */ 41, /*113 q */ 42, /*114 r */ 43, /*115 s */ 44, /*116 t */ 45, /*117 u */ 46, /*118 v */ 47, /*119 w */ 48, /*120 x */ 49, /*121 y */ 50, /*122 z */ 51, /*123 { */ s_, /*124 | */ s_, /*125 } */ s_, /*126 ~ */ s_, /*127 DEL*/ s_, }; } // namespace #ifndef NDEBUG namespace detail { C4CORE_EXPORT void base64_test_tables() // NOLINT(*use-internal-linkage*) { for(size_t i = 0; i < C4_COUNTOF(base64_sextet_to_char_); ++i) { char s2c = base64_sextet_to_char_[i]; dectype c2s = base64_char_to_sextet_[(unsigned)s2c]; C4_CHECK((size_t)c2s == i); } for(size_t i = 0; i < C4_COUNTOF(base64_char_to_sextet_); ++i) { dectype c2s = base64_char_to_sextet_[i]; if(c2s == s_) continue; char s2c = base64_sextet_to_char_[(unsigned)c2s]; C4_CHECK((size_t)s2c == i); } } } // namespace detail #endif //----------------------------------------------------------------------------- namespace { #if C4_CPP >= 17 C4_HOT C4_ALWAYS_INLINE bool is_valid_encoded_char_(char c) noexcept { if constexpr (std::is_unsigned_v) return ((c < 128) && (base64_char_to_sextet_[c] != s_)); else return ((c >= 0) && (base64_char_to_sextet_[c] != s_)); } #else // pre c++-17 implementation requires SFINAE template C4_HOT C4_ALWAYS_INLINE auto is_valid_encoded_char_(Char c) noexcept -> typename std::enable_if::value, bool>::type { return ((c < 128) && (base64_char_to_sextet_[c] != s_)); } template C4_HOT C4_ALWAYS_INLINE auto is_valid_encoded_char_(Char c) noexcept -> typename std::enable_if< ! std::is_unsigned::value, bool>::type { return ((c >= 0) && (base64_char_to_sextet_[c] != s_)); } #endif #undef s_ C4_HOT C4_ALWAYS_INLINE bool is_valid_encoded_group4_(const char *C4_RESTRICT c) noexcept { return is_valid_encoded_char_(c[0]) && is_valid_encoded_char_(c[1]) && is_valid_encoded_char_(c[2]) && is_valid_encoded_char_(c[3]); } C4_HOT C4_ALWAYS_INLINE bool is_valid_encoded_group8_(const char *C4_RESTRICT c) noexcept { return is_valid_encoded_char_(c[0]) && is_valid_encoded_char_(c[1]) && is_valid_encoded_char_(c[2]) && is_valid_encoded_char_(c[3]) && is_valid_encoded_char_(c[4]) && is_valid_encoded_char_(c[5]) && is_valid_encoded_char_(c[6]) && is_valid_encoded_char_(c[7]); } #if (C4_WORDSIZE >= 8) C4_HOT C4_ALWAYS_INLINE bool is_valid_encoded_group16_(const char *C4_RESTRICT c, size_t num) noexcept { C4_ASSERT(num >= 16); C4_ASSERT(!(num & 15)); // must be multiple of 16 size_t rem = num; for( ; rem >= 16; rem -= 16, c += 16) if C4_UNLIKELY(!is_valid_encoded_group8_(c) || !is_valid_encoded_group8_(c + 8)) return false; return true; } #endif #ifdef C4_PREFER_BSWAP # if C4_BIG_ENDIAN || (C4_MIXED_ENDIAN \ && defined(__BYTE_ORDER__) \ && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)) # define BSWAP_TO_BIG_ENDIAN64_(x) # define BSWAP_TO_BIG_ENDIAN32_(x) # elif C4_LITTLE_ENDIAN || (C4_MIXED_ENDIAN \ && defined(__BYTE_ORDER__) \ && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) # ifdef _MSC_VER # define BSWAP_TO_BIG_ENDIAN64_(x) (x) = _byteswap_uint64(x) # define BSWAP_TO_BIG_ENDIAN32_(x) (x) = _byteswap_ulong(x) # else # define BSWAP_TO_BIG_ENDIAN64_(x) (x) = __builtin_bswap64(x) # define BSWAP_TO_BIG_ENDIAN32_(x) (x) = __builtin_bswap32(x) # endif # else # error not implemented # endif #endif enum : uint32_t { mask32 = uint32_t((1 << 6u) - 1u) }; // NOLINT #if (C4_WORDSIZE >= 8) enum : uint64_t { mask64 = uint64_t((1 << 6u) - 1u) }; // NOLINT C4_HOT C4_ALWAYS_INLINE void base64_encode_block64_(const uint8_t *C4_RESTRICT const data, char *C4_RESTRICT const encoded) noexcept { #if defined(C4_PREFER_BSWAP) uint64_t val; // MSB -> LSB memcpy(&val, data, sizeof(val)); // |.|.|5|4|3|2|1|0| BSWAP_TO_BIG_ENDIAN64_(val); // |0|1|2|3|4|5|.|.| encoded[0] = base64_sextet_to_char_[(val >> 58) & mask64]; encoded[1] = base64_sextet_to_char_[(val >> 52) & mask64]; encoded[2] = base64_sextet_to_char_[(val >> 46) & mask64]; encoded[3] = base64_sextet_to_char_[(val >> 40) & mask64]; encoded[4] = base64_sextet_to_char_[(val >> 34) & mask64]; encoded[5] = base64_sextet_to_char_[(val >> 28) & mask64]; encoded[6] = base64_sextet_to_char_[(val >> 22) & mask64]; encoded[7] = base64_sextet_to_char_[(val >> 16) & mask64]; #else const uint64_t val = ((uint64_t(data[0]) << 40) | // |.|.|0|1|2|3|4|5| (uint64_t(data[1]) << 32) | (uint64_t(data[2]) << 24) | (uint64_t(data[3]) << 16) | (uint64_t(data[4]) << 8) | (uint64_t(data[5]))); encoded[0] = base64_sextet_to_char_[(val >> 42) & mask64]; encoded[1] = base64_sextet_to_char_[(val >> 36) & mask64]; encoded[2] = base64_sextet_to_char_[(val >> 30) & mask64]; encoded[3] = base64_sextet_to_char_[(val >> 24) & mask64]; encoded[4] = base64_sextet_to_char_[(val >> 18) & mask64]; encoded[5] = base64_sextet_to_char_[(val >> 12) & mask64]; encoded[6] = base64_sextet_to_char_[(val >> 6) & mask64]; encoded[7] = base64_sextet_to_char_[(val ) & mask64]; #endif } #endif C4_HOT void base64_encode_block32_(const uint8_t *C4_RESTRICT const data, char *C4_RESTRICT const encoded) noexcept { #if defined(C4_PREFER_BSWAP) uint32_t val = 0; memcpy(&val, data, sizeof(val)); // MSB: |.|2|1|0| :LSB BSWAP_TO_BIG_ENDIAN32_(val); // MSB: |0|1|2|.| :LSB encoded[0] = base64_sextet_to_char_[(val >> 26) & mask32]; encoded[1] = base64_sextet_to_char_[(val >> 20) & mask32]; encoded[2] = base64_sextet_to_char_[(val >> 14) & mask32]; encoded[3] = base64_sextet_to_char_[(val >> 8) & mask32]; #else // MSB: |.|0|1|2| :LSB const uint32_t val = ((uint32_t(data[0]) << 16) | (uint32_t(data[1]) << 8) | (uint32_t(data[2]))); encoded[0] = base64_sextet_to_char_[(val >> 18) & mask32]; encoded[1] = base64_sextet_to_char_[(val >> 12) & mask32]; encoded[2] = base64_sextet_to_char_[(val >> 6) & mask32]; encoded[3] = base64_sextet_to_char_[(val ) & mask32]; #endif } void base64_encode_block32_term2_(const uint8_t *C4_RESTRICT data, char *C4_RESTRICT encoded) noexcept { // MSB: |.|.|0|1| :LSB const uint32_t val = ((uint32_t(data[0]) << 16) | (uint32_t(data[1]) << 8)); encoded[0] = base64_sextet_to_char_[(val >> 18) & mask32]; encoded[1] = base64_sextet_to_char_[(val >> 12) & mask32]; encoded[2] = base64_sextet_to_char_[(val >> 6) & mask32]; encoded[3] = '='; } void base64_encode_block32_term1_(const uint8_t *C4_RESTRICT data, char *C4_RESTRICT encoded) noexcept { // MSB: |.|.|.|0| :LSB const uint32_t val = ((uint32_t(data[0]) << 16)); encoded[0] = base64_sextet_to_char_[(val >> 18) & mask32]; encoded[1] = base64_sextet_to_char_[(val >> 12) & mask32]; encoded[2] = '='; encoded[3] = '='; } //----------------------------------------------------------------------------- enum : uint32_t { dmask32 = 0xff }; // NOLINT #if (C4_WORDSIZE >= 8) enum : uint64_t { dmask64 = 0xff }; // NOLINT void base64_decode_block64_(const char *C4_RESTRICT encoded, dectype *C4_RESTRICT data) noexcept { uint64_t val = (((uint64_t)base64_char_to_sextet_[encoded[0]]) << 42) | (((uint64_t)base64_char_to_sextet_[encoded[1]]) << 36) | (((uint64_t)base64_char_to_sextet_[encoded[2]]) << 30) | (((uint64_t)base64_char_to_sextet_[encoded[3]]) << 24) | (((uint64_t)base64_char_to_sextet_[encoded[4]]) << 18) | (((uint64_t)base64_char_to_sextet_[encoded[5]]) << 12) | (((uint64_t)base64_char_to_sextet_[encoded[6]]) << 6) | (((uint64_t)base64_char_to_sextet_[encoded[7]]) ); data[0] = (dectype)((val >> 40) & dmask64); data[1] = (dectype)((val >> 32) & dmask64); data[2] = (dectype)((val >> 24) & dmask64); data[3] = (dectype)((val >> 16) & dmask64); data[4] = (dectype)((val >> 8) & dmask64); data[5] = (dectype)((val ) & dmask64); } #endif C4_HOT void base64_decode_block32_(const char *C4_RESTRICT encoded, dectype *C4_RESTRICT data) noexcept { const uint32_t val = (((uint32_t)base64_char_to_sextet_[encoded[0]]) << 18) | (((uint32_t)base64_char_to_sextet_[encoded[1]]) << 12) | (((uint32_t)base64_char_to_sextet_[encoded[2]]) << 6) | (((uint32_t)base64_char_to_sextet_[encoded[3]]) ); data[0] = (dectype)((val >> 16) & dmask32); data[1] = (dectype)((val >> 8) & dmask32); data[2] = (dectype)((val ) & dmask32); } void base64_decode_block32_term1_(const char *C4_RESTRICT encoded, dectype *C4_RESTRICT data) noexcept { const uint32_t val = (((uint32_t)base64_char_to_sextet_[encoded[0]]) << 18) | (((uint32_t)base64_char_to_sextet_[encoded[1]]) << 12); data[0] = (dectype)((val >> 16) & dmask32); } void base64_decode_block32_term2_(const char *C4_RESTRICT encoded, dectype *C4_RESTRICT data) noexcept { const uint32_t val = (((uint32_t)base64_char_to_sextet_[encoded[0]]) << 18) | (((uint32_t)base64_char_to_sextet_[encoded[1]]) << 12) | (((uint32_t)base64_char_to_sextet_[encoded[2]]) << 6); data[0] = (dectype)((val >> 16) & dmask32); data[1] = (dectype)((val >> 8) & dmask32); } } // namespace //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool base64_valid(const char *encoded_, size_t encoded_sz) { if(!encoded_sz) return true; if((encoded_sz & size_t(3u))) // is it not a multiple of 4? return false; const char *C4_RESTRICT encoded = encoded_; size_t i = 0; #if C4_WORDSIZE >= 8 for( ; i + 8 < encoded_sz; i += 8) if(!is_valid_encoded_group8_(encoded + i)) return false; #endif for( ; i + 4 < encoded_sz; i += 4) if(!is_valid_encoded_group4_(encoded + i)) return false; if(!is_valid_encoded_char_(encoded[i]) || !is_valid_encoded_char_(encoded[i + 1])) return false; if(!is_valid_encoded_char_(encoded[i + 2])) return (encoded[i + 2] == '=' && encoded[i + 3] == '='); if(!is_valid_encoded_char_(encoded[i + 3])) return (encoded[i + 3] == '='); return true; } //----------------------------------------------------------------------------- size_t base64_encode(char *encoded_, size_t encoded_sz, const void *data_, size_t data_sz) { C4_ASSERT(encoded_ != nullptr || encoded_sz == 0); C4_ASSERT(data_ != nullptr || data_sz == 0); // ....................... how many groups of 3 bytes to read // .... each group results in 4 bytes written size_t required_sz = ((data_sz + 3 - 1) / 3) * 4; if(encoded_sz < required_sz) return required_sz; size_t rem = data_sz; char *C4_RESTRICT encoded = encoded_; const uint8_t *C4_RESTRICT data = (const uint8_t *) data_; // cast to unsigned to avoid wrapping high-bits #if (C4_WORDSIZE >= 8) for( ; rem >= 15; rem -= 12) // leave 3 at the end (15=12+3) { base64_encode_block64_(data, encoded); data += 6; encoded += 8; base64_encode_block64_(data, encoded); data += 6; encoded += 8; } for( ; rem >= 9; rem -= 6) // leave 3 at the end (9=6+3) { base64_encode_block64_(data, encoded); data += 6; encoded += 8; } #else for( ; rem >= 15; rem -= 12) // leave 3 at the end (15=12+3) { base64_encode_block32_(data, encoded); data += 3; encoded += 4; base64_encode_block32_(data, encoded); data += 3; encoded += 4; base64_encode_block32_(data, encoded); data += 3; encoded += 4; base64_encode_block32_(data, encoded); data += 3; encoded += 4; } for( ; rem >= 9; rem -= 6) // leave 3 at the end (9=6+3) { base64_encode_block32_(data, encoded); data += 3; encoded += 4; base64_encode_block32_(data, encoded); data += 3; encoded += 4; } #endif for( ; rem >= 3; rem -= 3) { base64_encode_block32_(data, encoded); data += 3; encoded += 4; } C4_ASSERT(rem < 3); if(rem == 2) base64_encode_block32_term2_(data, encoded); else if(rem == 1) base64_encode_block32_term1_(data, encoded); return required_sz; } //----------------------------------------------------------------------------- bool base64_decode(char const* encoded_, size_t encoded_sz, void * data_, size_t data_sz, size_t *data_sz_required) { C4_ASSERT(encoded_ != nullptr || encoded_sz == 0); C4_ASSERT(data_ != nullptr || data_sz == 0); C4_ASSERT(data_sz_required != nullptr); if(!encoded_sz) { *data_sz_required = 0; return true; } else if(encoded_sz & 3u) // is encoded_sz not a multiple of 4? { return false; } // compute the required size for the decoded buffer: // ................ how many 4-byte groups of encoded data to decode // .... each group results in 3 decoded bytes *data_sz_required = (encoded_sz / 4) * 3; const char *C4_RESTRICT encoded = encoded_; // account for padded bytes at the end C4_ASSERT(encoded_sz >= 4); if(encoded[encoded_sz - 1] == '=') { C4_ASSERT(*data_sz_required >= 3); if(encoded[encoded_sz - 2] == '=') *data_sz_required -= 2; else *data_sz_required -= 1; } if(data_sz < *data_sz_required) return false; // we have enough room size_t rem = *data_sz_required; // numbytes remaining to write dectype *C4_RESTRICT data = (dectype *)data_; C4_STATIC_ASSERT(sizeof(dectype) == 1); #if (C4_WORDSIZE >= 8) for( ; rem >= 15; rem -= 12) { if C4_UNLIKELY(!is_valid_encoded_group16_(encoded, 16)) return false; base64_decode_block64_(encoded, data); encoded += 8; data += 6; base64_decode_block64_(encoded, data); encoded += 8; data += 6; } for( ; rem >= 9; rem -= 6) { if C4_UNLIKELY(!is_valid_encoded_group8_(encoded)) return false; base64_decode_block64_(encoded, data); encoded += 8; data += 6; } #else for( ; rem >= 9; rem -= 6) { if C4_UNLIKELY(!is_valid_encoded_group8_(encoded)) return false; base64_decode_block32_(encoded, data); encoded += 4; data += 3; base64_decode_block32_(encoded, data); encoded += 4; data += 3; } #endif for( ; rem >= 3; rem -= 3) { if C4_UNLIKELY(!is_valid_encoded_group4_(encoded)) return false; base64_decode_block32_(encoded, data); encoded += 4; data += 3; } C4_ASSERT(rem < 3); // the last quartet requires dealing with padded chars if(rem == 1) // 1 remaining byte, 2 padding chars { if(!is_valid_encoded_char_(encoded[0]) || !is_valid_encoded_char_(encoded[1]) || encoded[2] != '=' || encoded[3] != '=') return false; base64_decode_block32_term1_(encoded, data); } else if(rem == 2) // 2 remaining bytes, 1 padding char { if(!is_valid_encoded_char_(encoded[0]) || !is_valid_encoded_char_(encoded[1]) || !is_valid_encoded_char_(encoded[2]) || encoded[3] != '=') return false; base64_decode_block32_term2_(encoded, data); } return true; } } // namespace c4 // NOLINTEND(bugprone-signed-char-misuse,cert-str34-c,hicpp-signed-bitwise) C4_SUPPRESS_WARNING_POP #endif /* RYML_SINGLE_HDR_DEFINE_NOW */ // (end ext/c4core.src/c4/base64.cpp) #define C4_WINDOWS_POP_HPP_ //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/windows_push.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_WINDOWS_PUSH_HPP_ #define C4_WINDOWS_PUSH_HPP_ /** @file windows_push.hpp sets up macros to include windows header files * without pulling in all of * * @see windows_pop.hpp to undefine these macros * * @see https://aras-p.info/blog/2018/01/12/Minimizing-windows.h/ */ #if defined(_WIN64) || defined(_WIN32) #if defined(_M_AMD64) # ifndef _AMD64_ # define _c4_AMD64_ # define _AMD64_ # endif #elif defined(_M_IX86) # ifndef _X86_ # define _c4_X86_ # define _X86_ # endif #elif defined(_M_ARM64) # ifndef _ARM64_ # define _c4_ARM64_ # define _ARM64_ # endif #elif defined(_M_ARM) # ifndef _ARM_ # define _c4_ARM_ # define _ARM_ # endif #endif #ifndef NOMINMAX # define _c4_NOMINMAX # define NOMINMAX #endif #ifndef NOGDI # define _c4_NOGDI # define NOGDI #endif #ifndef VC_EXTRALEAN # define _c4_VC_EXTRALEAN # define VC_EXTRALEAN #endif #ifndef WIN32_LEAN_AND_MEAN # define _c4_WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN #endif /* If defined, the following flags inhibit definition * of the indicated items. * * NOGDICAPMASKS - CC_*, LC_*, PC_*, CP_*, TC_*, RC_ * NOVIRTUALKEYCODES - VK_* * NOWINMESSAGES - WM_*, EM_*, LB_*, CB_* * NOWINSTYLES - WS_*, CS_*, ES_*, LBS_*, SBS_*, CBS_* * NOSYSMETRICS - SM_* * NOMENUS - MF_* * NOICONS - IDI_* * NOKEYSTATES - MK_* * NOSYSCOMMANDS - SC_* * NORASTEROPS - Binary and Tertiary raster ops * NOSHOWWINDOW - SW_* * OEMRESOURCE - OEM Resource values * NOATOM - Atom Manager routines * NOCLIPBOARD - Clipboard routines * NOCOLOR - Screen colors * NOCTLMGR - Control and Dialog routines * NODRAWTEXT - DrawText() and DT_* * NOGDI - All GDI defines and routines * NOKERNEL - All KERNEL defines and routines * NOUSER - All USER defines and routines * NONLS - All NLS defines and routines * NOMB - MB_* and MessageBox() * NOMEMMGR - GMEM_*, LMEM_*, GHND, LHND, associated routines * NOMETAFILE - typedef METAFILEPICT * NOMINMAX - Macros min(a,b) and max(a,b) * NOMSG - typedef MSG and associated routines * NOOPENFILE - OpenFile(), OemToAnsi, AnsiToOem, and OF_* * NOSCROLL - SB_* and scrolling routines * NOSERVICE - All Service Controller routines, SERVICE_ equates, etc. * NOSOUND - Sound driver routines * NOTEXTMETRIC - typedef TEXTMETRIC and associated routines * NOWH - SetWindowsHook and WH_* * NOWINOFFSETS - GWL_*, GCL_*, associated routines * NOCOMM - COMM driver routines * NOKANJI - Kanji support stuff. * NOHELP - Help engine interface. * NOPROFILER - Profiler interface. * NODEFERWINDOWPOS - DeferWindowPos routines * NOMCX - Modem Configuration Extensions */ #endif /* defined(_WIN64) || defined(_WIN32) */ #endif /* C4_WINDOWS_PUSH_HPP_ */ // (end ext/c4core.src/c4/windows_push.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/windows.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_WINDOWS_HPP_ #define C4_WINDOWS_HPP_ #if defined(_WIN64) || defined(_WIN32) #ifndef C4_WINDOWS_PUSH_HPP_ //#include "c4/windows_push.hpp" // amalgamate: remove include #error "amalgamate: c4/windows_push.hpp must have been amalgamated before this point" #endif /* C4_WINDOWS_PUSH_HPP_ */ #include #ifndef C4_WINDOWS_POP_HPP_ //#include "c4/windows_pop.hpp" // amalgamate: remove include #error "amalgamate: c4/windows_pop.hpp must have been amalgamated before this point" #endif /* C4_WINDOWS_POP_HPP_ */ #endif #endif /* C4_WINDOWS_HPP_ */ // (end ext/c4core.src/c4/windows.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/windows_pop.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_WINDOWS_POP_HPP_ #define C4_WINDOWS_POP_HPP_ #if defined(_WIN64) || defined(_WIN32) #ifdef _c4_AMD64_ # undef _c4_AMD64_ # undef _AMD64_ #endif #ifdef _c4_X86_ # undef _c4_X86_ # undef _X86_ #endif #ifdef _c4_ARM_ # undef _c4_ARM_ # undef _ARM_ #endif #ifdef _c4_NOMINMAX # undef _c4_NOMINMAX # undef NOMINMAX #endif #ifdef NOGDI # undef _c4_NOGDI # undef NOGDI #endif #ifdef VC_EXTRALEAN # undef _c4_VC_EXTRALEAN # undef VC_EXTRALEAN #endif #ifdef WIN32_LEAN_AND_MEAN # undef _c4_WIN32_LEAN_AND_MEAN # undef WIN32_LEAN_AND_MEAN #endif #endif /* defined(_WIN64) || defined(_WIN32) */ #endif /* C4_WINDOWS_POP_HPP_ */ // (end ext/c4core.src/c4/windows_pop.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // ext/c4core.src/c4/error.cpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifdef RYML_SINGLE_HDR_DEFINE_NOW #ifndef C4_ERROR_HPP_ //#include "c4/error.hpp" // amalgamate: remove include #error "amalgamate: c4/error.hpp must have been amalgamated before this point" #endif /* C4_ERROR_HPP_ */ #ifndef C4_LANGUAGE_HPP_ //#include "c4/language.hpp" // amalgamate: remove include #error "amalgamate: c4/language.hpp must have been amalgamated before this point" #endif /* C4_LANGUAGE_HPP_ */ //#include // amalgamate: included above //#include // amalgamate: included above //#include // amalgamate: included above #define C4_LOGF_ERR(...) (void)fprintf(stderr, __VA_ARGS__); (void)fflush(stderr) #define C4_LOGF_WARN(...) (void)fprintf(stderr, __VA_ARGS__); (void)fflush(stderr) #define C4_LOGP(msg, ...) (void)printf(msg) #if defined(C4_XBOX) || (defined(C4_WIN) && defined(C4_MSVC)) #ifndef C4_WINDOWS_HPP_ //# include "c4/windows.hpp" // amalgamate: remove include #error "amalgamate: c4/windows.hpp must have been amalgamated before this point" #endif /* C4_WINDOWS_HPP_ */ #elif defined(C4_PS4) # include #elif defined(C4_UNIX) || defined(C4_LINUX) # include //# include // amalgamate: included above # include #elif defined(C4_MACOS) || defined(C4_IOS) //# include // amalgamate: included above # include # include # include #endif // the amalgamation tool is dumb and was omitting this include under MACOS. // So do it only once: #if defined(C4_UNIX) || defined(C4_LINUX) || defined(C4_MACOS) || defined(C4_IOS) # include #endif #if defined(C4_EXCEPTIONS_ENABLED) && defined(C4_ERROR_THROWS_EXCEPTION) //# include // amalgamate: included above #endif #ifdef __clang__ # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wformat-nonliteral" # pragma clang diagnostic ignored "-Wold-style-cast" #elif defined(__GNUC__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wformat-nonliteral" # pragma GCC diagnostic ignored "-Wold-style-cast" #endif // NOLINTBEGIN(*use-anonymous-namespace*,cert-dcl50-cpp) //----------------------------------------------------------------------------- namespace c4 { static error_flags s_error_flags = ON_ERROR_DEFAULTS; static error_callback_type s_error_callback = nullptr; //----------------------------------------------------------------------------- error_flags get_error_flags() { return s_error_flags; } void set_error_flags(error_flags flags) { s_error_flags = flags; } error_callback_type get_error_callback() { return s_error_callback; } /** Set the function which is called when an error occurs. */ void set_error_callback(error_callback_type cb) { s_error_callback = cb; } //----------------------------------------------------------------------------- void handle_error(srcloc where, const char *fmt, ...) // NOLINT { char buf[1024]; size_t msglen = 0; if(s_error_flags & (ON_ERROR_LOG|ON_ERROR_CALLBACK)) { va_list args; va_start(args, fmt); int ilen = vsnprintf(buf, sizeof(buf), fmt, args); // NOLINT(clang-analyzer-valist.Uninitialized) va_end(args); msglen = ilen >= 0 && ilen < (int)sizeof(buf) ? static_cast(ilen) : sizeof(buf)-1; } if(s_error_flags & ON_ERROR_LOG) { C4_LOGF_ERR("\n"); #if defined(C4_ERROR_SHOWS_FILELINE) && defined(C4_ERROR_SHOWS_FUNC) C4_LOGF_ERR("%s:%d: ERROR: %s\n", where.file, where.line, buf); C4_LOGF_ERR("%s:%d: ERROR here: %s\n", where.file, where.line, where.func); #elif defined(C4_ERROR_SHOWS_FILELINE) C4_LOGF_ERR("%s:%d: ERROR: %s\n", where.file, where.line, buf); #elif ! defined(C4_ERROR_SHOWS_FUNC) (void)where; C4_LOGF_ERR("ERROR: %s\n", buf); #endif } if(s_error_flags & ON_ERROR_CALLBACK) { if(s_error_callback) { s_error_callback(buf, msglen); } } if(s_error_flags & ON_ERROR_THROW) { #if defined(C4_EXCEPTIONS_ENABLED) && defined(C4_ERROR_THROWS_EXCEPTION) throw std::runtime_error(buf); #endif } if(s_error_flags & ON_ERROR_ABORT) { abort(); } abort(); // abort anyway, in case nothing was set C4_UNREACHABLE_AFTER_ERR(); } //----------------------------------------------------------------------------- void handle_warning(srcloc where, const char *fmt, ...) // NOLINT { va_list args; char buf[1024]; va_start(args, fmt); int ret = vsnprintf(buf, sizeof(buf), fmt, args); // NOLINT(clang-analyzer-valist.Uninitialized) if(ret+1 > (int)sizeof(buf)) buf[sizeof(buf) - 1] = '\0'; // truncate else if(ret < 0) buf[0] = '\0'; // output/format error va_end(args); C4_LOGF_WARN("\n"); #if defined(C4_ERROR_SHOWS_FILELINE) && defined(C4_ERROR_SHOWS_FUNC) C4_LOGF_WARN("%s:%d: WARNING: %s\n", where.file, where.line, buf); C4_LOGF_WARN("%s:%d: WARNING: here: %s\n", where.file, where.line, where.func); #elif defined(C4_ERROR_SHOWS_FILELINE) C4_LOGF_WARN("%s:%d: WARNING: %s\n", where.file, where.line, buf); #elif ! defined(C4_ERROR_SHOWS_FUNC) (void)where; C4_LOGF_WARN("WARNING: %s\n", buf); #endif } //----------------------------------------------------------------------------- bool is_debugger_attached() { #if defined(C4_UNIX) || defined(C4_LINUX) static bool first_call = true; static bool first_call_result = false; if(first_call) { first_call = false; C4_SUPPRESS_WARNING_GCC_PUSH #if defined(__GNUC__) && __GNUC__ > 9 C4_SUPPRESS_WARNING_GCC("-Wanalyzer-fd-leak") #endif //! @see http://stackoverflow.com/questions/3596781/how-to-detect-if-the-current-process-is-being-run-by-gdb //! (this answer: http://stackoverflow.com/a/24969863/3968589 ) char buf[1024] = ""; int status_fd = open("/proc/self/status", O_RDONLY); // NOLINT if (status_fd == -1) return false; ssize_t num_read = ::read(status_fd, buf, sizeof(buf)); if (num_read > 0) { static const char TracerPid[] = "TracerPid:"; char *tracer_pid; if(num_read < 1024) buf[num_read] = 0; tracer_pid = strstr(buf, TracerPid); if(tracer_pid) first_call_result = !!::atoi(tracer_pid + sizeof(TracerPid) - 1); // NOLINT } close(status_fd); C4_SUPPRESS_WARNING_GCC_POP } return first_call_result; #elif defined(C4_PS4) return (sceDbgIsDebuggerAttached() != 0); #elif defined(C4_XBOX) || (defined(C4_WIN) && defined(C4_MSVC)) return IsDebuggerPresent() != 0; #elif defined(C4_MACOS) || defined(C4_IOS) // https://stackoverflow.com/questions/2200277/detecting-debugger-on-mac-os-x // Returns true if the current process is being debugged (either // running under the debugger or has a debugger attached post facto). int junk; int mib[4]; struct kinfo_proc info; size_t size; // Initialize the flags so that, if sysctl fails for some bizarre // reason, we get a predictable result. info.kp_proc.p_flag = 0; // Initialize mib, which tells sysctl the info we want, in this case // we're looking for information about a specific process ID. mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PID; mib[3] = getpid(); // Call sysctl. size = sizeof(info); junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0); assert(junk == 0); (void)junk; // We're being debugged if the P_TRACED flag is set. return ((info.kp_proc.p_flag & P_TRACED) != 0); #else return false; #endif } // is_debugger_attached() } // namespace c4 // NOLINTEND(*use-anonymous-namespace*,cert-dcl50-cpp) #ifdef __clang__ # pragma clang diagnostic pop #elif defined(__GNUC__) # pragma GCC diagnostic pop #endif #endif /* RYML_SINGLE_HDR_DEFINE_NOW */ // (end ext/c4core.src/c4/error.cpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/version.cpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifdef RYML_SINGLE_HDR_DEFINE_NOW #ifndef C4_YML_VERSION_HPP_ //#include "c4/yml/version.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/version.hpp must have been amalgamated before this point" #endif /* C4_YML_VERSION_HPP_ */ namespace c4 { namespace yml { csubstr version() { return RYML_VERSION; } int version_major() { return RYML_VERSION_MAJOR; } int version_minor() { return RYML_VERSION_MINOR; } int version_patch() { return RYML_VERSION_PATCH; } } // namespace yml } // namespace c4 #endif /* RYML_SINGLE_HDR_DEFINE_NOW */ // (end src/c4/yml/version.cpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/common.cpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifdef RYML_SINGLE_HDR_DEFINE_NOW #ifndef C4_YML_COMMON_HPP_ //#include "c4/yml/common.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/common.hpp must have been amalgamated before this point" #endif /* C4_YML_COMMON_HPP_ */ #ifndef C4_YML_ERROR_HPP_ //#include "c4/yml/error.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/error.hpp must have been amalgamated before this point" #endif /* C4_YML_ERROR_HPP_ */ #ifndef C4_YML_ERROR_DEF_HPP_ //#include "c4/yml/error.def.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/error.def.hpp must have been amalgamated before this point" #endif /* C4_YML_ERROR_DEF_HPP_ */ #ifndef RYML_NO_DEFAULT_CALLBACKS //# include // amalgamate: included above //# include // amalgamate: included above #endif // RYML_NO_DEFAULT_CALLBACKS #ifdef _RYML_EXCEPTIONS # include #endif namespace c4 { namespace yml { C4_SUPPRESS_WARNING_GCC_CLANG_WITH_PUSH("-Wold-style-cast") C4_SUPPRESS_WARNING_MSVC_WITH_PUSH(4702/*unreachable code*/) // on the call to the unreachable macro namespace { Callbacks s_default_callbacks; #ifndef RYML_NO_DEFAULT_CALLBACKS C4_NO_INLINE void dump2stderr(csubstr s) { // using fwrite() is more portable than using fprintf("%.*s") which // is not available in some embedded platforms if(s.len) fwrite(s.str, 1, s.len, stderr); // NOLINT } C4_NO_INLINE void endmsg() { fputc('\n', stderr); // NOLINT fflush(stderr); // NOLINT } [[noreturn]] C4_NO_INLINE void error_basic_impl(csubstr msg, ErrorDataBasic const& errdata, void * /*user_data*/) { err_basic_format(dump2stderr, msg, errdata); endmsg(); #ifdef RYML_WITH_EXCEPTIONS_ throw ExceptionBasic(msg, errdata); #else abort(); #endif } [[noreturn]] C4_NO_INLINE void error_parse_impl(csubstr msg, ErrorDataParse const& errdata, void * /*user_data*/) { err_parse_format(dump2stderr, msg, errdata); endmsg(); #ifdef RYML_WITH_EXCEPTIONS_ throw ExceptionParse(msg, errdata); #else abort(); #endif } [[noreturn]] C4_NO_INLINE void error_visit_impl(csubstr msg, ErrorDataVisit const& errdata, void * /*user_data*/) { err_visit_format(dump2stderr, msg, errdata); endmsg(); #ifdef RYML_WITH_EXCEPTIONS_ throw ExceptionVisit(msg, errdata); #else abort(); #endif } void* allocate_impl(size_t length, void * /*hint*/, void * /*user_data*/) { void *mem = ::malloc(length); if(mem == nullptr) error_basic_impl("could not allocate memory", ErrorDataBasic{RYML_LOC_HERE()}, nullptr); // LCOV_EXCL_LINE return mem; } void free_impl(void *mem, size_t /*length*/, void * /*user_data*/) { ::free(mem); } #endif // RYML_NO_DEFAULT_CALLBACKS } // anon namespace void set_callbacks(Callbacks const& c) { s_default_callbacks = c; } Callbacks const& get_callbacks() { return s_default_callbacks; } void reset_callbacks() { set_callbacks(Callbacks()); } Callbacks::Callbacks() noexcept : m_user_data(nullptr), #ifndef RYML_NO_DEFAULT_CALLBACKS m_allocate(allocate_impl), m_free(free_impl), m_error_basic(error_basic_impl), m_error_parse(error_parse_impl), m_error_visit(error_visit_impl) #else m_allocate(nullptr), m_free(nullptr), m_error_basic(nullptr), m_error_parse(nullptr), m_error_visit(nullptr) #endif { } Callbacks::Callbacks(void *user_data, pfn_allocate alloc_, pfn_free free_, pfn_error_basic error_basic_) : m_user_data(user_data), #ifndef RYML_NO_DEFAULT_CALLBACKS m_allocate(alloc_ ? alloc_ : allocate_impl), m_free(free_ ? free_ : free_impl), m_error_basic(error_basic_ ? error_basic_ : error_basic_impl), m_error_parse(error_parse_impl), m_error_visit(error_visit_impl) #else m_allocate(alloc_), m_free(free_), m_error_basic(error_basic_), m_error_parse(nullptr), m_error_visit(nullptr) #endif { } Callbacks& Callbacks::set_user_data(void* user_data) { m_user_data = user_data; return *this; } Callbacks& Callbacks::set_allocate(pfn_allocate allocate) { m_allocate = allocate; #ifndef RYML_NO_DEFAULT_CALLBACKS m_allocate = m_allocate ? m_allocate : allocate_impl; #endif return *this; } Callbacks& Callbacks::set_free(pfn_free free) { m_free = free; #ifndef RYML_NO_DEFAULT_CALLBACKS m_free = m_free ? m_free : free_impl; #endif return *this; } Callbacks& Callbacks::set_error_basic(pfn_error_basic error_basic) { m_error_basic = error_basic; #ifndef RYML_NO_DEFAULT_CALLBACKS m_error_basic = m_error_basic ? m_error_basic : error_basic_impl; #endif return *this; } Callbacks& Callbacks::set_error_parse(pfn_error_parse error_parse) { m_error_parse = error_parse; #ifndef RYML_NO_DEFAULT_CALLBACKS m_error_parse = m_error_parse ? m_error_parse : error_parse_impl; #endif return *this; } Callbacks& Callbacks::set_error_visit(pfn_error_visit error_visit) { m_error_visit = error_visit; #ifndef RYML_NO_DEFAULT_CALLBACKS m_error_visit = m_error_visit ? m_error_visit : error_visit_impl; #endif return *this; } C4_NORETURN C4_NO_INLINE void err_basic(ErrorDataBasic const& errdata, const char* msg) { err_basic(get_callbacks(), errdata, msg); C4_UNREACHABLE_AFTER_ERR(); } C4_NORETURN C4_NO_INLINE void err_basic(Callbacks const& callbacks, ErrorDataBasic const& errdata, const char* msg_) { csubstr msg = to_csubstr(msg_); callbacks.m_error_basic(msg, errdata, callbacks.m_user_data); abort(); // the call above should not return, so force it here in case it does // LCOV_EXCL_LINE C4_UNREACHABLE_AFTER_ERR(); } C4_NORETURN C4_NO_INLINE void err_parse(ErrorDataParse const& errdata, const char *msg) { err_parse(get_callbacks(), errdata, msg); C4_UNREACHABLE_AFTER_ERR(); } C4_NORETURN C4_NO_INLINE void err_parse(Callbacks const& callbacks, ErrorDataParse const& errdata, const char *msg_) { csubstr msg = to_csubstr(msg_); if(callbacks.m_error_parse) callbacks.m_error_parse(msg, errdata, callbacks.m_user_data); // fall to basic error if there is no parse handler set else if(callbacks.m_error_basic) callbacks.m_error_basic(msg, errdata.ymlloc, callbacks.m_user_data); abort(); // the call above should not return, so force it here in case it does // LCOV_EXCL_LINE C4_UNREACHABLE_AFTER_ERR(); } C4_NORETURN C4_NO_INLINE void err_visit(ErrorDataVisit const& errdata, const char *msg) { err_visit(get_callbacks(), errdata, msg); C4_UNREACHABLE_AFTER_ERR(); } C4_NORETURN C4_NO_INLINE void err_visit(Callbacks const& callbacks, ErrorDataVisit const& errdata, const char *msg_) { csubstr msg = to_csubstr(msg_); if(callbacks.m_error_visit) callbacks.m_error_visit(msg, errdata, callbacks.m_user_data); // fall to basic error if there is no visit handler set else if(callbacks.m_error_basic) callbacks.m_error_basic(msg, errdata.cpploc, callbacks.m_user_data); abort(); // the call above should not return, so force it here in case it does // LCOV_EXCL_LINE C4_UNREACHABLE_AFTER_ERR(); } #ifdef RYML_WITH_EXCEPTIONS_ ExceptionBasic::ExceptionBasic(csubstr msg_, ErrorDataBasic const& errdata_) noexcept : errdata_basic(errdata_) , msg() { msg[0] = '\0'; if(msg_.len) { if(msg_.len >= sizeof(msg)) { static_assert(sizeof(msg) > 6u, "message buffer too small"); msg_.len = sizeof(msg) - 6u; msg[msg_.len ] = '['; msg[msg_.len + 1u] = '.'; msg[msg_.len + 2u] = '.'; msg[msg_.len + 3u] = '.'; msg[msg_.len + 4u] = ']'; msg[msg_.len + 5u] = '\0'; } memcpy(msg, msg_.str, msg_.len); } } ExceptionParse::ExceptionParse(csubstr msg_, ErrorDataParse const& errdata_) noexcept : ExceptionBasic(msg_, {errdata_.ymlloc}) , errdata_parse(errdata_) { } ExceptionVisit::ExceptionVisit(csubstr msg_, ErrorDataVisit const& errdata_) noexcept : ExceptionBasic(msg_, {errdata_.cpploc}) , errdata_visit(errdata_) { } #endif // RYML_WITH_EXCEPTIONS_ namespace detail { RYML_EXPORT csubstr _get_text_region(csubstr text, size_t pos, size_t num_lines_before, size_t num_lines_after) { if(pos > text.len) return text.last(0); size_t before = text.first(pos).last_of('\n'); size_t before_count = 0; while((before != npos) && (++before_count <= num_lines_before)) { if(before == 0) break; before = text.first(--before).last_of('\n'); } if(before < text.len || before == npos) ++before; size_t after = text.first_of('\n', pos); size_t after_count = 0; while((after != npos) && (++after_count <= num_lines_after)) { ++after; if(after >= text.len) break; after = text.first_of('\n', after); } return before <= after ? text.range(before, after) : text.first(0); } } // namespace detail C4_SUPPRESS_WARNING_MSVC_POP C4_SUPPRESS_WARNING_GCC_CLANG_POP } // namespace yml } // namespace c4 #endif /* RYML_SINGLE_HDR_DEFINE_NOW */ // (end src/c4/yml/common.cpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/node_type.cpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifdef RYML_SINGLE_HDR_DEFINE_NOW #ifndef C4_YML_NODE_TYPE_HPP_ //#include "c4/yml/node_type.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/node_type.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_ERROR_HPP_ //#include "c4/yml/error.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/error.hpp must have been amalgamated before this point" #endif namespace c4 { namespace yml { const char* NodeType::type_str(type_bits ty) noexcept { switch(ty & TYMASK_) { case KEYVAL: return "KEYVAL"; case KEY: return "KEY"; case VAL: return "VAL"; case MAP: return "MAP"; case SEQ: return "SEQ"; case KEYMAP: return "KEYMAP"; case KEYSEQ: return "KEYSEQ"; case DOCSEQ: return "DOCSEQ"; case DOCMAP: return "DOCMAP"; case DOCVAL: return "DOCVAL"; case DOC: return "DOC"; case STREAM: return "STREAM"; case NOTYPE: return "NOTYPE"; default: if((ty & KEYVAL) == KEYVAL) return "KEYVAL***"; if((ty & KEYMAP) == KEYMAP) return "KEYMAP***"; if((ty & KEYSEQ) == KEYSEQ) return "KEYSEQ***"; if((ty & DOCSEQ) == DOCSEQ) return "DOCSEQ***"; if((ty & DOCMAP) == DOCMAP) return "DOCMAP***"; if((ty & DOCVAL) == DOCVAL) return "DOCVAL***"; if(ty & KEY) return "KEY***"; if(ty & VAL) return "VAL***"; if(ty & MAP) return "MAP***"; if(ty & SEQ) return "SEQ***"; if(ty & DOC) return "DOC***"; return "(unk)"; } } namespace { struct type_and_name { const char* str; type_bits bits; }; constexpr const type_and_name type_names[] = { {"STREAM", STREAM}, {"DOC", DOC}, // key properties {"KEY", KEY}, {"KNIL", KEYNIL}, {"KTAG", KEYTAG}, {"KANCH", KEYANCH}, {"KREF", KEYREF}, {"KLITERAL", KEY_LITERAL}, {"KFOLDED", KEY_FOLDED}, {"KSQUO", KEY_SQUO}, {"KDQUO", KEY_DQUO}, {"KPLAIN", KEY_PLAIN}, {"KUNFILT", KEY_UNFILT}, // val properties {"VAL", VAL}, {"VNIL", VALNIL}, {"VTAG", VALTAG}, {"VANCH", VALANCH}, {"VREF", VALREF}, {"VLITERAL", VAL_LITERAL}, {"VFOLDED", VAL_FOLDED}, {"VSQUO", VAL_SQUO}, {"VDQUO", VAL_DQUO}, {"VPLAIN", VAL_PLAIN}, {"VUNFILT", VAL_UNFILT}, // container properties {"MAP", MAP}, {"SEQ", SEQ}, {"FLOWSL", FLOW_SL}, {"FLOWML1", FLOW_ML1}, {"FLOWMLN", FLOW_MLN}, {"FLOWSPC", FLOW_SPC}, {"BLCK", BLOCK}, }; } // namespace size_t NodeType::type_str(substr buf, type_bits flags) noexcept { detail::SubstrWriter_ writer(buf); for(type_and_name const tn : type_names) { if((flags & tn.bits) == tn.bits) { if(writer.pos) writer.append('|'); writer.append(tn.str); flags = flags & ~tn.bits; // remove the flag } } if(!writer.pos) writer.append("NOTYPE"); if(writer.pos < buf.len) buf[writer.pos] = '\0'; return writer.pos; } } // namespace yml } // namespace c4 #endif /* RYML_SINGLE_HDR_DEFINE_NOW */ // (end src/c4/yml/node_type.cpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/tag.cpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifdef RYML_SINGLE_HDR_DEFINE_NOW #ifndef C4_YML_TAG_HPP_ //#include "c4/yml/tag.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/tag.hpp must have been amalgamated before this point" #endif /* C4_YML_TAG_HPP_ */ #ifndef C4_YML_ERROR_HPP_ //#include "c4/yml/error.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/error.hpp must have been amalgamated before this point" #endif /* C4_YML_ERROR_HPP_ */ #ifndef C4_YML_DETAIL_DBGPRINT_HPP_ //#include "c4/yml/detail/dbgprint.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/detail/dbgprint.hpp must have been amalgamated before this point" #endif /* C4_YML_DETAIL_DBGPRINT_HPP_ */ namespace c4 { namespace yml { bool is_custom_tag(csubstr tag) { if((tag.len > 2) && (tag.str[0] == '!')) { size_t pos = tag.find('!', 1); return pos != npos && pos > 1 && tag.str[1] != '<'; } return false; } csubstr normalize_tag(csubstr tag) { YamlTag_e t = to_tag(tag); if(t != TAG_NONE) return from_tag(t); if(tag.begins_with("!<")) tag = tag.sub(1); if(tag.begins_with("'; result = output.first(len); } else { result.str = nullptr; result.len = len; } } return result; } YamlTag_e to_tag(csubstr tag) { if(tag.begins_with("!<")) tag = tag.sub(1); if(tag.begins_with("!!")) { tag = tag.sub(2); } else if(tag.begins_with('!')) { return TAG_NONE; } else { csubstr pfx = ""}; case TAG_OMAP: return {""}; case TAG_PAIRS: return {""}; case TAG_SET: return {""}; case TAG_SEQ: return {""}; case TAG_BINARY: return {""}; case TAG_BOOL: return {""}; case TAG_FLOAT: return {""}; case TAG_INT: return {""}; case TAG_MERGE: return {""}; case TAG_NULL: return {""}; case TAG_STR: return {""}; case TAG_TIMESTAMP: return {""}; case TAG_VALUE: return {""}; case TAG_YAML: return {""}; case TAG_NONE: default: return {""}; } } csubstr from_tag(YamlTag_e tag) { switch(tag) { case TAG_MAP: return {"!!map"}; case TAG_OMAP: return {"!!omap"}; case TAG_PAIRS: return {"!!pairs"}; case TAG_SET: return {"!!set"}; case TAG_SEQ: return {"!!seq"}; case TAG_BINARY: return {"!!binary"}; case TAG_BOOL: return {"!!bool"}; case TAG_FLOAT: return {"!!float"}; case TAG_INT: return {"!!int"}; case TAG_MERGE: return {"!!merge"}; case TAG_NULL: return {"!!null"}; case TAG_STR: return {"!!str"}; case TAG_TIMESTAMP: return {"!!timestamp"}; case TAG_VALUE: return {"!!value"}; case TAG_YAML: return {"!!yaml"}; case TAG_NONE: default: return {""}; } } bool is_valid_tag_handle(csubstr handle) { if(handle.begins_with('!') && handle.ends_with('!')) { _c4dbgpf("handle={}", prs_(handle, true)); csubstr trimmed = handle.sub(1); if(trimmed.ends_with('!')) trimmed = trimmed.offs(0, 1); _c4dbgpf("handle_trimmed={}", prs_(trimmed, true)); // https://yaml.org/spec/1.2.2/#rule-ns-word-char for(char c : trimmed) { bool ok = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '-'; if(!ok) { _c4dbgpf("invalid handle character: '{}'", _c4prc(c)); return false; } } return true; } return false; } namespace { bool is_valid_tag_char(char c) { // https://yaml.org/spec/1.2.2/#691-node-tags bool ok = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); if(!ok) { switch(c) { case '-': case '#': case ';': case '/': case '?': case ':': case '@': case '&': case '=': case '+': case '$': case '_': case '.': case '~': case '*': case '\'': case '(': case ')': case '%': break; default: return false; } } return true; } bool read_hex_char(csubstr suffix, size_t pos, char *out) { // must be succeeded by 2 hex digits if(pos + 3 > suffix.len) return false; suffix = suffix.range(pos + 1, pos + 3); uint8_t val = 0; if C4_UNLIKELY(!read_hex(suffix, &val) || val > 127) return false; *out = static_cast(val); return true; } } // namespace size_t transform_tag(substr output, csubstr handle, csubstr prefix, csubstr tag, Callbacks const& callbacks, Location const& ymlloc, bool with_brackets) { RYML_ASSERT_BASIC_CB_(callbacks, tag.len >= handle.len); RYML_ASSERT_BASIC_CB_(callbacks, !output.overlaps(tag)); RYML_ASSERT_BASIC_CB_(callbacks, prefix.len > 0); csubstr rest = tag.sub(handle.len); _c4dbgpf("%TAG: rest={}", prs_(rest)); size_t rpos = 0, wpos = 0; auto appendstr = [&](csubstr s) { if(s.len && wpos + s.len <= output.len) memcpy(output.str + wpos, s.str, s.len); wpos += s.len; }; auto appendchar = [&](char c) { if(wpos < output.len) output.str[wpos] = c; ++wpos; }; if(with_brackets) appendchar('<'); appendstr(prefix); const char *errmsg = nullptr; for(size_t pos = 0; pos < rest.len; ++pos) { char c = rest.str[pos]; if C4_LIKELY(is_valid_tag_char(c)) { if(c != '%') { continue; } else if(read_hex_char(rest, pos, &c)) { appendstr(rest.range(rpos, pos)); appendchar(c); pos += 2; rpos = pos + 1; continue; } } errmsg = "invalid tag"; goto err; // NOLINT } appendstr(rest.sub(rpos)); if(with_brackets) appendchar('>'); return wpos; err: if(ymlloc) { RYML_ERR_PARSE_CB_(callbacks, ymlloc, errmsg); } else { RYML_ERR_BASIC_CB_(callbacks, errmsg); } } //----------------------------------------------------------------------------- id_type TagDirectives::size() const noexcept { // this assumes we have a very small number of tag directives id_type i = 0; for(; i < RYML_MAX_TAG_DIRECTIVES; ++i) if(m_directives[i].handle.empty()) break; return i; } TagDirective const* TagDirectives::add(csubstr handle, csubstr prefix, id_type doc_id) noexcept { id_type pos = size(); TagDirective *C4_RESTRICT td = nullptr; if(pos < RYML_MAX_TAG_DIRECTIVES) { td = &m_directives[pos]; td->handle = handle; td->prefix = prefix; td->doc_id = doc_id; _c4dbgpf("tagd[{}]: added! handle={} prefix={} doc={}", pos, td->handle, td->prefix, td->doc_id); } return td; } void TagDirectives::clear() noexcept { for(TagDirective &td : m_directives) { td.handle = {}; td.prefix = {}; td.doc_id = NONE; } } TagDirectiveRange TagDirectives::lookup_range(id_type doc_id) const noexcept { TagDirective const* first = nullptr; TagDirective const* last = nullptr; for(id_type i = 0; i < RYML_MAX_TAG_DIRECTIVES; ++i) { TagDirective const& C4_RESTRICT td = m_directives[i]; if(doc_id == td.doc_id) { first = m_directives + i; break; } else if(td.handle.empty()) { break; } } if(first) { last = m_directives + RYML_MAX_TAG_DIRECTIVES; for(TagDirective const* C4_RESTRICT td = first; td < last; ++td) { if(doc_id != td->doc_id || td->handle.empty()) { last = td; break; } } } else { first = last = m_directives; } return TagDirectiveRange{first, last}; } TagDirective const* TagDirectives::lookup(csubstr tag, id_type doc_id) const noexcept { _c4dbgpf("tagd: searching for {}, doc_id={}", prs_(tag), doc_id); for(id_type i = 0; i < RYML_MAX_TAG_DIRECTIVES; ++i) { TagDirective const& C4_RESTRICT td = m_directives[i]; if(td.handle.empty()) { continue; } _c4dbgpf("tagd[{}]: handle={} prefix={} doc_id={}", i, td.handle, td.prefix, td.doc_id); if(tag.begins_with(td.handle)) { if(td.handle == '!' && ( tag.begins_with("!!") || tag.begins_with('<') || tag.begins_with("!<") || is_custom_tag(tag))) continue; _c4dbgpf("tagd[{}]: matches handle!", i); if(doc_id == td.doc_id) { _c4dbgpf("tagd[{}]: matches doc={}!", i, doc_id); return &td; } } } return nullptr; } csubstr TagDirectives::resolve(substr buf, size_t *bufsz, csubstr tag, id_type id, Location const& ymlloc, Callbacks const& callbacks, bool with_brackets) const { RYML_ASSERT_BASIC_CB_(callbacks, !buf.overlaps(tag)); TagDirective const* C4_RESTRICT td = lookup(tag, id); *bufsz = 0; csubstr handle, prefix, ret; const char *errmsg = nullptr; size_t len; if(td) { handle = td->handle; prefix = td->prefix; } else { _c4dbgp("tagd: no directive found"); if(tag.begins_with('<')) { _c4dbgp("tagd: already resolved"); if C4_UNLIKELY(!tag.ends_with('>')) { errmsg = "malformed tag"; goto err; // NOLINT } return tag; } else if(tag.begins_with("!<")) { _c4dbgp("tagd: already resolved"); if C4_UNLIKELY(!tag.ends_with('>')) { errmsg = "malformed tag"; goto err; // NOLINT } return tag.sub(1); } else if(tag.begins_with("!!")) { _c4dbgp("tagd: !!"); YamlTag_e tagenum = to_tag(tag); if(tagenum != TAG_NONE) { _c4dbgpf("tagd: standard tag: {} -> {}", tag, from_tag_long(tagenum)); tag = from_tag_long(tagenum); return with_brackets ? tag : tag.offs(1, 1); } handle = "!!"; prefix = "tag:yaml.org,2002:"; } else if C4_UNLIKELY(is_custom_tag(tag)) { _c4dbgp("tagd: custom_tag"); _c4dbgpf("tag '{}' at id={}: no matching directive was found", tag, id); errmsg = "tag without matching directive"; goto err; // NOLINT } else { _c4dbgp("tagd: !"); handle = prefix = "!"; } } len = transform_tag(buf, handle, prefix, tag, callbacks, ymlloc, with_brackets); *bufsz = len; if(len <= buf.len) { ret = buf.first(len); } else { _c4dbgp("tagd: not enough room"); ret.str = nullptr; ret.len = len; } return ret; err: if(ymlloc) { RYML_ERR_PARSE_CB_(callbacks, ymlloc, errmsg); } else { RYML_ERR_BASIC_CB_(callbacks, errmsg); } } //----------------------------------------------------------------------------- TagCache::LookupResult TagCache::find(csubstr tag, id_type doc_id, id_type linear_threshold) const noexcept { LookupResult ret = {}; id_type sz = m_entries.size(); if(sz < linear_threshold) // do a linear search on small size { for(size_t i = 0; i < sz; ++i) { Entry const& C4_RESTRICT e = m_entries[i]; if(e.tag == tag && e.doc_id == doc_id) { ret.resolved = e.resolved; ret.pos = i; return ret; } else if(e.tag > tag || ((e.tag == tag) && e.doc_id > doc_id)) { ret.pos = i; return ret; } } ret.pos = sz; } else // do a binary search on larger size { id_type first = 0; id_type count = sz; while(count) { id_type halfsz = count / id_type(2); // NOLINT(*avoid-c-style-cast) id_type mid = first + halfsz; RYML_ASSERT_BASIC_CB_(m_entries.m_callbacks, mid < sz); Entry const& C4_RESTRICT e = m_entries[mid]; if(e.tag < tag || (e.tag == tag && e.doc_id < doc_id)) { first = mid + 1; RYML_ASSERT_BASIC_CB_(m_entries.m_callbacks, count >= halfsz + 1); count -= halfsz + 1; } else { count = halfsz; } } ret.pos = first; if(first < sz) { Entry const& C4_RESTRICT e = m_entries[first]; if(e.tag == tag && e.doc_id == doc_id) { ret.resolved = m_entries[first].resolved; } } } return ret; } void TagCache::add(csubstr tag, csubstr resolved, id_type doc_id, const_iterator pos) RYML_NOEXCEPT { const id_type sz = m_entries.size(); RYML_ASSERT_BASIC_CB_(m_entries.m_callbacks, pos <= sz); RYML_ASSERT_BASIC_CB_(m_entries.m_callbacks, pos == sz || tag < m_entries[pos].tag || (tag == m_entries[pos].tag && doc_id < m_entries[pos].doc_id)); m_entries.resize(sz + 1); if(pos < sz) memmove(m_entries.m_stack + pos + 1, m_entries.m_stack + pos, (sz - pos) * sizeof(Entry)); m_entries.m_stack[pos].tag = tag; m_entries.m_stack[pos].resolved = resolved; m_entries.m_stack[pos].doc_id = doc_id; _c4dbgpf("tagcache: add entry @pos={}: docid={} {} -> {}", pos, doc_id, tag, maybe_null_str_(resolved)); } } // namespace yml } // namespace c4 #endif /* RYML_SINGLE_HDR_DEFINE_NOW */ // (end src/c4/yml/tag.cpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/parse_engine.def.hpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifndef C4_YML_PARSE_ENGINE_DEF_HPP_ #define C4_YML_PARSE_ENGINE_DEF_HPP_ #ifndef C4_YML_PARSE_ENGINE_HPP_ //#include "c4/yml/parse_engine.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/parse_engine.hpp must have been amalgamated before this point" #endif #ifndef C4_CHARCONV_HPP_ //#include "c4/charconv.hpp" // amalgamate: remove include #error "amalgamate: c4/charconv.hpp must have been amalgamated before this point" #endif #ifndef C4_UTF_HPP_ //#include "c4/utf.hpp" // amalgamate: remove include #error "amalgamate: c4/utf.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_FILTER_PROCESSOR_HPP_ //#include "c4/yml/filter_processor.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/filter_processor.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_TAG_HPP_ //#include "c4/yml/tag.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/tag.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_NODE_TYPE_HPP_ //#include "c4/yml/node_type.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/node_type.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_DETAIL_DBGPRINT_HPP_ //#include "c4/yml/detail/dbgprint.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/detail/dbgprint.hpp must have been amalgamated before this point" #endif #ifdef RYML_DBG #ifndef C4_DUMP_HPP_ //#include // amalgamate: remove include #error "amalgamate: c4/dump.hpp must have been amalgamated before this point" #endif #define _c4err(...) \ do { RYML_DEBUG_BREAK(); this->_err(RYML_LOC_HERE(), __VA_ARGS__); } while(0) #else #define _c4err(...) \ this->_err(RYML_LOC_HERE(), __VA_ARGS__) #endif #define _c4assert(...) \ RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, __VA_ARGS__, m_evt_handler->m_curr->pos) #if defined(RYML_WITH_TAB_TOKENS) #define RYML_WITH_TAB_TOKENS_(...) __VA_ARGS__ #define RYML_WITHOUT_TAB_TOKENS_(...) #define RYML_WITH_OR_WITHOUT_TAB_TOKENS_(with, without) with #else #define RYML_WITH_TAB_TOKENS_(...) #define RYML_WITHOUT_TAB_TOKENS_(...) __VA_ARGS__ #define RYML_WITH_OR_WITHOUT_TAB_TOKENS_(with, without) without #endif // scaffold: #define _c4dbgnextline() \ do { \ _c4dbgq("\n-----------"); \ _c4dbgt("handling line={}, offset={}B", \ m_evt_handler->m_curr->pos.line, \ m_evt_handler->m_curr->pos.offset); \ } while(0) C4_SUPPRESS_WARNING_MSVC_PUSH C4_SUPPRESS_WARNING_MSVC(4296) // expression is always 'boolean_value' C4_SUPPRESS_WARNING_MSVC(4702) // unreachable code C4_SUPPRESS_WARNING_GCC_CLANG_PUSH C4_SUPPRESS_WARNING_GCC_CLANG("-Wtype-limits") // to remove a warning on an assertion that a size_t >= 0. Later on, this size_t will turn into a template argument, and then it can become < 0. C4_SUPPRESS_WARNING_GCC_CLANG("-Wformat-nonliteral") C4_SUPPRESS_WARNING_GCC_CLANG("-Wold-style-cast") #if defined(__GNUC__) && (__GNUC__ >= 6) C4_SUPPRESS_WARNING_GCC("-Wnull-dereference") #endif #if defined(__GNUC__) && (__GNUC__ >= 7) C4_SUPPRESS_WARNING_GCC("-Wduplicated-branches") #endif // NOLINTBEGIN(hicpp-signed-bitwise,cppcoreguidelines-avoid-goto,hicpp-avoid-goto,hicpp-multiway-paths-covered,modernize-avoid-c-style-cast) namespace c4 { namespace yml { namespace { // NOLINT C4_HOT C4_ALWAYS_INLINE void _set_first(substr &C4_RESTRICT subject, size_t pos) noexcept { // avoids reassigning the ptr in substr subject.len = pos != npos ? pos : subject.len; } C4_HOT C4_ALWAYS_INLINE void _set_first(csubstr &C4_RESTRICT subject, size_t pos) noexcept { // avoids reassigning the ptr in substr subject.len = pos != npos ? pos : subject.len; } C4_HOT C4_ALWAYS_INLINE void _set_first_strict(substr &C4_RESTRICT subject, size_t pos) RYML_NOEXCEPT { // avoids reassigning the ptr in substr RYML_ASSERT_BASIC_(pos != npos); // LCOV_EXCL_LINE subject.len = pos; } C4_HOT C4_ALWAYS_INLINE void _set_first_strict(csubstr &C4_RESTRICT subject, size_t pos) RYML_NOEXCEPT { // avoids reassigning the ptr in substr RYML_ASSERT_BASIC_(pos != npos); // LCOV_EXCL_LINE subject.len = pos; } C4_HOT C4_ALWAYS_INLINE bool _is_blck_token(csubstr s) RYML_NOEXCEPT { RYML_ASSERT_BASIC_(s.len > 0); RYML_ASSERT_BASIC_(s.str[0] == '-' || s.str[0] == ':' || s.str[0] == '?'); return ((s.len == 1) || ((s.str[1] == ' ') RYML_WITH_TAB_TOKENS_( || (s.str[1] == '\t')))); } C4_HOT C4_ALWAYS_INLINE bool _is_blck_seq_token_maybe(csubstr const& C4_RESTRICT s) noexcept { return ((s.len >= 1) && (s.str[0] == '-') && ((s.len == 1) || ((s.str[1] == ' ') RYML_WITH_TAB_TOKENS_( || (s.str[1] == '\t'))))); } inline bool _is_doc_begin_token(csubstr s) RYML_NOEXCEPT { RYML_ASSERT_BASIC_(s.begins_with('-')); RYML_ASSERT_BASIC_(!s.ends_with("\n")); RYML_ASSERT_BASIC_(!s.ends_with("\r")); return (s.len >= 3 && s.str[1] == '-' && s.str[2] == '-') && (s.len == 3 || (s.str[3] == ' ' RYML_WITH_TAB_TOKENS_(|| s.str[3] == '\t'))); } inline bool _is_doc_end_token(csubstr s) RYML_NOEXCEPT { RYML_ASSERT_BASIC_(s.begins_with('.')); RYML_ASSERT_BASIC_(!s.ends_with("\n")); RYML_ASSERT_BASIC_(!s.ends_with("\r")); return (s.len >= 3 && s.str[1] == '.' && s.str[2] == '.') && (s.len == 3 || (s.str[3] == ' ' RYML_WITH_TAB_TOKENS_(|| s.str[3] == '\t'))); } inline bool _is_doc_token(csubstr s) noexcept { if(s.len >= 3) { switch(s.str[0]) { case '-': //return _is_doc_begin_token(s); // this was failing with gcc -O2 return (s.str[1] == '-' && s.str[2] == '-') && (s.len == 3 || (s.str[3] == ' ' RYML_WITH_TAB_TOKENS_(|| s.str[3] == '\t'))); case '.': //return _is_doc_end_token(s); // this was failing with gcc -O2 return (s.str[1] == '.' && s.str[2] == '.') && (s.len == 3 || (s.str[3] == ' ' RYML_WITH_TAB_TOKENS_(|| s.str[3] == '\t'))); } } return false; } inline size_t _begins_with_special_json_scalar(csubstr s) RYML_NOEXCEPT { RYML_ASSERT_BASIC_(s.len); switch(s.str[0]) { case 'f': return s.begins_with("false") ? 5u : 0u; case 't': return s.begins_with("true") ? 4u : 0u; case 'n': return s.begins_with("null") ? 4u : 0u; } return 0u; } //----------------------------------------------------------------------------- C4_ALWAYS_INLINE size_t _extend_from_combined_newline(char nl, char following) { return (nl == '\n' && following == '\r') || (nl == '\r' && following == '\n'); } //! look for the next newline chars, and jump to the right of those inline substr _from_next_line(substr rem) { size_t nlpos = rem.first_of("\r\n"); if(nlpos == csubstr::npos) return {}; const char nl = rem[nlpos]; rem = rem.right_of(nlpos); if(rem.empty()) return {}; if(_extend_from_combined_newline(nl, rem.front())) rem = rem.sub(1); return rem; } //----------------------------------------------------------------------------- inline size_t _count_following_newlines(csubstr r, size_t *C4_RESTRICT i) { RYML_ASSERT_BASIC_(r[*i] == '\n'); size_t numnl_following = 0; ++(*i); for( ; *i < r.len; ++(*i)) { if(r.str[*i] == '\n') ++numnl_following; // skip leading whitespace else if(r.str[*i] == ' ' || r.str[*i] == '\t' || r.str[*i] == '\r') ; else break; } return numnl_following; } /** @p i is set to the first non whitespace character after the line * @return the number of empty lines after the initial position */ inline size_t _count_following_newlines(csubstr r, size_t *C4_RESTRICT i, size_t indentation) { RYML_ASSERT_BASIC_(r[*i] == '\n'); size_t numnl_following = 0; ++(*i); if(indentation == 0) { for( ; *i < r.len; ++(*i)) { const char c = r.str[*i]; if(c == '\n') ++numnl_following; // skip leading whitespace else if(c != ' ' && c != '\t' && c != '\r') break; } } else { for( ; *i < r.len; ++(*i)) { char c = r.str[*i]; if(c == '\n') { ++numnl_following; // skip the indentation after the newline size_t stop = *i + indentation; for( ; *i < r.len; ++(*i)) { c = r.str[*i]; if(c != ' ' && c != '\r') break; RYML_ASSERT_BASIC_(*i < stop); // LCOV_EXCL_LINE } C4_UNUSED(stop); } // skip leading whitespace else if(c != ' ' && c != '\t' && c != '\r') { break; } } } return numnl_following; } } // anon namespace //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- template ParseEngine::~ParseEngine() noexcept { _free(); _clr(); } template ParseEngine::ParseEngine(EventHandler *evt_handler, ParserOptions const& opts) : m_options(opts) , m_evt_handler(evt_handler) , m_pending_anchors() , m_pending_tags() , m_has_directives_yaml(false) , m_has_directives(false) , m_doc_empty(true) , m_prev_colon(npos) , m_prev_val_end(npos) , m_encoding(NOBOM) , m_newline_offsets() , m_newline_offsets_size(0) , m_newline_offsets_capacity(0) { RYML_CHECK_BASIC_(evt_handler); } template ParseEngine::ParseEngine(ParseEngine &&that) noexcept : m_options(that.m_options) , m_evt_handler(that.m_evt_handler) , m_pending_anchors(that.m_pending_anchors) , m_pending_tags(that.m_pending_tags) , m_has_directives_yaml(that.m_has_directives_yaml) , m_has_directives(that.m_has_directives) , m_doc_empty(that.m_doc_empty) , m_prev_colon(npos) , m_prev_val_end(npos) , m_encoding(NOBOM) , m_newline_offsets(that.m_newline_offsets) , m_newline_offsets_size(that.m_newline_offsets_size) , m_newline_offsets_capacity(that.m_newline_offsets_capacity) { that._clr(); } template ParseEngine::ParseEngine(ParseEngine const& that) : m_options(that.m_options) , m_evt_handler(that.m_evt_handler) , m_pending_anchors(that.m_pending_anchors) , m_pending_tags(that.m_pending_tags) , m_has_directives_yaml(that.m_has_directives_yaml) , m_has_directives(that.m_has_directives) , m_doc_empty(that.m_doc_empty) , m_prev_colon(npos) , m_prev_val_end(npos) , m_encoding(NOBOM) , m_newline_offsets() , m_newline_offsets_size() , m_newline_offsets_capacity() { if(that.m_newline_offsets_capacity) { _resize_locations(that.m_newline_offsets_capacity); RYML_CHECK_BASIC_CB_(m_evt_handler->m_stack.m_callbacks, m_newline_offsets_capacity == that.m_newline_offsets_capacity); memcpy(m_newline_offsets, that.m_newline_offsets, that.m_newline_offsets_size * sizeof(size_t)); m_newline_offsets_size = that.m_newline_offsets_size; } } template ParseEngine& ParseEngine::operator=(ParseEngine &&that) noexcept { _free(); m_options = (that.m_options); m_evt_handler = that.m_evt_handler; m_pending_anchors = that.m_pending_anchors; m_pending_tags = that.m_pending_tags; m_has_directives_yaml = that.m_has_directives_yaml; m_has_directives = that.m_has_directives; m_doc_empty = that.m_doc_empty; m_prev_colon = that.m_prev_colon; m_prev_val_end = that.m_prev_val_end; m_encoding = that.m_encoding; m_newline_offsets = (that.m_newline_offsets); m_newline_offsets_size = (that.m_newline_offsets_size); m_newline_offsets_capacity = (that.m_newline_offsets_capacity); that._clr(); return *this; } template ParseEngine& ParseEngine::operator=(ParseEngine const& that) { if(&that != this) { _free(); m_options = (that.m_options); m_evt_handler = that.m_evt_handler; m_pending_anchors = that.m_pending_anchors; m_pending_tags = that.m_pending_tags; m_has_directives_yaml = that.m_has_directives_yaml; m_has_directives = that.m_has_directives; m_doc_empty = that.m_doc_empty; m_prev_colon = that.m_prev_colon; m_prev_val_end = that.m_prev_val_end; m_encoding = that.m_encoding; if(that.m_newline_offsets_capacity > m_newline_offsets_capacity) _resize_locations(that.m_newline_offsets_capacity); RYML_CHECK_BASIC_CB_(m_evt_handler->m_stack.m_callbacks, m_newline_offsets_capacity >= that.m_newline_offsets_capacity); RYML_CHECK_BASIC_CB_(m_evt_handler->m_stack.m_callbacks, m_newline_offsets_capacity >= that.m_newline_offsets_size); memcpy(m_newline_offsets, that.m_newline_offsets, that.m_newline_offsets_size * sizeof(size_t)); m_newline_offsets_size = that.m_newline_offsets_size; } return *this; } template void ParseEngine::_clr() { m_options = {}; m_evt_handler = {}; m_pending_anchors = {}; m_pending_tags = {}; m_has_directives_yaml = false; m_has_directives = false; m_doc_empty = true; m_prev_colon = npos; m_prev_val_end = npos; m_encoding = NOBOM; m_newline_offsets = {}; m_newline_offsets_size = {}; m_newline_offsets_capacity = {}; } template void ParseEngine::_free() { if(m_newline_offsets) { RYML_CB_FREE_(m_evt_handler->m_stack.m_callbacks, m_newline_offsets, size_t, m_newline_offsets_capacity); m_newline_offsets = nullptr; m_newline_offsets_size = 0u; m_newline_offsets_capacity = 0u; } } //----------------------------------------------------------------------------- template void ParseEngine::_reset() { m_pending_anchors = {}; m_pending_tags = {}; m_has_directives_yaml = false; m_has_directives = false; m_doc_empty = true; m_prev_colon = npos; m_prev_val_end = npos; m_bom_len = 0; m_encoding = NOBOM; m_bom_line = 0; if(m_options.locations()) { _prepare_locations(); } } //----------------------------------------------------------------------------- template void ParseEngine::_relocate_arena(csubstr prev_arena, substr next_arena, substr *other) { _c4dbgp("relocate to new arena"); const char *pb = prev_arena.str; const char *pe = prev_arena.str + prev_arena.len; #define _ryml_relocate(s) \ if((s).str >= pb && (s).str <= pe) \ { \ (s).str = next_arena.str + ((s).str - pb); \ } \ ((void)0) for(ParserState &st : m_evt_handler->m_stack) { _ryml_relocate(st.line_contents.rem); _ryml_relocate(st.line_contents.full); } _ryml_relocate(m_evt_handler->m_src); for(size_t i = 0; i < m_pending_tags.num_entries; ++i) { _ryml_relocate(m_pending_tags.annotations[i].str); // LCOV_EXCL_LINE _ryml_relocate(m_pending_tags.annotations[i].orig); // LCOV_EXCL_LINE } for(size_t i = 0; i < m_pending_anchors.num_entries; ++i) { _ryml_relocate(m_pending_anchors.annotations[i].str); _ryml_relocate(m_pending_anchors.annotations[i].orig); } { TagDirectives &tds = m_evt_handler->tag_directives(); for(size_t i = 0, sz = tds.size(); i < sz; ++i) { _ryml_relocate(tds.m_directives[i].handle); _ryml_relocate(tds.m_directives[i].prefix); } } { TagCache &tch = m_evt_handler->tag_cache(); for(id_type i = 0, sz = tch.m_entries.size(); i < sz; ++i) { _ryml_relocate(tch.m_entries[i].tag); _ryml_relocate(tch.m_entries[i].resolved); } } if(other) { _ryml_relocate(*other); } #undef _ryml_relocate } /** @cond dev */ template substr ParseEngine::_alloc_arena(size_t len, substr *other) { csubstr prev = m_evt_handler->arena(); substr out = m_evt_handler->alloc_arena(len); substr curr = m_evt_handler->arena(); if(curr.str != prev.str) _relocate_arena(prev, curr, other); return out; } /** @endcond */ //----------------------------------------------------------------------------- #ifdef RYML_DBG template template C4_NO_INLINE void ParseEngine::_fmt_msg(DumpFn &&dumpfn) const { ParserState const *const C4_RESTRICT st = m_evt_handler->m_curr; LineContents const& C4_RESTRICT lc = st->line_contents; csubstr contents = lc.full.first(lc.num_cols); if(contents.len) { // print the yaml src line size_t offs = 3u + to_chars(substr{}, st->pos.line) + to_chars(substr{}, st->pos.col); csubstr m_file = m_evt_handler->m_curr->pos.name; if(m_file.len) { dbg_dump_(std::forward(dumpfn), "{}:", m_file); offs += m_file.len + 1; } dbg_dump_(std::forward(dumpfn), "{}:{}: ", st->pos.line, st->pos.col); csubstr maybe_full_content = (contents.len < 80u ? contents : contents.first(80u)); csubstr maybe_ellipsis = (contents.len < 80u ? csubstr{} : csubstr("...")); dbg_dump_(std::forward(dumpfn), "{}{} (size={})\n", escaped_scalar(maybe_full_content, /*escape*/true), maybe_ellipsis, contents.len); // highlight the remaining portion of the previous line size_t firstcol = (size_t)(lc.rem.str - lc.full.str); size_t lastcol = firstcol + lc.rem.len; size_t firstcol_adj = adjust_pos_with_escapes(lc.full, firstcol); size_t len = adjust_pos_with_escapes(lc.rem, lc.rem.len); for(size_t i = 0; i < offs + firstcol_adj; ++i) std::forward(dumpfn)(" "); std::forward(dumpfn)("^"); for(size_t i = 1, e = (len < 80u ? len : 80u); i < e; ++i) std::forward(dumpfn)("~"); dbg_dump_(std::forward(dumpfn), "{} (cols {}-{})\n", maybe_ellipsis, firstcol+1, lastcol+1); } else { std::forward(dumpfn)("\n"); } // next line: print the state flags { char flagbuf_[128]; dbg_dump_(std::forward(dumpfn), "top state: {}\n", detail::_parser_flags_to_str(flagbuf_, m_evt_handler->m_curr->flags)); } } template void ParseEngine::_print_state_stack(substr buf) const { if(dbg_enabled_()) { for(ParserState const& s : m_evt_handler->m_stack) dbg_printf_("state[{}]: ind={} node={} flags={}\n", s.level, s.indref, s.node_id, detail::_parser_flags_to_str(buf, s.flags)); } } template void ParseEngine::_print_state_stack() const { char buf[128]; _print_state_stack(buf); } #endif //----------------------------------------------------------------------------- template template C4_NORETURN C4_NO_INLINE void ParseEngine::_err(Location const& cpploc, Location const& ymlloc, const char* fmt, Args const& ...args) const { m_evt_handler->cancel_parse(); err_parse(m_evt_handler->m_stack.m_callbacks, ErrorDataParse{cpploc, ymlloc}, fmt, args...); } template template C4_NORETURN C4_NO_INLINE void ParseEngine::_err(Location const& cpploc, const char *fmt, Args const& ...args) const { m_evt_handler->cancel_parse(); err_parse(m_evt_handler->m_stack.m_callbacks, ErrorDataParse{cpploc, m_evt_handler->m_curr->pos}, fmt, args...); } //----------------------------------------------------------------------------- #ifdef RYML_DBG template template void ParseEngine::_dbg(csubstr fmt, Args const& ...args) const { if(dbg_enabled_()) { dbg_printf_(fmt, args...); dbg_dumper_("\n"); _fmt_msg(dbg_dumper_); } } #endif //----------------------------------------------------------------------------- template bool ParseEngine::_finished_file() const { bool ret = m_evt_handler->m_curr->pos.offset >= _buf().len; #ifdef RYML_DBG if(ret) { _c4dbgp("finished file!!!"); } #endif return ret; } template C4_HOT C4_ALWAYS_INLINE bool ParseEngine::_finished_line() const // LCOV_EXCL_LINE { return m_evt_handler->m_curr->line_contents.rem.empty(); } //----------------------------------------------------------------------------- template void ParseEngine::_maybe_skip_whitespace_tokens() { if(m_evt_handler->m_curr->line_contents.rem.len && (m_evt_handler->m_curr->line_contents.rem.str[0] == ' ' RYML_WITH_TAB_TOKENS_(|| m_evt_handler->m_curr->line_contents.rem.str[0] == '\t'))) { size_t pos = m_evt_handler->m_curr->line_contents.rem.first_not_of(RYML_WITH_OR_WITHOUT_TAB_TOKENS_(" \t", ' ')); if(pos == npos) pos = m_evt_handler->m_curr->line_contents.rem.len; // maybe the line is just all whitespace _c4dbgpf("skip {} whitespace characters", pos); _line_progressed(pos); } } template void ParseEngine::_maybe_skipchars(char c) { if(m_evt_handler->m_curr->line_contents.rem.len && m_evt_handler->m_curr->line_contents.rem.str[0] == c) { size_t pos = m_evt_handler->m_curr->line_contents.rem.first_not_of(c); if(pos == npos) pos = m_evt_handler->m_curr->line_contents.rem.len; // maybe the line is just all c _c4dbgpf("skip {}x'{}'", pos, _c4prc(c)); _line_progressed(pos); } } template template void ParseEngine::_skipchars(const char (&chars)[N]) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_curr->line_contents.rem.begins_with_any(chars), m_evt_handler->m_curr->pos); size_t pos = m_evt_handler->m_curr->line_contents.rem.first_not_of(chars); if(pos == npos) pos = m_evt_handler->m_curr->line_contents.rem.len; // maybe the line is just whitespace _c4dbgpf("skip {} characters", pos); _line_progressed(pos); } template void ParseEngine::_skip_comment() { LineContents const& C4_RESTRICT lc = m_evt_handler->m_curr->line_contents; const size_t col = m_evt_handler->m_curr->pos.col - 1u; RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, lc.rem.begins_with('#'), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, lc.rem.is_sub(lc.full), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_curr->pos.col >= 1, m_evt_handler->m_curr->pos); // 1-based RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, col == ((size_t)(lc.rem.str - lc.full.str)), m_evt_handler->m_curr->pos); // raise an error if the comment is not preceded by whitespace if(lc.rem.str != lc.full.str) // not at line beginning { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, col > 0, m_evt_handler->m_curr->pos); const char prev = lc.full.str[col - 1u]; if C4_UNLIKELY(prev != ' ' && prev != '\t') _c4err("comment not preceded by whitespace"); } _c4dbgpf("comment was '{}'", m_evt_handler->m_curr->line_contents.rem); _line_progressed(m_evt_handler->m_curr->line_contents.rem.len); } template void ParseEngine::_maybe_skip_comment_strict() { size_t pos = m_evt_handler->m_curr->line_contents.rem.first_not_of(" \t"); if(pos != npos) { if('#' == m_evt_handler->m_curr->line_contents.rem[pos]) { _line_progressed(pos); _skip_comment(); } } } template void ParseEngine::_maybe_skip_comment() { size_t pos = m_evt_handler->m_curr->line_contents.rem.first_not_of(" \t"); if(pos != npos) { if('#' == m_evt_handler->m_curr->line_contents.rem[pos]) { _line_progressed(pos); _skip_comment(); } } else { _line_progressed(m_evt_handler->m_curr->line_contents.rem.len); } } template bool ParseEngine::_maybe_scan_following_colon() noexcept { size_t pos = m_evt_handler->m_curr->line_contents.rem.first_not_of(" \t"); if(pos != npos) { if(':' == m_evt_handler->m_curr->line_contents.rem[pos]) { // bump pos to skip the colon as well, and check the colon // is followed by space or tab if(++pos < m_evt_handler->m_curr->line_contents.rem.len) { const char next = m_evt_handler->m_curr->line_contents.rem.str[pos]; if(next == ' ' RYML_WITH_TAB_TOKENS_(|| next == '\t')) ++pos; else return false; } _line_progressed(pos); return true; } } else { _line_progressed(m_evt_handler->m_curr->line_contents.rem.len); } return false; } //----------------------------------------------------------------------------- template csubstr ParseEngine::_scan_anchor() { csubstr s = m_evt_handler->m_curr->line_contents.rem; RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.begins_with('&'), m_evt_handler->m_curr->pos); csubstr anchor = s.range(1, s.first_of(" ,]}\t")); _line_progressed(1u + anchor.len); _maybe_skipchars(' '); return anchor; } template csubstr ParseEngine::_scan_ref_seq() { csubstr s = m_evt_handler->m_curr->line_contents.rem; RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.begins_with('*'), m_evt_handler->m_curr->pos); _set_first(s, s.first_of(" ,]\t")); _line_progressed(s.len); return s; } template csubstr ParseEngine::_scan_ref_map() { csubstr s = m_evt_handler->m_curr->line_contents.rem; RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.begins_with('*'), m_evt_handler->m_curr->pos); _set_first(s, s.first_of(" ,}\t")); _line_progressed(s.len); return s; } template csubstr ParseEngine::_scan_tag() { csubstr t = m_evt_handler->m_curr->line_contents.rem; RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, t.begins_with('!'), m_evt_handler->m_curr->pos); if(!t.begins_with("!<")) { _c4dbgp("begins with '!'"); _set_first(t, t.first_of(" ,]}\t")); if C4_UNLIKELY(t.first_of("[{") != npos) _c4err("invalid tag"); _line_progressed(t.len); if(m_options.resolve_tags_all() || (m_options.resolve_tags() && is_custom_tag(t))) t = _resolve_tag(t); } else { _c4dbgp("begins with '!<'"); size_t pos = t.find('>'); if C4_UNLIKELY(pos == npos) _c4err("invalid tag"); _set_first_strict(t, pos+1); _line_progressed(t.len); t = t.sub(1); } _maybe_skip_whitespace_tokens(); return t; } template csubstr ParseEngine::_scan_tag(csubstr *orig) { csubstr t = m_evt_handler->m_curr->line_contents.rem; RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, t.begins_with('!'), m_evt_handler->m_curr->pos); if(!t.begins_with("!<")) { _c4dbgp("begins with '!'"); _set_first(t, t.first_of(" ,\t")); if C4_UNLIKELY(t.first_of("[{") != npos) _c4err("invalid tag"); _line_progressed(t.len); *orig = t; if(m_options.resolve_tags_all() || (m_options.resolve_tags() && is_custom_tag(t))) t = _resolve_tag(t); } else { _c4dbgp("begins with '!<'"); size_t pos = t.find('>'); if C4_UNLIKELY(pos == npos) _c4err("invalid tag"); _set_first_strict(t, pos+1); _line_progressed(t.len); *orig = t; t = t.sub(1); } _maybe_skip_whitespace_tokens(); return t; } //----------------------------------------------------------------------------- template bool ParseEngine::_is_valid_start_scalar_plain_flow_check_block_token(csubstr s) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.len > 0, m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.begins_with_any(":-"), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.count('\n') == 0, m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.count('\r') == 0, m_evt_handler->m_curr->pos); if(s.len > 1) { switch(s.str[1]) { case ' ': case ',': case '}': case ']': case '\t': if(s.str[0] == ':') { _c4dbgpf("not a scalar: found non-scalar token '{}{}'", s.str[0], s.str[1]); return false; } else { _c4err("invalid scalar"); } break; case '{': case '[': _c4err("invalid token \":{}\"", _c4prc(s.str[1])); break; default: break; } } else { if(s.str[0] == '-') _c4err("invalid scalar"); return false; } return true; } template bool ParseEngine::_is_valid_start_scalar_plain_flow_check_qmrk(csubstr s) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.len > 0, m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s[0] == '?', m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.count('\n') == 0, m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.count('\r') == 0, m_evt_handler->m_curr->pos); if(s.len > 1) { switch(s.str[1]) { case ' ': case '\t': _c4dbgpf("not a scalar: found non-scalar token '?{}'", _c4prc(s.str[1])); return false; case '{': case '}': case '[': case ']': _c4err("invalid token \"?{}\"", _c4prc(s.str[1])); break; default: break; } } else { return false; } return true; } template bool ParseEngine::_is_valid_start_scalar_plain_flow(csubstr s) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, !s.empty(), m_evt_handler->m_curr->pos); // it's not a scalar if it starts with any of these characters: switch(s.str[0]) { // these are all legal tokens which mean no scalar is starting: case '[': case ']': case '{': case '}': case '&': case '*': case '!': case '|': case '>': case '#': case ',': _c4dbgpf("not a scalar: found non-scalar token '{}'", _c4prc(s.str[0])); return false; // '-' and ':' are illegal at the beginning if not followed by a scalar character case '-': case ':': _c4dbgpf("suspicious token='{}' len={}", _c4prc(s.str[0]), s.len); return _is_valid_start_scalar_plain_flow_check_block_token(s); case '?': _c4dbgpf("qmrk='{}' len={}", _c4prc(s.str[0]), s.len); return _is_valid_start_scalar_plain_flow_check_qmrk(s); // everything else is a legal starting character default: return true; } } template bool ParseEngine::_scan_scalar_plain_handle_newline(csubstr s, size_t offs) { _c4dbgpf("newl[PLAIN]: found '\\n'. offs={} line={} sofar={}", offs, m_evt_handler->m_curr->pos.line, prs_(s.first(offs), true)); if(s.len > offs + 1) { _c4dbgp("newl[PLAIN]: buffer continues"); csubstr next_line = s.sub(offs + 1); size_t next_line_indentation = next_line.first_not_of(' '); if(next_line_indentation != npos) { _c4dbgpf("newl[PLAIN]: line={} indentation={} indref={}", m_evt_handler->m_curr->pos.line + 1, next_line_indentation, m_evt_handler->m_curr->indref); next_line = next_line.first(next_line.first_of("\n\r")); _c4dbgpf("newl[PLAIN]: has indentation. next_line={}", prs_(next_line)); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, next_line_indentation <= next_line.len, m_evt_handler->m_curr->pos); if C4_LIKELY(next_line_indentation >= m_evt_handler->m_curr->indref) { _c4dbgp("newl[PLAIN]: larger indentation"); next_line = next_line.sub(next_line_indentation); } else if C4_UNLIKELY(next_line.len && next_line.triml(' ').len) { _c4dbgp("newl[PLAIN]: err, smaller indentation"); _line_progressed(m_evt_handler->m_curr->line_contents.rem.len); _line_ended(); _scan_line(); if(m_evt_handler->m_curr->line_contents.indentation != npos) _line_progressed(m_evt_handler->m_curr->line_contents.indentation); _c4err("parse error"); // cannot reduce indentation here } _c4dbgpf("newl[PLAIN]: next_line.len={}", next_line.len); if(next_line.len) { size_t fno = next_line.first_not_of(" \t"); if(fno != csubstr::npos) { _c4assert(fno < next_line.len); switch(next_line.str[fno]) { case ',': case ']': case '#': _c4dbgpf("newl[PLAIN]: found terminating character beginning next line: '{}'", next_line.str[fno]); return false; case ':': // cannot be succeeded by whitespace _c4dbgp("newl[PLAIN]: found :"); if(fno + 1 == next_line.len || _is_blck_token(next_line.sub(fno))) { _c4dbgpf("newl[PLAIN]: found terminating character beginning next line: '{}'", next_line.str[fno]); return false; } break; } } } } } _line_progressed(m_evt_handler->m_curr->line_contents.rem.len); _line_ended(); _scan_line(); return true; } template bool ParseEngine::_scan_scalar_plain_seq_flow(ScannedScalar *C4_RESTRICT sc) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RMAP), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RBLCK), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RSEQ|RSEQIMAP), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RFLOW), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RVAL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, !m_evt_handler->m_curr->line_contents.rem.begins_with(' '), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, !m_evt_handler->m_curr->line_contents.rem.begins_with('\n'), m_evt_handler->m_curr->pos); if(!m_evt_handler->m_curr->line_contents.rem.len || !_is_valid_start_scalar_plain_flow(m_evt_handler->m_curr->line_contents.rem)) return false; substr s = _buf().sub(m_evt_handler->m_curr->pos.offset); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.begins_with(m_evt_handler->m_curr->line_contents.rem), m_evt_handler->m_curr->pos); _c4dbgp("scanning seqflow scalar..."); bool needs_filter = false; size_t col = 0; // zero-based column size_t offs = 0; // offset for( ; offs < s.len; ++offs, ++col) { const char c = s.str[offs]; switch(c) { case ',': case ']': _c4dbgpf("found terminating character at {}: '{}'", offs, c); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, offs > 0, m_evt_handler->m_curr->pos); goto ended_scalar; case '\n': _c4dbgpf("found '\\n' at col={}", col); if(!_scan_scalar_plain_handle_newline(s, offs)) goto ended_scalar; col = (size_t)-1; // so that col is 0 in the next loop iteration needs_filter = true; break; case '\r': --col; // don't count \r when calling _line_progressed() needs_filter = true; break; case ':': _c4dbgp("found suspicious ':'"); if(s.len > offs + 1) { char next = s.str[offs + 1]; _c4dbgpf("next char is '{}'", _c4prc(next)); if(next == '\r') { csubstr after = s.sub(offs + 1).triml('\r'); if(after.len) { next = after.str[0]; _c4dbgpf("skip \\r to '{}'", _c4prc(next)); } } // no else here. if(next == ' ' RYML_WITH_TAB_TOKENS_(|| next == '\t') || next == ',' || next == '\n' || next == ']') { _c4dbgp("map starting!"); goto ended_scalar; } else { _c4dbgp("':' nothing to see here"); } } else { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.len == offs + 1, m_evt_handler->m_curr->pos); _line_progressed(col); _c4err("missing termination: '{}'", c); // noreturn } break; case '#': { _c4dbgp("found suspicious '#'"); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, offs > 0, m_evt_handler->m_curr->pos); char prev = s.str[offs - 1]; if(prev == ' ' RYML_WITH_TAB_TOKENS_(|| prev == '\t')) { _c4dbgpf("found terminating character at {}: '{}'", offs, c); goto ended_scalar; } } break; case '[': case '{': case '}': _line_progressed(col); // advance to report the proper position in the error _c4err("invalid character: '{}'", c); // noreturn case '-': case '.': _c4dbgpf("doc token character: '{}', offs={}", c, offs); if(offs == 0 && m_evt_handler->m_curr->at_line_beginning()) { _c4dbgp("at line beginning"); if(s.len >= 3 && s.str[1] == c && s.str[2] == c) { _c4err("parse error"); // no return } } break; default: ; } } ended_scalar: _line_progressed(col); _set_first(s, offs); sc->scalar = s.trimr(RYML_WITH_OR_WITHOUT_TAB_TOKENS_(" \t", ' ')); sc->needs_filter = needs_filter; _c4prscalar("scanned plain scalar", sc->scalar, /*keep_newlines*/true); return true; } template bool ParseEngine::_scan_scalar_plain_map_flow(ScannedScalar *C4_RESTRICT sc) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RSEQ) || has_any(RSEQIMAP), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RBLCK), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RMAP|RSEQIMAP), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RFLOW), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RKEY|RVAL|QMRK), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, !m_evt_handler->m_curr->line_contents.rem.begins_with(' '), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, !m_evt_handler->m_curr->line_contents.rem.begins_with('\n'), m_evt_handler->m_curr->pos); if(!m_evt_handler->m_curr->line_contents.rem.len || !_is_valid_start_scalar_plain_flow(m_evt_handler->m_curr->line_contents.rem)) return false; substr s = _buf().sub(m_evt_handler->m_curr->pos.offset); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.begins_with(m_evt_handler->m_curr->line_contents.rem), m_evt_handler->m_curr->pos); _c4dbgp("scanning mapflow scalar..."); bool needs_filter = false; size_t col = 0; // zero-based column size_t offs = 0; // offset for( ; offs < s.len; ++offs, ++col) { const char c = s.str[offs]; switch(c) { case ',': case '}': _c4dbgpf("found terminating character at {}: '{}'", offs, c); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, offs > 0, m_evt_handler->m_curr->pos); goto ended_scalar; case '\n': _c4dbgpf("found '\\n' at col={}", col); if(!_scan_scalar_plain_handle_newline(s, offs)) goto ended_scalar; col = (size_t)-1; // so that col is 0 in the next loop iteration needs_filter = true; break; case '\r': --col; // don't count \r when calling _line_progressed() needs_filter = true; break; case ':': _c4dbgpf("found ':'", c); if(s.len == offs+1) break; { const char next = s.str[offs+1]; _c4dbgpf("next='{}'", c); if(next == ' ' || next == ',' || next == '}' || next == '\n' || next == '\r' RYML_WITH_TAB_TOKENS_(|| next == '\t')) { _c4dbgpf("found terminating character: '{}'", c); goto ended_scalar; } } break; case '{': case '[': _line_progressed(col); _c4err("invalid character: '{}'", c); // noreturn break; case ']': RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RSEQIMAP), m_evt_handler->m_curr->pos); goto ended_scalar; default: ; } } ended_scalar: _line_progressed(col); s = s.first(offs); sc->scalar = s.trimr(RYML_WITH_OR_WITHOUT_TAB_TOKENS_(" \t", ' ')); sc->needs_filter = needs_filter; _c4prscalar("scanned plain scalar", sc->scalar, /*keep_newlines*/true); return sc->scalar.len > 0u; } template bool ParseEngine::_scan_scalar_seq_json(ScannedScalar *C4_RESTRICT sc) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RMAP), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RBLCK), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RSEQ), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RFLOW), m_evt_handler->m_curr->pos); substr s = m_evt_handler->m_curr->line_contents.rem; RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, !s.begins_with(' '), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.len > 0, m_evt_handler->m_curr->pos); _c4dbgp("seq_json: scanning scalar..."); switch(s.str[0]) { case ']': case '{': case ',': _c4dbgp("seq_json: not a scalar."); return false; } { const size_t len = _begins_with_special_json_scalar(s); if(len) { char c = s.len > len ? s.str[len] : ','; if(c == ',' || c == ']' || c == ' ' || c == '\n' || c == '\t' || c == '\r') { sc->scalar = s.first(len); sc->needs_filter = false; _c4dbgpf("seq_json: special scalar: '{}'", sc->scalar); _line_progressed(len); return true; } else { return false; } } } // must be a number or special scalar size_t i = 0; for( ; i < s.len; ++i) { const char c = s.str[i]; switch(c) { case ',': case ']': case ' ': case '\t': _c4dbgpf("seq_json: found terminating character: '{}'", c); goto ended_scalar; default: ; } } ended_scalar: _line_progressed(i); sc->scalar = s.first(i); sc->needs_filter = false; _c4dbgpf("seq_json: scalar was {}", prs_(sc->scalar, /*escape*/true)); return true; } template bool ParseEngine::_scan_scalar_map_json(ScannedScalar *C4_RESTRICT sc) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RSEQ), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RBLCK), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RMAP), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RFLOW), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RKEY|RVAL), m_evt_handler->m_curr->pos); substr s = m_evt_handler->m_curr->line_contents.rem; RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, !s.begins_with(' '), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.len > 0, m_evt_handler->m_curr->pos); _c4dbgp("scanning scalar..."); { const size_t len = _begins_with_special_json_scalar(s); if(len) { char c = s.len > len ? s.str[len] : ','; _c4dbgpf("begins with special scalar: {} next='{}'", s.first(len), _c4prc(c)); if(c == ',' || c == '}' || c == ' ' || c == '\n' || c == '\t' || c == '\r') { sc->scalar = s.first(len); sc->needs_filter = false; _c4dbgpf("special json scalar: '{}'", prs_(sc->scalar)); _line_progressed(len); return true; } else { return false; } } } // must be a number size_t i = 0; for( ; i < s.len; ++i) { const char c = s.str[i]; switch(c) { case ',': case '}': case ' ': case '\t': _c4dbgpf("found terminating character: '{}'", c); goto ended_scalar; default: ; } } ended_scalar: if C4_LIKELY(i > 0) { _line_progressed(i); sc->scalar = s.first(i); sc->needs_filter = false; _c4dbgpf("scalar was {}", prs_(sc->scalar)); return true; } return false; } template bool ParseEngine::_is_doc_begin(csubstr s) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s[0] == '-', m_evt_handler->m_curr->pos); return (m_evt_handler->m_curr->line_contents.indentation == 0u && m_evt_handler->m_curr->at_line_beginning() && _is_doc_begin_token(s)); } template bool ParseEngine::_is_doc_end(csubstr s) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s[0] == '.', m_evt_handler->m_curr->pos); return (m_evt_handler->m_curr->line_contents.indentation == 0u && m_evt_handler->m_curr->at_line_beginning() && _is_doc_end_token(s)); } template bool ParseEngine::_scan_scalar_plain_blck(ScannedScalar *C4_RESTRICT sc, size_t indentation) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RFLOW), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RSEQIMAP), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RBLCK|RUNK|USTY), m_evt_handler->m_curr->pos); substr s = m_evt_handler->m_curr->line_contents.rem; RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, !s.begins_with(' '), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.len > 0, m_evt_handler->m_curr->pos); switch(s.str[0]) { case '-': if(_is_blck_token(s)) { return false; } else if(_is_doc_begin(s)) { _c4dbgp("token is doc start"); return false; } break; case ':': case '?': if(_is_blck_token(s)) return false; break; case '[': case '{': case '&': case '*': case '!': case '\t': case ',': case '%': return false; case '.': if(_is_doc_end(s)) { _c4dbgp("token is doc end"); return false; } break; } _c4dbgpf("plain scalar! indentation={}", indentation); const size_t start_offset = m_evt_handler->m_curr->pos.offset; const size_t start_line = m_evt_handler->m_curr->pos.line; bool needs_filter = false; while(true) { _c4dbgpf("plain scalar line: {}", prs_(s)); for(size_t i = 0; i < s.len; ++i) { const char curr = s.str[i]; //_c4dbgpf("[{}]='{}'", i, _c4prc(curr)); switch(curr) { case ':': _c4dbgpf("[{}]: got suspicious ':'", i); // are there more characters? if((i + 1 == s.len) || ((s.str[i+1] == ' ') RYML_WITH_TAB_TOKENS_( || (s.str[i+1] == '\t')))) { _c4dbgpf("followed by '{}'", i+1 == s.len ? csubstr("\\n") : _c4prc(s.str[i+1])); _line_progressed(i); // ': ' is accepted only on the first line if C4_LIKELY(m_evt_handler->m_curr->pos.line == start_line) { _c4dbgp("start line. scalar ends here"); goto ended_scalar; } else { _c4err("multiline scalars cannot be used as keys"); } } else { size_t j = i; while(j + 1 < s.len && s.str[j+1] == ':') { _c4dbgp("skip colon"); ++j; } i = j > i ? j-1 : i; _c4dbgp("nothing to see here"); } break; case '#': _c4dbgp("got suspicious '#'"); if(!i || (s.str[i-1] == ' ' || s.str[i-1] == '\t')) { _c4dbgp("comment! scalar ends here"); _line_progressed(i); goto ended_scalar; } else { _c4dbgp("nothing to see here"); } break; } } _line_progressed(s.len); csubstr next_peeked = _peek_next_line(m_evt_handler->m_curr->pos.offset); next_peeked = next_peeked.trimr("\n\r"); const size_t next_indentation = next_peeked.first_not_of(' '); _c4dbgpf("indentation curr={} next={}", indentation, next_indentation); if(next_indentation < indentation) { _c4dbgp("smaller indentation! scalar ended"); goto ended_scalar; } else if(next_indentation == 0 && next_peeked.len > 0) { const char first = next_peeked.str[0]; switch(first) { case '-': _c4dbgpf("doc begin? peeked={}", prs_(next_peeked, size_t(3))); if(_is_doc_begin_token(next_peeked)) { _c4dbgp("doc begin! scalar ended"); goto ended_scalar; } break; case '.': _c4dbgpf("doc end? peeked={}", prs_(next_peeked, size_t(3))); if(_is_doc_end_token(next_peeked)) { _c4dbgp("doc end! scalar ended"); goto ended_scalar; } break; } } // load with next line _c4dbgp("next line!"); if(!_finished_file()) { _c4dbgp("next line!"); _line_ended(); _scan_line(); } else { _c4dbgp("file finished!"); goto ended_scalar; } s = m_evt_handler->m_curr->line_contents.rem; needs_filter = true; } ended_scalar: sc->scalar = _buf().range(start_offset, m_evt_handler->m_curr->pos.offset).trimr(" \n\r\t"); sc->needs_filter = needs_filter; _c4dbgpf("scalar was {}", prs_(sc->scalar)); return true; } template C4_ALWAYS_INLINE bool ParseEngine::_scan_scalar_plain_seq_blck(ScannedScalar *C4_RESTRICT sc) // LCOV_EXCL_LINE { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RMAP), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RFLOW), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RSEQIMAP), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RSEQ), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RBLCK), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RVAL), m_evt_handler->m_curr->pos); return _scan_scalar_plain_blck(sc, m_evt_handler->m_curr->indref + 1u); } template C4_ALWAYS_INLINE bool ParseEngine::_scan_scalar_plain_map_blck(ScannedScalar *C4_RESTRICT sc) // LCOV_EXCL_LINE { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RSEQ), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RFLOW), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RMAP), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RBLCK), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RKEY|RVAL|QMRK), m_evt_handler->m_curr->pos); return _scan_scalar_plain_blck(sc, m_evt_handler->m_curr->indref + 1u); } template C4_ALWAYS_INLINE bool ParseEngine::_scan_scalar_plain_unk(ScannedScalar *C4_RESTRICT sc) // LCOV_EXCL_LINE { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RUNK|USTY), m_evt_handler->m_curr->pos); return _scan_scalar_plain_blck(sc, m_evt_handler->m_curr->indref); } //----------------------------------------------------------------------------- template substr ParseEngine::_peek_next_line(size_t pos) const { substr rem{}; // declare here because of the goto size_t nlpos{}; // declare here because of the goto pos = pos == npos ? m_evt_handler->m_curr->pos.offset : pos; if(pos >= _buf().len) goto next_is_empty; // look for the next newline chars, and jump to the right of those rem = _from_next_line(_buf().sub(pos)); if(rem.empty()) goto next_is_empty; // now get everything up to and including the following newline chars nlpos = rem.first_of("\r\n"); if((nlpos != csubstr::npos) && (nlpos + 1 < rem.len)) nlpos += _extend_from_combined_newline(rem[nlpos], rem[nlpos+1]); rem = rem.left_of(nlpos, /*include_pos*/true); _c4dbgpf("peek next line @ {}: (len={})'{}'", pos, rem.len, rem.trimr("\r\n")); return rem; next_is_empty: _c4dbgpf("peek next line @ {}: (len=0)''", pos); return rem; } //----------------------------------------------------------------------------- template void ParseEngine::_scan_line() { if C4_LIKELY(m_evt_handler->m_curr->pos.offset < _buf().len) m_evt_handler->m_curr->line_contents.reset_with_next_line(_buf(), m_evt_handler->m_curr->pos.offset); else m_evt_handler->m_curr->line_contents.reset_with_next_line(_buf().last(0), 0); } template void ParseEngine::_line_progressed(size_t ahead) { _c4dbgpf("line[{}] ({} cols) progressed by {}: col {}-->{} offset {}-->{}", m_evt_handler->m_curr->pos.line, m_evt_handler->m_curr->line_contents.full.len, ahead, m_evt_handler->m_curr->pos.col, m_evt_handler->m_curr->pos.col+ahead, m_evt_handler->m_curr->pos.offset, m_evt_handler->m_curr->pos.offset+ahead); m_evt_handler->m_curr->pos.offset += ahead; m_evt_handler->m_curr->pos.col += ahead; RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_curr->pos.col <= m_evt_handler->m_curr->line_contents.num_cols+1, m_evt_handler->m_curr->pos); m_evt_handler->m_curr->line_contents.rem = m_evt_handler->m_curr->line_contents.rem.sub(ahead); } template void ParseEngine::_line_ended() { _c4dbgpf("line[{}] ({} cols) ended! offset {}-->{} / col {}-->{}", m_evt_handler->m_curr->pos.line, m_evt_handler->m_curr->line_contents.full.len, m_evt_handler->m_curr->pos.offset, m_evt_handler->m_curr->pos.offset + m_evt_handler->m_curr->line_contents.full.len - m_evt_handler->m_curr->line_contents.num_cols, m_evt_handler->m_curr->pos.col, 1); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_curr->pos.col == m_evt_handler->m_curr->line_contents.num_cols + 1, m_evt_handler->m_curr->pos); m_evt_handler->m_curr->pos.offset += m_evt_handler->m_curr->line_contents.full.len - m_evt_handler->m_curr->line_contents.num_cols; ++m_evt_handler->m_curr->pos.line; m_evt_handler->m_curr->pos.col = 1; } template void ParseEngine::_line_ended_undo() { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_curr->pos.col == 1u, m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_curr->pos.line > 0u, m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_curr->pos.offset >= m_evt_handler->m_curr->line_contents.full.len - m_evt_handler->m_curr->line_contents.num_cols, m_evt_handler->m_curr->pos); const size_t delta = m_evt_handler->m_curr->line_contents.full.len - m_evt_handler->m_curr->line_contents.num_cols; _c4dbgpf("line[{}] undo ended! line {}-->{}, offset {}-->{}", m_evt_handler->m_curr->pos.line, m_evt_handler->m_curr->pos.line, m_evt_handler->m_curr->pos.line - 1, m_evt_handler->m_curr->pos.offset, m_evt_handler->m_curr->pos.offset - delta); m_evt_handler->m_curr->pos.offset -= delta; --m_evt_handler->m_curr->pos.line; m_evt_handler->m_curr->pos.col = m_evt_handler->m_curr->line_contents.num_cols + 1u; // don't forget to undo also the changes to the remainder of the line //RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_curr->pos.offset >= _buf().len || _buf()[m_evt_handler->m_curr->pos.offset] == '\n' || _buf()[m_evt_handler->m_curr->pos.offset] == '\r', m_evt_handler->m_curr->pos); m_evt_handler->m_curr->line_contents.rem = _buf().sub(m_evt_handler->m_curr->pos.offset, 0); } //----------------------------------------------------------------------------- template void ParseEngine::_set_indentation(size_t indentation) noexcept { m_evt_handler->m_curr->indref = indentation; _c4dbgpf("state[{}]: saving indentation: {}", m_evt_handler->m_curr->level, m_evt_handler->m_curr->indref); } template void ParseEngine::_save_indentation() { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_curr->line_contents.rem.is_sub(m_evt_handler->m_curr->line_contents.full), m_evt_handler->m_curr->pos); m_evt_handler->m_curr->indref = m_evt_handler->m_curr->line_contents.current_col(); _c4dbgpf("state[{}]: saving indentation: {}", m_evt_handler->m_curr->level, m_evt_handler->m_curr->indref); } template void ParseEngine::_mark_seqflow_val_end() noexcept { _c4dbgpf("SEQFLOW. mark val end at line={}", m_evt_handler->m_curr->pos.line); m_prev_val_end = m_evt_handler->m_curr->pos.line; } //----------------------------------------------------------------------------- template void ParseEngine::_flow_container_was_a_key(size_t orig_indent) { _c4dbgpf("flow container is followed by colon! orig_indent={}", orig_indent); m_evt_handler->actually_val_is_first_key_of_new_map_block(); addrem_flags(RMAP|RVAL|RBLCK, RKCL|RSEQ|RUNK); _set_indentation(orig_indent); _maybe_skip_whitespace_tokens(); } template void ParseEngine::_end_flow_container(size_t orig_indent, bool multiline) { // this is called AFTER ending the flow container, // so now we're at the parent container's scope if(has_all(RMAP|RBLCK) && has_none(RKCL|RVAL|RNXT)) { _c4dbgp("flow container: end as vanilla block map key!"); if C4_UNLIKELY(multiline) _c4err("multiline key is invalid"); if C4_UNLIKELY(!_maybe_scan_following_colon()) _c4err("could not find ':' colon after key"); _maybe_skip_whitespace_tokens(); addrem_flags(RVAL, RKEY|RKCL|RNXT); } else if(has_none(RFLOW)) { _c4dbgp("end_flow_container: now not in flow!"); if(has_any(RUNK|RSEQ|RKCL) && _maybe_scan_following_colon()) { if C4_UNLIKELY(multiline) _c4err("multiline key is invalid"); _flow_container_was_a_key(orig_indent); } else { _c4dbgp("end_flow_container: end map as key!"); } } else if(has_any(RSEQ)) { _c4dbgp("end_flow_container: now in a flow seq"); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RFLOW), m_evt_handler->m_curr->pos); _mark_seqflow_val_end(); } } template void ParseEngine::_end_map_flow() { bool multiline = m_evt_handler->m_parent->pos.line < m_evt_handler->m_curr->pos.line; size_t orig_indent = m_evt_handler->m_curr->indref; _c4dbgpf("mapflow: end, multiline={}", multiline); m_evt_handler->end_map_flow(multiline && m_options.detect_flow_ml(), m_options.flow_ml_style().m_bits); _end_flow_container(orig_indent, multiline); } template void ParseEngine::_end_seq_flow() { bool multiline = m_evt_handler->m_parent->pos.line < m_evt_handler->m_curr->pos.line; size_t orig_indent = m_evt_handler->m_curr->indref; _c4dbgpf("seqflow: end, multiline={}", multiline); m_evt_handler->end_seq_flow(multiline && m_options.detect_flow_ml(), m_options.flow_ml_style().m_bits); _end_flow_container(orig_indent, multiline); } template void ParseEngine::_end_map_blck() { _c4dbgp("mapblck: end"); if(has_any(RKCL|RVAL)) { _c4dbgp("mapblck: set missing val"); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_plain_empty(); } else if(has_any(QMRK)) { _c4dbgp("mapblck: set missing keyval"); _handle_annotations_before_blck_key_scalar(); m_evt_handler->set_key_scalar_plain_empty(); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_plain_empty(); } m_evt_handler->end_map_block(); } template void ParseEngine::_end_seq_blck() { if(has_any(RVAL)) { _c4dbgp("seqblck: set missing val"); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_plain_empty(); } m_evt_handler->end_seq_block(); } template void ParseEngine::_end2_map() { _c4dbgp("map: end"); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RMAP), m_evt_handler->m_curr->pos); if(has_any(RBLCK)) { _end_map_blck(); } else { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RFLOW), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(USTY), m_evt_handler->m_curr->pos); m_evt_handler->_pop(); } } template void ParseEngine::_end2_seq() { _c4dbgp("seq: end"); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RSEQ), m_evt_handler->m_curr->pos); if(has_any(RBLCK)) { _end_seq_blck(); } else { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RFLOW), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(USTY), m_evt_handler->m_curr->pos); m_evt_handler->_pop(); } } template void ParseEngine::_begin2_doc() { _c4dbgp("begin_doc"); m_has_directives_yaml = false; m_has_directives = false; m_doc_empty = true; add_flags(RDOC); m_evt_handler->begin_doc(); m_evt_handler->m_curr->indref = 0; // ? } template void ParseEngine::_begin2_doc_expl() { _c4dbgp("begin_doc_expl"); m_has_directives_yaml = false; m_has_directives = false; m_doc_empty = true; add_flags(RDOC); m_evt_handler->begin_doc_expl(); m_evt_handler->m_curr->indref = 0; // ? } template void ParseEngine::_end2_doc() { _c4dbgp("doc: end"); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RDOC), m_evt_handler->m_curr->pos); if(m_doc_empty || (m_pending_tags.num_entries || m_pending_anchors.num_entries)) { _c4dbgp("doc was empty; add empty val"); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_plain_empty(); } m_evt_handler->end_doc(); m_bom_len = 0; } template void ParseEngine::_end2_doc_expl() { _c4dbgp("doc: end"); if(m_doc_empty || (m_pending_tags.num_entries || m_pending_anchors.num_entries)) { _c4dbgp("doc: no children; add empty val"); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_plain_empty(); } m_evt_handler->end_doc_expl(); m_bom_len = 0; } template void ParseEngine::_maybe_begin_doc() { if(has_none(RDOC)) { _c4dbgp("doc must be started"); _begin2_doc(); } } template void ParseEngine::_maybe_end_doc() { if(has_any(RDOC)) { _c4dbgp("doc must be finished"); _end2_doc(); } else if(m_doc_empty && (m_pending_tags.num_entries || m_pending_anchors.num_entries)) { _c4dbgp("no doc to finish, but pending annotations"); m_evt_handler->begin_doc(); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_plain_empty(); m_evt_handler->end_doc(); } } template void ParseEngine::_end_doc_suddenly__pop() { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_stack.size() >= 1, m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_stack[0].flags & RDOC, m_evt_handler->m_curr->pos); _c4dbgp("root is RDOC"); if(m_evt_handler->m_curr->level != 0) _handle_indentation_pop(&m_evt_handler->m_stack[0]); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RDOC), m_evt_handler->m_curr->pos); } /** Check whether the current parse tokens are trailing on the * previous doc, and raise an error if they are */ template void ParseEngine::_check_trailing_doc_token() { const bool is_root = (m_evt_handler->m_stack.size() == 1u); const bool isndoc = (m_evt_handler->m_curr->flags & NDOC) != 0; const bool suspicious = m_evt_handler->template has_any_(); _c4dbgpf("target={} isroot={} suspicious={} ndoc={}", m_evt_handler->m_curr->node_id, is_root, suspicious, isndoc); if((is_root || m_evt_handler->template has_any_()) && suspicious && !isndoc) _c4err("parse error"); } template void ParseEngine::_end_doc_suddenly() { _c4dbgp("end doc suddenly"); _end_doc_suddenly__pop(); _end2_doc_expl(); addrem_flags(RUNK|RTOP|NDOC, RMAP|RSEQ|RDOC); } template void ParseEngine::_check_doc_end_tokens() const { csubstr rem = m_evt_handler->m_curr->line_contents.rem; RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, !rem.begins_with_any(". \t"), m_evt_handler->m_curr->pos); if C4_UNLIKELY(rem.len && !rem.begins_with('#')) { _c4err("parse error"); } } template void ParseEngine::_start_doc_suddenly() { _c4dbgp("start doc suddenly"); _end_doc_suddenly__pop(); _end2_doc(); _begin2_doc_expl(); } template void ParseEngine::_end_stream() { _c4dbgpf("end_stream, level={} node_id={}", m_evt_handler->m_curr->level, m_evt_handler->m_curr->node_id); if C4_UNLIKELY(has_all(RSEQ|RFLOW)) _c4err("missing terminating ]"); else if C4_UNLIKELY(has_all(RMAP|RFLOW)) _c4err("missing terminating }"); if(m_evt_handler->m_stack.size() > 1) _handle_indentation_pop(m_evt_handler->m_stack.begin()); if(has_all(RDOC)) { _end2_doc(); } else if(has_all(RTOP|RUNK)) { if(m_pending_anchors.num_entries || m_pending_tags.num_entries) { if(m_doc_empty) { m_evt_handler->begin_doc(); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_plain_empty(); m_evt_handler->end_doc(); } } } m_evt_handler->end_stream(); if C4_UNLIKELY(m_has_directives) _c4err("directives cannot be used without a document"); } template void ParseEngine::_handle_indentation_pop(ParserState const* popto) { _c4dbgpf("popping {} level{}: from level {}(@ind={}) to level {}(@ind={})", m_evt_handler->m_curr->level - popto->level, (((m_evt_handler->m_curr->level - popto->level) > 1) ? "s" : ""), m_evt_handler->m_curr->level, m_evt_handler->m_curr->indref, popto->level, popto->indref); while(m_evt_handler->m_curr != popto) { if(has_any(RSEQ)) { _c4dbgpf("popping seq at level {} (indentation={},addr={})", m_evt_handler->m_curr->level, m_evt_handler->m_curr->indref, m_evt_handler->m_curr); _end2_seq(); } else if(has_any(RMAP)) { _c4dbgpf("popping map at level {} (indentation={},addr={})", m_evt_handler->m_curr->level, m_evt_handler->m_curr->indref, m_evt_handler->m_curr); _end2_map(); } else { break; } } _c4dbgpf("current level is {} (indentation={})", m_evt_handler->m_curr->level, m_evt_handler->m_curr->indref); } template void ParseEngine::_handle_indentation_pop_from_block_seq() { // search the stack frame to jump to based on its indentation using state_type = typename EventHandler::state; state_type const* popto = nullptr; auto &stack = m_evt_handler->m_stack; RYML_ASSERT_PARSE_CB_(stack.m_callbacks, stack.is_contiguous(), m_evt_handler->m_curr->pos); // this search relies on the stack being contiguous RYML_ASSERT_PARSE_CB_(stack.m_callbacks, m_evt_handler->m_curr >= stack.begin() && m_evt_handler->m_curr < stack.end(), m_evt_handler->m_curr->pos); const size_t ind = m_evt_handler->m_curr->line_contents.indentation; #ifdef RYML_DBG _print_state_stack(); #endif for(state_type const* s = m_evt_handler->m_curr-1; s >= stack.begin(); --s) { _c4dbgpf("searching for state with indentation {}. curr={} (level={},node={})", ind, s->indref, s->level, s->node_id); if(s->indref == ind) { _c4dbgpf("gotit!!! level={} node={}", s->level, s->node_id); popto = s; break; } } if(!popto || popto >= m_evt_handler->m_curr || popto->level >= m_evt_handler->m_curr->level) { _c4err("parse error: incorrect indentation?"); } _handle_indentation_pop(popto); } template void ParseEngine::_handle_indentation_pop_from_block_map() { // search the stack frame to jump to based on its indentation using state_type = typename EventHandler::state; auto &stack = m_evt_handler->m_stack; RYML_ASSERT_PARSE_CB_(stack.m_callbacks, stack.is_contiguous(), m_evt_handler->m_curr->pos); // this search relies on the stack being contiguous RYML_ASSERT_PARSE_CB_(stack.m_callbacks, m_evt_handler->m_curr >= stack.begin() && m_evt_handler->m_curr < stack.end(), m_evt_handler->m_curr->pos); const size_t ind = m_evt_handler->m_curr->line_contents.indentation; state_type const* popto = nullptr; #ifdef RYML_DBG char flagbuf_[128]; _print_state_stack(flagbuf_); #endif for(state_type const* s = m_evt_handler->m_curr-1; s > stack.begin(); --s) // never go to the stack bottom. that's the root { _c4dbgpf("searching for state with indentation {}. current: ind={},level={},node={},flags={}", ind, s->indref, s->level, s->node_id, detail::_parser_flags_to_str(flagbuf_, s->flags)); if(s->indref < ind) { break; } else if(s->indref == ind) { _c4dbgpf("same indentation!!! level={} node={}", s->level, s->node_id); if(popto && has_any(RTOP, s) && has_none(RMAP|RSEQ, s)) { break; } popto = s; if(has_all(RSEQ|RBLCK, s)) { csubstr rem = m_evt_handler->m_curr->line_contents.rem; const size_t first = rem.first_not_of(' '); RYML_ASSERT_PARSE_CB_(stack.m_callbacks, first == ind || first == npos, m_evt_handler->m_curr->pos); rem = rem.right_of(first, true); _c4dbgpf("indentless? rem='{}' first={}", rem, first); if(rem.begins_with('-') && _is_blck_token(rem)) { _c4dbgp("parent was indentless seq"); break; } } } } if(!popto || popto >= m_evt_handler->m_curr || popto->level >= m_evt_handler->m_curr->level) { _c4err("parse error: incorrect indentation?"); } _handle_indentation_pop(popto); } //----------------------------------------------------------------------------- template void ParseEngine::_check_valid_newline_in_quoted_scalar() { if C4_UNLIKELY(has_all(RMAP|RBLCK|RKEY)) { _c4err("multiline quoted keys are invalid"); } else // check contextual indentation { const size_t minindent = m_evt_handler->m_curr->indref + ((has_any(RMAP|RSEQ) && has_any(RBLCK))); _c4dbgpf("indent={} vs minindent={} indref={}", m_evt_handler->m_curr->line_contents.indentation, minindent, m_evt_handler->m_curr->indref); if(m_evt_handler->m_curr->line_contents.indentation < minindent) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_curr->line_contents.indentation == m_evt_handler->m_curr->line_contents.rem.first_not_of(' '), m_evt_handler->m_curr->pos); csubstr trimmed = m_evt_handler->m_curr->line_contents.rem.sub(m_evt_handler->m_curr->line_contents.indentation); _c4dbgpf("trimmed.len={} line={}", trimmed.len, prs_(m_evt_handler->m_curr->line_contents.rem, true)); if C4_UNLIKELY(!!trimmed.len) { _c4err("bad indentation"); } } } } //----------------------------------------------------------------------------- template ScannedScalar ParseEngine::_scan_scalar_squot() { // quoted scalars can spread over multiple lines! // nice explanation here: http://yaml-multiline.info/ RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, _buf().sub(m_evt_handler->m_curr->pos.offset).begins_with('\''), m_evt_handler->m_curr->pos); // a span to the end of the file, skipping the opening quote substr s = _buf().sub(m_evt_handler->m_curr->pos.offset + 1); _line_progressed(1); // advance over the opening quote RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, !m_evt_handler->m_curr->at_line_beginning(), m_evt_handler->m_curr->pos); bool needs_filter = false; size_t pos = npos; // find the pos of the matching quote while( ! _finished_file()) { const csubstr line = m_evt_handler->m_curr->line_contents.rem; _c4dbgpf("scanning single quoted scalar @ line[{}]: {}", m_evt_handler->m_curr->pos.line, prs_(line)); if C4_UNLIKELY(m_evt_handler->m_curr->at_line_beginning() && _is_doc_token(line)) _c4err("token can not appear at line begin"); for(size_t i = 0; i < line.len; ++i) { const char curr = line.str[i]; if(curr == '\'') // single quotes are escaped with two single quotes { const char next = i+1 < line.len ? line.str[i+1] : '~'; if(next != '\'') // so just look for the first quote { // without another after it _line_progressed(i + 1); // progress beyond the quote pos = i + (size_t)(line.str - s.str); // set pos to before the quote goto found_close; } else { needs_filter = true; // needs filter to remove escaped quotes ++i; // skip the escaped quote } } } needs_filter = true; _line_progressed(line.len); _line_ended(); _scan_line(); _check_valid_newline_in_quoted_scalar(); } _c4err("reached end of file while looking for closing quote"); found_close: _c4dbgpf("found closing quote at: {}", pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, pos != npos, m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, pos >= 0, m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.end() >= _buf().begin() && s.end() <= _buf().end(), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.end() == _buf().end() || *s.end() == '\'', m_evt_handler->m_curr->pos); _set_first_strict(s, pos); _c4prscalar("scanned squoted scalar", s, /*keep_newlines*/true); return ScannedScalar { s, needs_filter }; } //----------------------------------------------------------------------------- template ScannedScalar ParseEngine::_scan_scalar_dquot() { // quoted scalars can spread over multiple lines! // nice explanation here: http://yaml-multiline.info/ RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, _buf().sub(m_evt_handler->m_curr->pos.offset).begins_with('"'), m_evt_handler->m_curr->pos); // a span to the end of the file, skipping the opening quote substr s = _buf().sub(m_evt_handler->m_curr->pos.offset + 1); _line_progressed(1); // advance over the opening quote RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, !m_evt_handler->m_curr->at_line_beginning(), m_evt_handler->m_curr->pos); bool needs_filter = false; size_t pos = npos; // find the pos of the matching quote while( ! _finished_file()) { #if defined(__GNUC__) && (/*__GNUC__ == 12 || */__GNUC__ == 13) C4_DONT_OPTIMIZE(m_evt_handler->m_curr->line_contents.rem); // prevent hoisting #endif csubstr rem = m_evt_handler->m_curr->line_contents.rem; _c4dbgpf("scanning double quoted scalar @ line[{}]: line='{}'", m_evt_handler->m_curr->pos.line, rem); if C4_UNLIKELY(m_evt_handler->m_curr->at_line_beginning() && _is_doc_token(rem)) _c4err("token can not appear at line begin"); for(size_t i = 0; i < rem.len; ++i) { const char curr = rem.str[i]; // every \ is an escape if(curr == '\\') { const char next = i+1 < rem.len ? rem.str[i+1] : '~'; needs_filter = true; if(next == '"' || next == '\\') ++i; } else if(curr == '"') { _line_progressed(i + 1); // progress beyond the quote pos = i + (size_t)(rem.str - s.str); // set pos to before the quote goto found_close; } } // leading whitespace also needs filtering needs_filter = true; _line_progressed(rem.len); _line_ended(); _scan_line(); _check_valid_newline_in_quoted_scalar(); } _c4err("reached end of file while looking for closing quote"); found_close: _c4dbgpf("found closing quote at: {}", pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, pos != npos, m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, pos >= 0, m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.end() >= _buf().begin() && s.end() <= _buf().end(), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.end() == _buf().end() || *s.end() == '"', m_evt_handler->m_curr->pos); _set_first_strict(s, pos); _c4prscalar("scanned dquoted scalar", s, /*keep_newlines*/true); return ScannedScalar{s, needs_filter}; } //----------------------------------------------------------------------------- template void ParseEngine::_scan_block(ScannedBlock *C4_RESTRICT sb, size_t indref) { _c4dbgpf("blck: indref={}", indref); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, indref != npos, m_evt_handler->m_curr->pos); // nice explanation here: http://yaml-multiline.info/ csubstr s = m_evt_handler->m_curr->line_contents.rem; RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.begins_with('|') || s.begins_with('>'), m_evt_handler->m_curr->pos); _c4dbgpf("blck: specs={}", prs_(s)); // parse the spec BlockChomp_e chomp = CHOMP_CLIP; // default to clip unless + or - are used size_t indentation = npos; // have to find out if no spec is given if(s.len > 1) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.begins_with_any("|>"), m_evt_handler->m_curr->pos); csubstr t = s.sub(1); _c4dbgpf("blck: spec is multichar: {}", prs_(t)); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, t.len >= 1, m_evt_handler->m_curr->pos); size_t pos = t.first_of("-+"); _c4dbgpf("blck: spec chomp char: pos={}", pos); if(pos != npos) { _c4dbgpf("blck: spec chomp char: {}", _c4prc(t[pos])); if(t[pos] == '-') { _c4dbgp("blck: chomp=STRIP"); chomp = CHOMP_STRIP; } else if(t[pos] == '+') { _c4dbgp("blck: chomp=KEEP"); chomp = CHOMP_KEEP; } if(pos == 0) t = t.sub(1); else t = t.first(pos); _c4dbgpf("blck: spec is now: {}", prs_(t)); } // from here to the end, only digits are considered pos = t.first_not_of("0123456789"); csubstr rest = t.first(pos); if( ! rest.empty()) { _c4dbgpf("blck: parse indentation digits: {}", prs_(rest)); if C4_UNLIKELY(rest.len > 1) _c4err("parse error: invalid indentation"); if C4_UNLIKELY( ! c4::atou(rest, &indentation)) _c4err("parse error: could not read indentation as decimal"); // LCOV_EXCL_LINE if C4_UNLIKELY( ! indentation) _c4err("parse error: null indentation"); _c4dbgpf("blck: indentation specified: {}. add {} from curr state -> {}", indentation, m_evt_handler->m_curr->indref, indentation+indref); indentation += m_evt_handler->m_curr->indref; } else { rest = t.triml(" \t"); _c4dbgpf("blck: digits empty. t={} trimmed={} iscomm={} t.iscomm={}", prs_(t), prs_(rest), rest.begins_with('#'), t.begins_with('#')); if C4_UNLIKELY(rest.len && (rest.str[0] != '#' || t.str[0] == '#')) _c4err("parse error: invalid token"); } } _c4dbgpf("blck: style={} chomp={} indentation={}", s.begins_with('>') ? "fold" : "literal", chomp==CHOMP_CLIP ? "clip" : (chomp==CHOMP_STRIP ? "strip" : "keep"), indentation); // finish the current line _line_progressed(s.len); _line_ended(); _scan_line(); // start with a zero-length block, already pointing at the right place substr raw_block(_buf().data() + m_evt_handler->m_curr->pos.offset, size_t(0)); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, raw_block.begin() == m_evt_handler->m_curr->line_contents.full.str, m_evt_handler->m_curr->pos); // read every full line into a raw block, // from which newlines are to be stripped as needed. // // If no explicit indentation was given, pick it from the first // non-empty line. See // https://yaml.org/spec/1.2.2/#8111-block-indentation-indicator size_t num_lines = 0; size_t first = m_evt_handler->m_curr->pos.line; size_t provisional_indentation = npos; LineContents lc; while(( ! _finished_file())) { // peek next line, but do not advance immediately lc.reset_with_next_line(_buf(), m_evt_handler->m_curr->pos.offset); #if defined(__GNUC__) && (__GNUC__ == 12 || __GNUC__ == 13) C4_DONT_OPTIMIZE(lc.rem); #endif _c4dbgpf("blck: peeking at {}", prs_(lc.rem.trimr("\r\n"), true)); // evaluate termination conditions if(indentation != npos) { _c4dbgpf("blck: indentation={}", indentation); // stop when the line is deindented and not empty if(lc.indentation < indentation && ( ! lc.rem.trim(" \t").empty())) { if(raw_block.len) { _c4dbgpf("blck: indentation decreased ref={} thisline={}", indentation, lc.indentation); } else { _c4err("indentation decreased without any scalar"); } break; } else if(indentation == 0) { _c4dbgpf("blck: noindent. lc.rem={}", prs_(lc.rem)); if(_is_doc_token(lc.rem)) { _c4dbgp("blck: stop. indentation=0 and doc ended"); break; } } } else { const size_t fns = lc.rem.first_not_of(' '); _c4dbgpf("blck: indentation ref not set. firstnonws={}", fns); if(fns != npos) // non-empty line { _c4dbgpf("blck: line not empty. indref={} indprov={} indentation={}", indref, provisional_indentation, lc.indentation); if C4_UNLIKELY(lc.full.begins_with('\t')) _c4err("parse error"); if(provisional_indentation == npos) { if(lc.indentation < indref) { _c4dbgpf("blck: block terminated indentation={} < indref={}", lc.indentation, indref); if(raw_block.len == 0) { _c4dbgp("blck: was empty, undo next line"); _line_ended_undo(); } break; } else if(lc.indentation == m_evt_handler->m_curr->indref) { if(has_any(RSEQ|RMAP)) { _c4dbgpf("blck: block terminated. reading container and indentation={}==indref={}", lc.indentation, m_evt_handler->m_curr->indref); break; } } _c4dbgpf("blck: set indentation ref from this line: ref={}", lc.indentation); indentation = lc.indentation; } else { if(lc.indentation >= provisional_indentation) { _c4dbgpf("blck: set indentation ref from provisional indentation: provisional_ref={}, thisline={}", provisional_indentation, lc.indentation); //indentation = provisional_indentation ? provisional_indentation : lc.indentation; indentation = lc.indentation; } else { if(lc.indentation >= indref) _c4err("parse error: first non-empty block line should have at least the original indentation"); _c4dbgp("blck: finished"); break; } } } else // empty line { _c4dbgpf("blck: line empty or {} spaces. line_indentation={} prov_indentation={}", lc.rem.len, lc.indentation, provisional_indentation); if(provisional_indentation != npos) { if(lc.rem.len >= provisional_indentation) { _c4dbgpf("blck: increase provisional_ref {} -> {}", provisional_indentation, lc.rem.len); provisional_indentation = lc.rem.len; } } else { provisional_indentation = lc.indentation ? lc.indentation : has_any(RSEQ|RVAL); _c4dbgpf("blck: initialize provisional_ref={}", provisional_indentation); if(provisional_indentation == npos) { provisional_indentation = lc.rem.len ? lc.rem.len : has_any(RSEQ|RVAL); _c4dbgpf("blck: initialize provisional_ref={}", provisional_indentation); } if(provisional_indentation < indref) { provisional_indentation = indref; _c4dbgpf("blck: initialize provisional_ref={}", provisional_indentation); } } } } // advance now that we know the folded scalar continues m_evt_handler->m_curr->line_contents = lc; _c4dbgpf("blck: append '{}'", m_evt_handler->m_curr->line_contents.rem); raw_block.len += m_evt_handler->m_curr->line_contents.full.len; _line_progressed(m_evt_handler->m_curr->line_contents.rem.len); _line_ended(); ++num_lines; } RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_curr->pos.line == (first + num_lines) || (raw_block.len == 0), m_evt_handler->m_curr->pos); C4_UNUSED(num_lines); C4_UNUSED(first); if(indentation == npos) { _c4dbgpf("blck: set indentation from provisional: {}", provisional_indentation); indentation = provisional_indentation; } if(num_lines) _line_ended_undo(); _c4prscalar("scanned block", raw_block, /*keep_newlines*/true); sb->scalar = raw_block; sb->indentation = indentation; sb->chomp = chomp; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** @cond dev */ // a debugging scaffold: #if 0 #define _c4dbgfws(fmt, ...) _c4dbgpf("filt_ws[{}->{}]: " fmt, proc.rpos, proc.wpos, __VA_ARGS__) #else #define _c4dbgfws(...) #endif template template bool ParseEngine::_filter_ws_handle_to_first_non_space(FilterProcessor &proc) { _c4dbgfws("found whitespace '{}'", _c4prc(proc.curr())); RYML_ASSERT_PARSE_CB_(this->callbacks(), proc.curr() == ' ' || proc.curr() == '\t', m_evt_handler->m_curr->pos); const size_t first_pos = proc.rpos > 0 ? proc.src.first_not_of(" \t", proc.rpos) : proc.src.first_not_of(' ', proc.rpos); if(first_pos != npos) { const char first_char = proc.src[first_pos]; _c4dbgfws("firstnonws='{}'@{}", _c4prc(first_char), first_pos); if(first_char == '\n' || first_char == '\r') // skip trailing whitespace { _c4dbgfws("whitespace is trailing on line", ""); proc.skip(first_pos - proc.rpos); } else // a legit whitespace { proc.copy(); _c4dbgfws("legit whitespace. sofar={}", prs_(proc.sofar())); } return true; } _c4dbgfws("whitespace is trailing on line", ""); return false; } template template void ParseEngine::_filter_ws_copy_trailing(FilterProcessor &proc) { if(!_filter_ws_handle_to_first_non_space(proc)) { _c4dbgfws("... everything else is trailing whitespace - copy {} chars", proc.src.len - proc.rpos); proc.copy(proc.src.len - proc.rpos); } } template template void ParseEngine::_filter_ws_skip_trailing(FilterProcessor &proc) { if(!_filter_ws_handle_to_first_non_space(proc)) { _c4dbgfws("... everything else is trailing whitespace - skip {} chars", proc.src.len - proc.rpos); proc.skip(proc.src.len - proc.rpos); } } #undef _c4dbgfws //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /* plain scalars */ // a debugging scaffold: #if 0 #define _c4dbgfps(fmt, ...) _c4dbgpf("filt_plain[{}->{}]: " fmt, proc.rpos, proc.wpos, __VA_ARGS__) #else #define _c4dbgfps(fmt, ...) #endif template template void ParseEngine::_filter_nl_plain(FilterProcessor &C4_RESTRICT proc, size_t indentation) { RYML_ASSERT_PARSE_CB_(this->callbacks(), proc.curr() == '\n', m_evt_handler->m_curr->pos); _c4dbgfps("found newline. sofar={}", prs_(proc.sofar())); size_t ii = proc.rpos; const size_t numnl_following = _count_following_newlines(proc.src, &ii, indentation); if(numnl_following) { proc.set('\n', numnl_following); _c4dbgfps("{} consecutive (empty) lines {}. totalws={}", 1+numnl_following, ii < proc.src.len ? "in the middle" : "at the end", proc.rpos-ii); } else { const size_t ret = proc.src.first_not_of(" \t", proc.rpos+1); if(ret != npos) { proc.set(' '); _c4dbgfps("single newline. convert to space. ret={}/{}. sofar={}", ii, proc.src.len, prs_(proc.sofar())); } else { _c4dbgfps("last newline, everything else is whitespace. ii={}/{}", ii, proc.src.len); ii = proc.src.len; } } proc.rpos = ii; } template template auto ParseEngine::_filter_plain(FilterProcessor &C4_RESTRICT proc, size_t indentation) -> decltype(proc.result()) { RYML_ASSERT_PARSE_CB_(this->callbacks(), indentation != npos, m_evt_handler->m_curr->pos); _c4dbgfps("before={}", prs_(proc.src)); while(proc.has_more_chars()) { const char curr = proc.curr(); _c4dbgfps("'{}', sofar={}", _c4prc(curr), prs_(proc.sofar())); switch(curr) { case ' ': RYML_WITH_TAB_TOKENS_(case '\t':) _c4dbgfps("whitespace", curr); _filter_ws_skip_trailing(proc); break; case '\n': _c4dbgfps("newline", curr); _filter_nl_plain(proc, /*indentation*/indentation); break; case '\r': // skip \r --- https://stackoverflow.com/questions/1885900 _c4dbgfps("carriage return, ignore", curr); proc.skip(); break; default: proc.copy(); break; } } _c4dbgfps("after={}", prs_(proc.sofar())); return proc.result(); } #undef _c4dbgfps template FilterResult ParseEngine::filter_scalar_plain(csubstr scalar, substr dst, size_t indentation) { FilterProcessorSrcDst proc(scalar, dst); return _filter_plain(proc, indentation); } template FilterResult ParseEngine::filter_scalar_plain_in_place(substr dst, size_t cap, size_t indentation) { FilterProcessorInplaceEndExtending proc(dst, cap); return _filter_plain(proc, indentation); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /* single quoted */ // a debugging scaffold: #if 0 #define _c4dbgfsq(fmt, ...) _c4dbgpf("filt_squo[{}->{}]: " fmt, proc.rpos, proc.wpos, __VA_ARGS__) #else #define _c4dbgfsq(fmt, ...) #endif template template void ParseEngine::_filter_nl_squoted(FilterProcessor &C4_RESTRICT proc) { RYML_ASSERT_PARSE_CB_(this->callbacks(), proc.curr() == '\n', m_evt_handler->m_curr->pos); _c4dbgfsq("found newline. sofar={}", prs_(proc.sofar())); size_t ii = proc.rpos; const size_t numnl_following = _count_following_newlines(proc.src, &ii); if(numnl_following) { proc.set('\n', numnl_following); _c4dbgfsq("{} consecutive (empty) lines {}. totalws={}", 1+numnl_following, ii < proc.src.len ? "in the middle" : "at the end", proc.rpos-ii); } else { const size_t ret = proc.src.first_not_of(" \t", proc.rpos+1); if(ret != npos) { proc.set(' '); _c4dbgfsq("single newline. convert to space. ret={}/{}. sofar={}", ii, proc.src.len, prs_(proc.sofar())); } else { proc.set(' '); _c4dbgfsq("single newline. convert to space. ii={}/{}. sofar={}", ii, proc.src.len, prs_(proc.sofar())); } } proc.rpos = ii; } template template auto ParseEngine::_filter_squoted(FilterProcessor &C4_RESTRICT proc) -> decltype(proc.result()) { _c4dbgfsq("before={}", prs_(proc.src)); // from the YAML spec for double-quoted scalars: // https://yaml.org/spec/1.2-old/spec.html#style/flow/single-quoted while(proc.has_more_chars()) { const char curr = proc.curr(); _c4dbgfsq("'{}', sofar={}", _c4prc(curr), prs_(proc.sofar())); switch(curr) { case ' ': case '\t': _c4dbgfsq("whitespace", curr); _filter_ws_copy_trailing(proc); break; case '\n': _c4dbgfsq("newline", curr); _filter_nl_squoted(proc); break; case '\r': // skip \r --- https://stackoverflow.com/questions/1885900 _c4dbgfsq("skip cr", curr); proc.skip(); break; case '\'': _c4dbgfsq("squote", curr); if(proc.next() == '\'') { _c4dbgfsq("two consecutive squotes", curr); proc.skip(); proc.copy(); } else { _c4err("filter error"); } break; default: proc.copy(); break; } } _c4dbgfsq(": #filteredchars={} after={}", proc.src.len-proc.sofar().len, prs_(proc.sofar())); return proc.result(); } #undef _c4dbgfsq template FilterResult ParseEngine::filter_scalar_squoted(csubstr scalar, substr dst) { FilterProcessorSrcDst proc(scalar, dst); return _filter_squoted(proc); } template FilterResult ParseEngine::filter_scalar_squoted_in_place(substr dst, size_t cap) { FilterProcessorInplaceEndExtending proc(dst, cap); return _filter_squoted(proc); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /* double quoted */ // a debugging scaffold: #if 0 #define _c4dbgfdq(fmt, ...) _c4dbgpf("filt_dquo[{}->{}]: " fmt, proc.rpos, proc.wpos, __VA_ARGS__) #else #define _c4dbgfdq(...) #endif template template void ParseEngine::_filter_nl_dquoted(FilterProcessor &C4_RESTRICT proc) { RYML_ASSERT_PARSE_CB_(this->callbacks(), proc.curr() == '\n', m_evt_handler->m_curr->pos); _c4dbgfdq("found newline. sofar={}", prs_(proc.sofar())); size_t ii = proc.rpos; const size_t numnl_following = _count_following_newlines(proc.src, &ii); if(numnl_following) { proc.set('\n', numnl_following); _c4dbgfdq("{} consecutive (empty) lines {}. totalws={}", 1+numnl_following, ii < proc.src.len ? "in the middle" : "at the end", proc.rpos-ii); } else { const size_t ret = proc.src.first_not_of(" \t", proc.rpos+1); if(ret != npos) { proc.set(' '); _c4dbgfdq("single newline. convert to space. ret={}/{}. sofar={}", ii, proc.src.len, prs_(proc.sofar())); } else { proc.set(' '); _c4dbgfdq("single newline. convert to space. ii={}/{}. sofar={}", ii, proc.src.len, prs_(proc.sofar())); } if(ii < proc.src.len && proc.src.str[ii] == '\\') { _c4dbgfdq("backslash at [{}]", ii); const char next = ii+1 < proc.src.len ? proc.src.str[ii+1] : '\0'; if(next == ' ' || next == '\t') { _c4dbgfdq("extend skip to backslash", ""); ++ii; } } } proc.rpos = ii; } template template void ParseEngine::_filter_dquoted_backslash_decode(FilterProcessor &C4_RESTRICT proc, size_t sz) { const size_t szp1 = sz + 1u; if C4_UNLIKELY(proc.rpos + szp1 >= proc.src.len) _c4err("codepoint requires {} hex digits. scalar pos={}", sz, proc.rpos); char readbuf[8]; csubstr codepoint = proc.src.sub(proc.rpos + 2u, sz); _c4dbgfdq("utf8 ~~~{}~~~ rpos={} rem=~~~{}~~~", codepoint, proc.rpos, proc.src.sub(proc.rpos)); uint32_t codepoint_val = {}; if C4_UNLIKELY(!read_hex(codepoint, &codepoint_val)) _c4err("failed to parse codepoint. scalar pos={}", proc.rpos); const size_t numbytes = decode_code_point((uint8_t*)readbuf, sizeof(readbuf), codepoint_val); if C4_UNLIKELY(numbytes == 0) _c4err("failed to decode code point={}", proc.rpos); RYML_ASSERT_PARSE_CB_(callbacks(), numbytes <= 4, m_evt_handler->m_curr->pos); proc.translate_esc_bulk(readbuf, numbytes, /*nread*/szp1); _c4dbgfdq("utf8 after rpos={} rem=~~~{}~~~", proc.rpos, proc.src.sub(proc.rpos)); } template template void ParseEngine::_filter_dquoted_backslash(FilterProcessor &C4_RESTRICT proc) { char next = proc.next(); _c4dbgfdq("backslash, next='{}'", _c4prc(next)); if(next == '\r') { if(proc.rpos+2 < proc.src.len && proc.src.str[proc.rpos+2] == '\n') { proc.skip(); // newline escaped with \ -- skip both (add only one as i is loop-incremented) next = '\n'; _c4dbgfdq("[{}]: was \\r\\n, now next='\\n'", proc.rpos); } } if(next == '\n') { size_t ii = proc.rpos + 2; for( ; ii < proc.src.len; ++ii) { // skip leading whitespace if(proc.src.str[ii] == ' ' || proc.src.str[ii] == '\t') ; else break; } proc.skip(ii - proc.rpos); } else if(next == '"' || next == '/' || next == ' ' || next == '\t') { // escapes for json compatibility proc.translate_esc(next); _c4dbgfdq("here, used '{}'", _c4prc(next)); } else if(next == '\r') { proc.skip(); } else if(next == 'n') { proc.translate_esc('\n'); } else if(next == 'r') { proc.translate_esc('\r'); } else if(next == 't') { proc.translate_esc('\t'); } else if(next == '\\') { proc.translate_esc('\\'); } else if(next == 'x') // 2-digit Unicode escape (\xXX), code point 0x00–0xFF { _filter_dquoted_backslash_decode(proc, 2u); } else if(next == 'u') // 4-digit Unicode escape (\uXXXX), code point 0x0000–0xFFFF { _filter_dquoted_backslash_decode(proc, 4u); } else if(next == 'U') // 8-digit Unicode escape (\UXXXXXXXX), full 32-bit code point { _filter_dquoted_backslash_decode(proc, 8u); } // https://yaml.org/spec/1.2.2/#rule-c-ns-esc-char else if(next == '0') { proc.translate_esc('\0'); } else if(next == 'b') // backspace { proc.translate_esc('\b'); } else if(next == 'f') // form feed { proc.translate_esc('\f'); } else if(next == 'a') // bell character { proc.translate_esc('\a'); } else if(next == 'v') // vertical tab { proc.translate_esc('\v'); } else if(next == 'e') // escape character { proc.translate_esc('\x1b'); } else if(next == '_') // unicode non breaking space \u00a0 { // https://www.compart.com/en/unicode/U+00a0 const char payload[] = { RYML_CHCONST_(-0x3e, 0xc2), RYML_CHCONST_(-0x60, 0xa0), }; proc.translate_esc_bulk(payload, /*nwrite*/2, /*nread*/1); } else if(next == 'N') // unicode next line \u0085 { // https://www.compart.com/en/unicode/U+0085 const char payload[] = { RYML_CHCONST_(-0x3e, 0xc2), RYML_CHCONST_(-0x7b, 0x85), }; proc.translate_esc_bulk(payload, /*nwrite*/2, /*nread*/1); } else if(next == 'L') // unicode line separator \u2028 { // https://www.utf8-chartable.de/unicode-utf8-table.pl?start=8192&number=1024&names=-&utf8=0x&unicodeinhtml=hex const char payload[] = { RYML_CHCONST_(-0x1e, 0xe2), RYML_CHCONST_(-0x80, 0x80), RYML_CHCONST_(-0x58, 0xa8), }; proc.translate_esc_extending(payload, /*nwrite*/3, /*nread*/1); } else if(next == 'P') // unicode paragraph separator \u2029 { // https://www.utf8-chartable.de/unicode-utf8-table.pl?start=8192&number=1024&names=-&utf8=0x&unicodeinhtml=hex const char payload[] = { RYML_CHCONST_(-0x1e, 0xe2), RYML_CHCONST_(-0x80, 0x80), RYML_CHCONST_(-0x57, 0xa9), }; proc.translate_esc_extending(payload, /*nwrite*/3, /*nread*/1); } else if(next == '\0') { proc.skip(); } else { _c4err("unknown character '{}' after '\\' pos={}", _c4prc(next), proc.rpos); } _c4dbgfdq("backslash...sofar={}", prs_(proc.sofar())); } template template auto ParseEngine::_filter_dquoted(FilterProcessor &C4_RESTRICT proc) -> decltype(proc.result()) { _c4dbgfdq("before={}", prs_(proc.src)); // from the YAML spec for double-quoted scalars: // https://yaml.org/spec/1.2-old/spec.html#style/flow/double-quoted while(proc.has_more_chars()) { const char curr = proc.curr(); _c4dbgfdq("'{}' sofar={}", _c4prc(curr), prs_(proc.sofar())); switch(curr) { case ' ': case '\t': { _c4dbgfdq("whitespace", curr); _filter_ws_copy_trailing(proc); break; } case '\n': { _c4dbgfdq("newline", curr); _filter_nl_dquoted(proc); break; } case '\r': // skip \r --- https://stackoverflow.com/questions/1885900 { _c4dbgfdq("carriage return, ignore", curr); proc.skip(); break; } case '\\': { _filter_dquoted_backslash(proc); break; } default: { proc.copy(); break; } } } _c4dbgfdq("after={}", prs_(proc.sofar())); return proc.result(); } #undef _c4dbgfdq template FilterResult ParseEngine::filter_scalar_dquoted(csubstr scalar, substr dst) { FilterProcessorSrcDst proc(scalar, dst); return _filter_dquoted(proc); } template FilterResultExtending ParseEngine::filter_scalar_dquoted_in_place(substr dst, size_t cap) { FilterProcessorInplaceMidExtending proc(dst, cap); return _filter_dquoted(proc); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // block filtering helpers template template void ParseEngine::_filter_chomp(FilterProcessor &C4_RESTRICT proc, BlockChomp_e chomp, size_t indentation) { RYML_ASSERT_PARSE_CB_(this->callbacks(), chomp == CHOMP_CLIP || chomp == CHOMP_KEEP || chomp == CHOMP_STRIP, m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(this->callbacks(), proc.rem().first_not_of(" \n\r") == npos, m_evt_handler->m_curr->pos); // a debugging scaffold: #if 0 #define _c4dbgchomp(fmt, ...) _c4dbgpf("chomp[{}->{}]: " fmt, proc.rpos, proc.wpos, __VA_ARGS__) #else #define _c4dbgchomp(...) #endif // advance to the last line having spaces beyond the indentation { size_t last = _find_last_newline_and_larger_indentation(proc.rem(), indentation); if(last != npos) { _c4dbgchomp("found newline and larger indentation. last={}", last); last = proc.rpos + last + size_t(1) + indentation; // last started at to-be-read. RYML_ASSERT_PARSE_CB_(this->callbacks(), last <= proc.src.len, m_evt_handler->m_curr->pos); // remove indentation spaces, copy the rest while((proc.rpos < last) && proc.has_more_chars()) { const char curr = proc.curr(); _c4dbgchomp("curr='{}'", _c4prc(curr)); switch(curr) { case '\n': { _c4dbgchomp("newline! remlen={}", proc.rem().len); proc.copy(); // are there spaces after the newline? csubstr at_next_line = proc.rem(); if(at_next_line.begins_with(' ')) { _c4dbgchomp("next line begins with spaces. indentation={}", indentation); // there are spaces. size_t first_non_space = at_next_line.first_not_of(' '); _c4dbgchomp("first_non_space={}", first_non_space); if(first_non_space == npos) { _c4dbgchomp("{} spaces, to the end", at_next_line.len); first_non_space = at_next_line.len; } if(first_non_space <= indentation) { _c4dbgchomp("skip spaces={}<=indentation={}", first_non_space, indentation); proc.skip(first_non_space); } else { _c4dbgchomp("skip indentation={}{}]: " fmt, proc.rpos, proc.wpos, __VA_ARGS__) #else #define _c4dbgfb(...) #endif template template void ParseEngine::_filter_block_indentation(FilterProcessor &C4_RESTRICT proc, size_t indentation) { csubstr rem = proc.rem(); // remaining if(rem.len) { size_t first = rem.first_not_of(' '); if(first != npos) { _c4dbgfb("{} spaces follow before next nonws character", first); if(first < indentation) { _c4dbgfb("skip {}<{} spaces from indentation", first, indentation); proc.skip(first); } else { _c4dbgfb("skip {} spaces from indentation", indentation); proc.skip(indentation); } } #ifdef RYML_NO_COVERAGE__TO_BE_DELETED else { _c4dbgfb("all spaces to the end: {} spaces", first); first = rem.len; if(first) { if(first < indentation) { _c4dbgfb("skip everything", first); proc.skip(proc.src.len - proc.rpos); } else { _c4dbgfb("skip {} spaces from indentation", indentation); proc.skip(indentation); } } } #endif } } template template size_t ParseEngine::_handle_all_whitespace(FilterProcessor &C4_RESTRICT proc, BlockChomp_e chomp) { csubstr contents = proc.src.trimr(" \n\r"); _c4dbgfb("ws: contents_len={} wslen={}", contents.len, proc.src.len-contents.len); if(!contents.len) { _c4dbgfb("ws: all whitespace: len={}", proc.src.len); if(chomp == CHOMP_KEEP && proc.src.len) { _c4dbgfb("ws: chomp=KEEP all {} newlines", proc.src.count('\n')); while(proc.has_more_chars()) { const char curr = proc.curr(); if(curr == '\n') proc.copy(); else proc.skip(); } if(!proc.wpos) { proc.set('\n'); } } } return contents.len; } template template size_t ParseEngine::_extend_to_chomp(FilterProcessor &C4_RESTRICT proc, size_t contents_len) { _c4dbgfb("contents_len={}", contents_len); RYML_ASSERT_PARSE_CB_(this->callbacks(), contents_len > 0u, m_evt_handler->m_curr->pos); // extend contents to just before the first newline at the end, // in case it is preceded by spaces size_t firstnewl = proc.src.first_of('\n', contents_len); if(firstnewl != npos) { contents_len = firstnewl; _c4dbgfb("contents_len={} <--- firstnewl={}", contents_len, firstnewl); } else { contents_len = proc.src.len; _c4dbgfb("contents_len={} <--- src.len={}", contents_len, proc.src.len); } return contents_len; } #undef _c4dbgfb //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // a debugging scaffold: #if 0 #define _c4dbgfbl(fmt, ...) _c4dbgpf("filt_block_lit[{}->{}]: " fmt, proc.rpos, proc.wpos, __VA_ARGS__) #else #define _c4dbgfbl(...) #endif template template auto ParseEngine::_filter_block_literal(FilterProcessor &C4_RESTRICT proc, size_t indentation, BlockChomp_e chomp) -> decltype(proc.result()) { _c4dbgfbl("indentation={} before={}", indentation, prs_(proc.src)); size_t contents_len = _handle_all_whitespace(proc, chomp); if(!contents_len) return proc.result(); contents_len = _extend_to_chomp(proc, contents_len); _c4dbgfbl("to filter={}", prs_(proc.src.first(contents_len))); _filter_block_indentation(proc, indentation); // now filter the bulk while(proc.has_more_chars(/*maxpos*/contents_len)) { const char curr = proc.curr(); _c4dbgfbl("'{}' sofar={}", _c4prc(curr), prs_(proc.sofar())); switch(curr) { case '\n': { _c4dbgfbl("found newline. skip indentation on the next line", curr); proc.copy(); // copy the newline _filter_block_indentation(proc, indentation); break; } case '\r': proc.skip(); break; default: proc.copy(); break; } } _c4dbgfbl("before chomp: #tochomp={} sofar={}", proc.rem().len, prs_(proc.sofar())); _filter_chomp(proc, chomp, indentation); _c4dbgfbl("final={}", prs_(proc.sofar())); return proc.result(); } #undef _c4dbgfbl template FilterResult ParseEngine::filter_scalar_block_literal(csubstr scalar, substr dst, size_t indentation, BlockChomp_e chomp) { FilterProcessorSrcDst proc(scalar, dst); return _filter_block_literal(proc, indentation, chomp); } template FilterResult ParseEngine::filter_scalar_block_literal_in_place(substr scalar, size_t cap, size_t indentation, BlockChomp_e chomp) { FilterProcessorInplaceEndExtending proc(scalar, cap); return _filter_block_literal(proc, indentation, chomp); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // a debugging scaffold: #if 0 #define _c4dbgfbf(fmt, ...) _c4dbgpf("filt_block_folded[{}->{}]: " fmt, proc.rpos, proc.wpos, __VA_ARGS__) #else #define _c4dbgfbf(...) #endif template template void ParseEngine::_filter_block_folded_newlines_leading(FilterProcessor &C4_RESTRICT proc, size_t indentation, size_t len) { _filter_block_indentation(proc, indentation); while(proc.has_more_chars(len)) { const char curr = proc.curr(); _c4dbgfbf("'{}' sofar={}", _c4prc(curr), prs_(proc.sofar())); switch(curr) { case '\n': _c4dbgfbf("newline.", curr); proc.copy(); _filter_block_indentation(proc, indentation); break; case '\r': proc.skip(); break; case ' ': case '\t': { size_t first = proc.rem().first_not_of(" \t"); _c4dbgfbf("space. first={}", first); if(first == npos) first = proc.rem().len; _c4dbgfbf("... indentation increased to {}", first); _filter_block_folded_indented_block(proc, indentation, len, first); break; } default: _c4dbgfbf("newl leading: not space, not newline. stop.", 0); return; } } } template template size_t ParseEngine::_filter_block_folded_newlines_compress(FilterProcessor &C4_RESTRICT proc, size_t num_newl, size_t wpos_at_first_newl) { switch(num_newl) { case 1u: _c4dbgfbf("... this is the first newline. turn into space. wpos={}", proc.wpos); wpos_at_first_newl = proc.wpos; proc.skip(); proc.set(' '); break; case 2u: _c4dbgfbf("... this is the second newline. prev space (at wpos={}) must be newline", wpos_at_first_newl); RYML_ASSERT_PARSE_CB_(this->callbacks(), wpos_at_first_newl != npos, m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(this->callbacks(), proc.sofar()[wpos_at_first_newl] == ' ', m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(this->callbacks(), wpos_at_first_newl + 1u == proc.wpos, m_evt_handler->m_curr->pos); proc.skip(); proc.set_at(wpos_at_first_newl, '\n'); RYML_ASSERT_PARSE_CB_(this->callbacks(), proc.sofar()[wpos_at_first_newl] == '\n', m_evt_handler->m_curr->pos); break; default: _c4dbgfbf("... subsequent newline (num_newl={}). copy", num_newl); proc.copy(); break; } return wpos_at_first_newl; } template template void ParseEngine::_filter_block_folded_newlines(FilterProcessor &C4_RESTRICT proc, size_t indentation, size_t len) { RYML_ASSERT_PARSE_CB_(this->callbacks(), proc.curr() == '\n', m_evt_handler->m_curr->pos); size_t num_newl = 0; size_t wpos_at_first_newl = npos; while(proc.has_more_chars(len)) { const char curr = proc.curr(); _c4dbgfbf("'{}' sofar={}", _c4prc(curr), prs_(proc.sofar())); switch(curr) { case '\n': { _c4dbgfbf("newline. sofar={}", num_newl); // NOTE: vs2022-32bit-release builds were giving wrong // results in this block, if it was written as either // as a switch(num_newl) or its equivalent if-form. // // For this reason, we're using a dedicated function // (**_compress), which seems to work around the issue. // // The manifested problem was that somewhere between the // assignment to curr and this point, proc.wpos (the // write-position of the processor) jumped to npos, which // made the write wrap-around! To make things worse, // enabling prints via _c4dbgpf() and _c4dbgfbf() made the // problem go away! // // The only way to make the problem appear with prints // enabled was by disabling all prints in this function // (including in the block which was moved to the compress // function) and then selectively enabling only some of // those prints. // // This may be due to some bug in the cl-x86 optimizer; or // it may be triggered by some UB which may be // inadvertedly present in this function or in the filter // processor. This is despite our best efforts to weed out // any such UB problem: neither clang-tidy nor none of the // sanitizers, or gcc's -fanalyzer pointed to any problems // in this code. // // In the end, moving this block to a separate function // was the only way to bury the problem. But it may // resurface again, as The Undead, rising to from the // grave to haunt us with his terrible presence. // // We may have to revisit this. With a stake, and lots of // garlic. wpos_at_first_newl = _filter_block_folded_newlines_compress(proc, ++num_newl, wpos_at_first_newl); _filter_block_indentation(proc, indentation); break; } case ' ': case '\t': { size_t first = proc.rem().first_not_of(" \t"); _c4dbgfbf("space. first={}", first); if(first == npos) first = proc.rem().len; _c4dbgfbf("... indentation increased to {}", first); if(num_newl) { _c4dbgfbf("... prev space (at wpos={}) must be newline", wpos_at_first_newl); proc.set_at(wpos_at_first_newl, '\n'); } if(num_newl > 1u) { _c4dbgfbf("... add missing newline", wpos_at_first_newl); proc.set('\n'); } _filter_block_folded_indented_block(proc, indentation, len, first); num_newl = 0; wpos_at_first_newl = npos; break; } case '\r': proc.skip(); break; default: _c4dbgfbf("not space, not newline. stop.", 0); return; } } } template template void ParseEngine::_filter_block_folded_indented_block(FilterProcessor &C4_RESTRICT proc, size_t indentation, size_t len, size_t curr_indentation) noexcept { RYML_ASSERT_PARSE_CB_(this->callbacks(), (proc.rem().first_not_of(" \t") == curr_indentation) || (proc.rem().first_not_of(" \t") == npos), m_evt_handler->m_curr->pos); if(curr_indentation) proc.copy(curr_indentation); while(proc.has_more_chars(len)) { const char curr = proc.curr(); _c4dbgfbf("'{}' sofar={}", _c4prc(curr), prs_(proc.sofar())); switch(curr) { case '\n': { proc.copy(); _filter_block_indentation(proc, indentation); csubstr rem = proc.rem(); const size_t first = rem.first_not_of(' '); _c4dbgfbf("newline. firstns={}", first); if(first == 0) { const char c = rem[first]; _c4dbgfbf("firstns={}='{}'", first, _c4prc(c)); if(c != '\n' && c != '\r') { _c4dbgfbf("done with indented block", first); goto endloop; } } else if(first != npos) { proc.copy(first); _c4dbgfbf("copy all {} spaces", first); } break; } break; case '\r': proc.skip(); break; default: proc.copy(); break; } } endloop: return; } template template auto ParseEngine::_filter_block_folded(FilterProcessor &C4_RESTRICT proc, size_t indentation, BlockChomp_e chomp) -> decltype(proc.result()) { _c4dbgfbf("indentation={} before={}", indentation, prs_(proc.src)); size_t contents_len = _handle_all_whitespace(proc, chomp); if(!contents_len) return proc.result(); contents_len = _extend_to_chomp(proc, contents_len); _c4dbgfbf("to filter={}", prs_(proc.src.first(contents_len))); _filter_block_folded_newlines_leading(proc, indentation, contents_len); // now filter the bulk while(proc.has_more_chars(/*maxpos*/contents_len)) { const char curr = proc.curr(); _c4dbgfbf("'{}' sofar={}", _c4prc(curr), prs_(proc.sofar())); switch(curr) { case '\n': { _c4dbgfbf("found newline", curr); _filter_block_folded_newlines(proc, indentation, contents_len); break; } case '\r': proc.skip(); break; default: proc.copy(); break; } } _c4dbgfbf("before chomp: #tochomp={} sofar={}", proc.rem().len, prs_(proc.sofar())); _filter_chomp(proc, chomp, indentation); _c4dbgfbf("final={}", proc.sofar().len, prs_(proc.sofar())); return proc.result(); } #undef _c4dbgfbf template FilterResult ParseEngine::filter_scalar_block_folded(csubstr scalar, substr dst, size_t indentation, BlockChomp_e chomp) { FilterProcessorSrcDst proc(scalar, dst); return _filter_block_folded(proc, indentation, chomp); } template FilterResult ParseEngine::filter_scalar_block_folded_in_place(substr scalar, size_t cap, size_t indentation, BlockChomp_e chomp) { FilterProcessorInplaceEndExtending proc(scalar, cap); return _filter_block_folded(proc, indentation, chomp); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- template csubstr ParseEngine::_filter_scalar_plain(substr s, size_t indentation) { _c4dbgpf("filtering plain scalar: s={}", prs_(s)); FilterResult r = this->filter_scalar_plain_in_place(s, s.len, indentation); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, r.valid(), m_evt_handler->m_curr->pos); _c4dbgpf("filtering plain scalar: success! s={}", prs_(r.get())); return r.get(); } //----------------------------------------------------------------------------- template csubstr ParseEngine::_filter_scalar_squot(substr s) { _c4dbgpf("filtering squo scalar: s={}", prs_(s)); FilterResult r = this->filter_scalar_squoted_in_place(s, s.len); RYML_ASSERT_PARSE_CB_(this->callbacks(), r.valid(), m_evt_handler->m_curr->pos); _c4dbgpf("filtering squo scalar: success! s={}", prs_(r.get())); return r.get(); } //----------------------------------------------------------------------------- template csubstr ParseEngine::_filter_scalar_dquot(substr s) { _c4dbgpf("filtering dquo scalar: s={}", prs_(s)); FilterResultExtending r = this->filter_scalar_dquoted_in_place(s, s.len); if C4_LIKELY(r.valid()) { _c4dbgpf("filtering dquo scalar: success! s={}", prs_(r.get())); return r.get(); } else { const size_t len = r.required_len(); _c4dbgpf("filtering dquo scalar: not enough space: needs {}, have {}", len, s.len); substr dst = _alloc_arena(len, &s); _c4dbgpf("filtering dquo scalar: dst.len={}", dst.len); if(dst.str) { RYML_ASSERT_PARSE_CB_(this->callbacks(), dst.len == len, m_evt_handler->m_curr->pos); FilterResult rsd = this->filter_scalar_dquoted(s, dst); _c4dbgpf("filtering dquo scalar: ... result now needs {} was {}", rsd.required_len(), len); RYML_ASSERT_PARSE_CB_(this->callbacks(), rsd.required_len() <= len, m_evt_handler->m_curr->pos); // may be smaller! RYML_CHECK_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, rsd.valid(), m_evt_handler->m_curr->pos); _c4dbgpf("filtering dquo scalar: success! s={}", prs_(rsd.get())); return rsd.get(); } return dst; } } //----------------------------------------------------------------------------- template csubstr ParseEngine::_move_scalar_left_and_add_newline(substr s) { if(s.is_sub(_buf())) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.str > _buf().str, m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, s.str-1 >= _buf().str, m_evt_handler->m_curr->pos); if(s.len) memmove(s.str - 1, s.str, s.len); --s.str; s.str[s.len] = '\n'; ++s.len; return s; } else { substr dst = _alloc_arena(s.len + 1, &s); if(s.len) memcpy(dst.str, s.str, s.len); dst[s.len] = '\n'; return dst; } } template csubstr ParseEngine::_filter_scalar_literal(substr s, size_t indentation, BlockChomp_e chomp) { _c4dbgpf("filtering block literal scalar: s={}", prs_(s)); FilterResult r = this->filter_scalar_block_literal_in_place(s, s.len, indentation, chomp); csubstr result; if C4_LIKELY(r.valid()) { result = r.get(); } else { _c4dbgpf("filtering block literal scalar: not enough space: needs {}, have {}", r.required_len(), s.len); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, r.required_len() == s.len + 1, m_evt_handler->m_curr->pos); // this can only happen when adding a single newline in clip mode. // so we shift left the scalar by one place result = _move_scalar_left_and_add_newline(s); } _c4dbgpf("filtering block literal scalar: success! s={}", prs_(result)); return result; } //----------------------------------------------------------------------------- template csubstr ParseEngine::_filter_scalar_folded(substr s, size_t indentation, BlockChomp_e chomp) { _c4dbgpf("filtering block folded scalar: s={}", prs_(s)); FilterResult r = this->filter_scalar_block_folded_in_place(s, s.len, indentation, chomp); csubstr result; if C4_LIKELY(r.valid()) { result = r.get(); } else { _c4dbgpf("filtering block folded scalar: not enough space: needs {}, have {}", r.required_len(), s.len); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, r.required_len() == s.len + 1, m_evt_handler->m_curr->pos); // this can only happen when adding a single newline in clip mode. // so we shift left the scalar by one place result = _move_scalar_left_and_add_newline(s); } _c4dbgpf("filtering block folded scalar: success! s={}", prs_(result)); return result; } //----------------------------------------------------------------------------- template csubstr ParseEngine::_maybe_filter_key_scalar_plain(ScannedScalar const& C4_RESTRICT sc, size_t indentation) { if(sc.needs_filter) { if(m_options.scalar_filtering()) { return _filter_scalar_plain(sc.scalar, indentation); } else { _c4dbgp("plain scalar left unfiltered"); m_evt_handler->mark_key_scalar_unfiltered(); } } else { _c4dbgp("plain scalar doesn't need filtering"); } return sc.scalar; } template csubstr ParseEngine::_maybe_filter_val_scalar_plain(ScannedScalar const& C4_RESTRICT sc, size_t indentation) { if(sc.needs_filter) { if(m_options.scalar_filtering()) { return _filter_scalar_plain(sc.scalar, indentation); } else { _c4dbgp("plain scalar left unfiltered"); m_evt_handler->mark_val_scalar_unfiltered(); } } else { _c4dbgp("plain scalar doesn't need filtering"); } return sc.scalar; } //----------------------------------------------------------------------------- template csubstr ParseEngine::_maybe_filter_key_scalar_squot(ScannedScalar const& C4_RESTRICT sc) { if(sc.needs_filter) { if(m_options.scalar_filtering()) { return _filter_scalar_squot(sc.scalar); } else { _c4dbgp("squo key scalar left unfiltered"); m_evt_handler->mark_key_scalar_unfiltered(); } } else { _c4dbgp("squo key scalar doesn't need filtering"); } return sc.scalar; } template csubstr ParseEngine::_maybe_filter_val_scalar_squot(ScannedScalar const& C4_RESTRICT sc) { if(sc.needs_filter) { if(m_options.scalar_filtering()) { return _filter_scalar_squot(sc.scalar); } else { _c4dbgp("squo val scalar left unfiltered"); m_evt_handler->mark_val_scalar_unfiltered(); } } else { _c4dbgp("squo val scalar doesn't need filtering"); } return sc.scalar; } //----------------------------------------------------------------------------- template csubstr ParseEngine::_maybe_filter_key_scalar_dquot(ScannedScalar const& C4_RESTRICT sc) { if(sc.needs_filter) { if(m_options.scalar_filtering()) { return _filter_scalar_dquot(sc.scalar); } else { _c4dbgp("dquo scalar left unfiltered"); m_evt_handler->mark_key_scalar_unfiltered(); } } else { _c4dbgp("dquo scalar doesn't need filtering"); } return sc.scalar; } template csubstr ParseEngine::_maybe_filter_val_scalar_dquot(ScannedScalar const& C4_RESTRICT sc) { if(sc.needs_filter) { if(m_options.scalar_filtering()) { return _filter_scalar_dquot(sc.scalar); } else { _c4dbgp("dquo scalar left unfiltered"); m_evt_handler->mark_val_scalar_unfiltered(); } } else { _c4dbgp("dquo scalar doesn't need filtering"); } return sc.scalar; } //----------------------------------------------------------------------------- template csubstr ParseEngine::_maybe_filter_key_scalar_literal(ScannedBlock const& C4_RESTRICT sb) { if(m_options.scalar_filtering()) { return _filter_scalar_literal(sb.scalar, sb.indentation, sb.chomp); } else { _c4dbgp("literal scalar left unfiltered"); m_evt_handler->mark_key_scalar_unfiltered(); } return sb.scalar; } template csubstr ParseEngine::_maybe_filter_val_scalar_literal(ScannedBlock const& C4_RESTRICT sb) { if(m_options.scalar_filtering()) { return _filter_scalar_literal(sb.scalar, sb.indentation, sb.chomp); } else { _c4dbgp("literal scalar left unfiltered"); m_evt_handler->mark_val_scalar_unfiltered(); } return sb.scalar; } //----------------------------------------------------------------------------- template csubstr ParseEngine::_maybe_filter_key_scalar_folded(ScannedBlock const& C4_RESTRICT sb) { if(m_options.scalar_filtering()) { return _filter_scalar_folded(sb.scalar, sb.indentation, sb.chomp); } else { _c4dbgp("folded scalar left unfiltered"); m_evt_handler->mark_key_scalar_unfiltered(); } return sb.scalar; } template csubstr ParseEngine::_maybe_filter_val_scalar_folded(ScannedBlock const& C4_RESTRICT sb) { if(m_options.scalar_filtering()) { return _filter_scalar_folded(sb.scalar, sb.indentation, sb.chomp); } else { _c4dbgp("folded scalar left unfiltered"); m_evt_handler->mark_val_scalar_unfiltered(); } return sb.scalar; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- #ifdef RYML_DBG // !!! <---------------------------------- template void ParseEngine::add_flags(ParserFlag_t on) { ParserState *s = m_evt_handler->m_curr; char buf1_[64], buf2_[64], buf3_[64]; csubstr buf1 = detail::_parser_flags_to_str(buf1_, on); csubstr buf2 = detail::_parser_flags_to_str(buf2_, s->flags); csubstr buf3 = detail::_parser_flags_to_str(buf3_, s->flags|on); _c4dbgpf("state[{}]: add {}: before={} after={}", s->level, buf1, buf2, buf3); s->flags |= on; } template void ParseEngine::addrem_flags(ParserFlag_t on, ParserFlag_t off) { ParserState *s = m_evt_handler->m_curr; char buf1_[64], buf2_[64], buf3_[64], buf4_[64]; csubstr buf1 = detail::_parser_flags_to_str(buf1_, on); csubstr buf2 = detail::_parser_flags_to_str(buf2_, off); csubstr buf3 = detail::_parser_flags_to_str(buf3_, s->flags); csubstr buf4 = detail::_parser_flags_to_str(buf4_, (~off)&((s->flags|on))); _c4dbgpf("state[{}]: add {} / rem {}: before={} after={}", s->level, buf1, buf2, buf3, buf4); RYML_ASSERT_BASIC_((on & off) == ParserFlag_t(0)); s->flags &= ~off; s->flags |= on; } template void ParseEngine::rem_flags(ParserFlag_t off) { ParserState *s = m_evt_handler->m_curr; char buf1_[64], buf2_[64], buf3_[64]; csubstr buf1 = detail::_parser_flags_to_str(buf1_, off); csubstr buf2 = detail::_parser_flags_to_str(buf2_, s->flags); csubstr buf3 = detail::_parser_flags_to_str(buf3_, s->flags&(~off)); _c4dbgpf("state[{}]: rem {}: before={} after={}", s->level, buf1, buf2, buf3); s->flags &= ~off; } inline C4_NO_INLINE csubstr detail::_parser_flags_to_str(substr buf, ParserFlag_t flags) { size_t pos = 0; bool gotone = false; #define _prflag(fl) \ if((flags & fl) == (fl)) \ { \ if(gotone) \ { \ if(pos + 1 < buf.len) \ buf[pos] = '|'; \ ++pos; \ } \ csubstr fltxt = #fl; \ if(pos + fltxt.len <= buf.len) \ memcpy(buf.str + pos, fltxt.str, fltxt.len); \ pos += fltxt.len; \ gotone = true; \ } _prflag(RTOP); _prflag(RUNK); _prflag(RMAP); _prflag(RSEQ); _prflag(RFLOW); _prflag(RBLCK); _prflag(QMRK); _prflag(RKEY); _prflag(RVAL); _prflag(RKCL); _prflag(RNXT); _prflag(SSCL); _prflag(QSCL); _prflag(RSET); _prflag(RDOC); _prflag(NDOC); _prflag(USTY); _prflag(RSEQIMAP); #undef _prflag if(pos == 0) if(buf.len > 0) buf[pos++] = '0'; RYML_CHECK_BASIC_(pos <= buf.len); return buf.first(pos); } #endif // RYML_DBG !!! <---------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- template csubstr ParseEngine::location_contents(Location const& loc) const { RYML_ASSERT_BASIC_CB_(m_evt_handler->m_stack.m_callbacks, loc.offset < _buf().len); return _buf().sub(loc.offset); } template Location ParseEngine::val_location(const char *val) const { if C4_UNLIKELY(val == nullptr) return {m_evt_handler->m_curr->pos.name, 0, 0, 0}; RYML_CHECK_BASIC_CB_(m_evt_handler->m_stack.m_callbacks, m_options.locations()); // NOTE: if any of these checks fails, the parser needs to be // instantiated with locations enabled. RYML_ASSERT_BASIC_CB_(m_evt_handler->m_stack.m_callbacks, m_options.locations()); RYML_ASSERT_BASIC_CB_(m_evt_handler->m_stack.m_callbacks, !_locations_dirty()); RYML_ASSERT_BASIC_CB_(m_evt_handler->m_stack.m_callbacks, m_newline_offsets != nullptr); RYML_ASSERT_BASIC_CB_(m_evt_handler->m_stack.m_callbacks, m_newline_offsets_size > 0); // NOTE: the pointer needs to belong to the buffer that was used to parse. csubstr src = _buf(); RYML_CHECK_BASIC_CB_(m_evt_handler->m_stack.m_callbacks, val != nullptr || src.str == nullptr); RYML_CHECK_BASIC_CB_(m_evt_handler->m_stack.m_callbacks, (val >= src.begin() && val <= src.end()) || (src.str == nullptr && val == nullptr)); // ok. search the first stored newline after the given ptr using lineptr_type = size_t const* C4_RESTRICT; lineptr_type lineptr = nullptr; size_t offset = (size_t)(val - src.begin()); if(m_newline_offsets_size < RYML_LOCATIONS_SMALL_THRESHOLD) { // just do a linear search if the size is small. for(lineptr_type curr = m_newline_offsets, last = m_newline_offsets + m_newline_offsets_size; curr < last; ++curr) { if(*curr > offset) { lineptr = curr; break; } } } else { // do a bisection search if the size is not small. // // We could use std::lower_bound but this is simple enough and // spares the costly include of . size_t count = m_newline_offsets_size; lineptr = m_newline_offsets; while(count) { size_t step = count >> 1; lineptr_type it = lineptr + step; if(*it < offset) { lineptr = ++it; count -= step + 1; } else { count = step; } } } RYML_ASSERT_BASIC_CB_(m_evt_handler->m_stack.m_callbacks, lineptr); RYML_ASSERT_BASIC_CB_(m_evt_handler->m_stack.m_callbacks, lineptr >= m_newline_offsets); RYML_ASSERT_BASIC_CB_(m_evt_handler->m_stack.m_callbacks, lineptr <= m_newline_offsets + m_newline_offsets_size); RYML_ASSERT_BASIC_CB_(m_evt_handler->m_stack.m_callbacks, lineptr && (*lineptr > offset)); Location loc; loc.name = m_evt_handler->m_curr->pos.name; loc.offset = offset; loc.line = (size_t)(lineptr - m_newline_offsets); if(lineptr > m_newline_offsets) loc.col = (offset - *(lineptr-1) - 1u); else loc.col = offset; return loc; } template void ParseEngine::_prepare_locations() { csubstr src = _buf(); size_t numnewlines = 1u + src.count('\n'); _resize_locations(numnewlines); m_newline_offsets_size = 0; for(size_t i = 0; i < src.len; i++) if(src.str[i] == '\n') m_newline_offsets[m_newline_offsets_size++] = i; // NOLINT m_newline_offsets[m_newline_offsets_size++] = src.len; // NOLINT RYML_ASSERT_BASIC_CB_(m_evt_handler->m_stack.m_callbacks, m_newline_offsets_size == numnewlines); } template void ParseEngine::_resize_locations(size_t numnewlines) { numnewlines = numnewlines >= 16 ? numnewlines : 16; if(numnewlines > m_newline_offsets_capacity) { if(m_newline_offsets) RYML_CB_FREE_(m_evt_handler->m_stack.m_callbacks, m_newline_offsets, size_t, m_newline_offsets_capacity); m_newline_offsets = RYML_CB_ALLOC_HINT_(m_evt_handler->m_stack.m_callbacks, size_t, numnewlines, m_newline_offsets); m_newline_offsets_capacity = numnewlines; } } template bool ParseEngine::_locations_dirty() const { return !m_newline_offsets_size; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- template void ParseEngine::_handle_flow_skip_whitespace() { // don't assign to csubstr rem: otherwise, gcc12,13,14 -O3 -m32 misbuilds if(m_evt_handler->m_curr->line_contents.rem.len > 0) { if(m_evt_handler->m_curr->line_contents.rem.str[0] == ' ' || m_evt_handler->m_curr->line_contents.rem.str[0] == '\t') { _c4dbgpf("starts with whitespace: '{}'", _c4prc(m_evt_handler->m_curr->line_contents.rem.str[0])); _skipchars(" \t"); } // comments if(m_evt_handler->m_curr->line_contents.rem.begins_with('#')) { _c4dbgpf("it's a comment: {}", m_evt_handler->m_curr->line_contents.rem); _line_progressed(m_evt_handler->m_curr->line_contents.rem.len); } } } template void ParseEngine::_handle_flow_line_beginning() { _c4dbgpf("flow: indref={} indentation={}", m_evt_handler->m_curr->indref, m_evt_handler->m_curr->line_contents.indentation); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_curr->at_line_beginning(), m_evt_handler->m_curr->pos); if C4_UNLIKELY(m_evt_handler->m_curr->indentation_lt()) { csubstr trimmed = m_evt_handler->m_curr->line_contents.rem.sub(m_evt_handler->m_curr->line_contents.indentation); _c4dbgpf("flow: after indentation={}", prs_(trimmed)); if(trimmed.len && trimmed.triml(" \t").len) { _line_progressed(m_evt_handler->m_curr->line_contents.indentation); _c4err("bad indentation"); } } } template size_t ParseEngine::_handle_block_skip_leading_whitespace() { const size_t mark = m_evt_handler->m_curr->pos.offset; const size_t firstpos = m_evt_handler->m_curr->line_contents.rem.first_not_of(" \t"); _c4dbgpf("block: mark={} firstpos={}", mark, firstpos); if(firstpos != npos) { _c4dbgp("block: non empty line"); _line_progressed(firstpos); return mark; } else { _c4dbgp("block: rest of line is whitespace"); _line_progressed(m_evt_handler->m_curr->line_contents.rem.len); return npos; } } template void ParseEngine::_handle_block_check_leading_tabs(size_t start_mark, size_t end_mark) { _c4dbgpf("block: start_mark={} end_mark={}", start_mark, end_mark); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, end_mark >= start_mark, m_evt_handler->m_curr->pos); if(end_mark != start_mark) { csubstr leading = _buf().range(start_mark, end_mark); _c4dbgpf("block: leading[{}-{}]={}", start_mark, end_mark, prs_(leading, true)); size_t pos = leading.find('\t'); if(pos != npos) { size_t fno = leading.first_not_of(" \t"); if(fno == npos || pos < fno) _c4err("invalid tab character to the left"); } (void)leading; } } //----------------------------------------------------------------------------- template void ParseEngine::_handle_colon() { size_t curr = m_evt_handler->m_curr->pos.line; if C4_UNLIKELY(m_prev_colon != npos && curr == m_prev_colon) { _c4dbgpf("colon: prevline={} currline={}", m_prev_colon, curr); _c4err("two colons on same line"); } _c4dbgpf("colon: set prevline={}->{}", m_prev_colon, curr); m_prev_colon = curr; } template void ParseEngine::_add_annotation(Annotation *C4_RESTRICT dst, csubstr str) { _c4dbgpf("store annotation[{}]: {}", dst->num_entries, prs_(str)); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, dst->num_entries < C4_COUNTOF(dst->annotations), m_evt_handler->m_curr->pos); // NOLINT(bugprone-sizeof-expression) dst->annotations[dst->num_entries].str = str; dst->annotations[dst->num_entries].indentation = {}; dst->annotations[dst->num_entries].line = {}; dst->annotations[dst->num_entries].orig = {}; ++dst->num_entries; } template void ParseEngine::_add_annotation(Annotation *C4_RESTRICT dst, csubstr str, size_t indentation, size_t line) { _c4dbgpf("store annotation[{}]: '{}' indentation={} line={}", dst->num_entries, maybe_null_str_(str), indentation, line); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, dst->num_entries < C4_COUNTOF(dst->annotations), m_evt_handler->m_curr->pos); // NOLINT(bugprone-sizeof-expression) if C4_UNLIKELY(dst->num_entries && dst->annotations[0].line == line) { _c4err("parse error"); } dst->annotations[dst->num_entries].str = str; dst->annotations[dst->num_entries].indentation = indentation; dst->annotations[dst->num_entries].line = line; dst->annotations[dst->num_entries].orig = {}; ++dst->num_entries; } template void ParseEngine::_add_annotation(Annotation *C4_RESTRICT dst, csubstr str, size_t indentation, size_t line, csubstr orig) { _c4dbgpf("store annotation[{}]: '{}'->'{}' indentation={} line={}", dst->num_entries, orig, maybe_null_str_(str), indentation, line); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, dst->num_entries < C4_COUNTOF(dst->annotations), m_evt_handler->m_curr->pos); // NOLINT(bugprone-sizeof-expression) if C4_UNLIKELY(dst->num_entries && dst->annotations[0].line == line) { _c4err("parse error"); } dst->annotations[dst->num_entries].str = str; dst->annotations[dst->num_entries].indentation = indentation; dst->annotations[dst->num_entries].line = line; dst->annotations[dst->num_entries].orig = orig; ++dst->num_entries; } template bool ParseEngine::_annotations_require_key_container() const { return m_pending_tags.num_entries > 1 || m_pending_anchors.num_entries > 1; } template bool ParseEngine::_handle_annotations_before_unexpected_flow_token_rkey() { if(!(m_pending_tags.num_entries | m_pending_anchors.num_entries)) return false; _c4dbgpf("handle_annotations_before_unexpected_flow_comma_rkey, node={}", m_evt_handler->m_curr->node_id); if(m_pending_tags.num_entries) { _c4dbgpf("handle_annotations_before_unexpected_flow_comma_rkey, #tags={}", m_pending_tags.num_entries); if C4_LIKELY(m_pending_tags.num_entries == 1) { m_evt_handler->set_key_tag(m_pending_tags.annotations[0].str); _clear_annotations(&m_pending_tags); } else { _c4err("too many tags"); } } if(m_pending_anchors.num_entries) { _c4dbgpf("handle_annotations_before_unexpected_flow_comma, #anchors={}", m_pending_tags.num_entries); if C4_LIKELY(m_pending_anchors.num_entries == 1) { m_evt_handler->set_key_anchor(m_pending_anchors.annotations[0].str); _clear_annotations(&m_pending_anchors); } else { _c4err("too many anchors"); } } m_evt_handler->set_key_scalar_plain_empty(); m_evt_handler->set_val_scalar_plain_empty(); return true; } template void ParseEngine::_handle_annotations_before_blck_key_scalar() { _c4dbgpf("annotations_before_blck_key_scalar, node={}", m_evt_handler->m_curr->node_id); if(m_pending_tags.num_entries) { _c4dbgpf("annotations_before_blck_key_scalar, #tags={}", m_pending_tags.num_entries); if C4_LIKELY(m_pending_tags.num_entries == 1) { m_evt_handler->set_key_tag(m_pending_tags.annotations[0].str); _clear_annotations(&m_pending_tags); } else { _c4err("too many tags"); // LCOV_EXCL_LINE } } if(m_pending_anchors.num_entries) { _c4dbgpf("annotations_before_blck_key_scalar, #anchors={}", m_pending_anchors.num_entries); if C4_LIKELY(m_pending_anchors.num_entries == 1) { m_evt_handler->set_key_anchor(m_pending_anchors.annotations[0].str); _clear_annotations(&m_pending_anchors); } else { _c4err("too many anchors"); // LCOV_EXCL_LINE } } } template void ParseEngine::_handle_annotations_before_blck_val_scalar() { _c4dbgpf("annotations_before_blck_val_scalar, node={}", m_evt_handler->m_curr->node_id); if(m_pending_tags.num_entries) { _c4dbgpf("annotations_before_blck_val_scalar, #tags={}", m_pending_tags.num_entries); if C4_LIKELY(m_pending_tags.num_entries == 1) { m_evt_handler->set_val_tag(m_pending_tags.annotations[0].str); _clear_annotations(&m_pending_tags); } else { _c4err("too many tags"); } } if(m_pending_anchors.num_entries) { _c4dbgpf("annotations_before_blck_val_scalar, #anchors={}", m_pending_anchors.num_entries); if C4_LIKELY(m_pending_anchors.num_entries == 1) { m_evt_handler->set_val_anchor(m_pending_anchors.annotations[0].str); _clear_annotations(&m_pending_anchors); } else { _c4err("too many anchors"); } } } template void ParseEngine::_handle_annotations_before_start_mapblck(size_t current_line) { _c4dbgpf("annotations_before_start_mapblck, current_line={}", current_line); if(m_pending_tags.num_entries == 2) { _c4dbgp("2 tags, setting entry 0"); m_evt_handler->set_val_tag(m_pending_tags.annotations[0].str); } else if(m_pending_tags.num_entries == 1) { _c4dbgpf("1 tag. line={}, curr={}", m_pending_tags.annotations[0].line, current_line); if(m_pending_tags.annotations[0].line < current_line) { _c4dbgp("...tag is for the map. setting it."); m_evt_handler->set_val_tag(m_pending_tags.annotations[0].str); _clear_annotations(&m_pending_tags); } } // if(m_pending_anchors.num_entries == 2) { _c4dbgp("2 anchors, setting entry 0"); m_evt_handler->set_val_anchor(m_pending_anchors.annotations[0].str); } else if(m_pending_anchors.num_entries == 1) { _c4dbgpf("1 anchor. line={}, curr={}", m_pending_anchors.annotations[0].line, current_line); if(m_pending_anchors.annotations[0].line < current_line) { _c4dbgp("...anchor is for the map. setting it."); m_evt_handler->set_val_anchor(m_pending_anchors.annotations[0].str); _clear_annotations(&m_pending_anchors); } } } template void ParseEngine::_handle_annotations_before_start_mapblck_as_key() { _c4dbgp("annotations_before_start_mapblck_as_key"); switch(m_pending_tags.num_entries) { case 1u: _c4dbgpf("annotations_after_start_mapblck_as_key: 1 tag={} line={} currline=", prs_(m_pending_tags.annotations[0].str), m_pending_tags.annotations[0].line, m_evt_handler->m_curr->pos.line); if(m_pending_tags.annotations[0].line != m_evt_handler->m_curr->pos.line) { _c4dbgp("annotations_after_start_mapblck_as_key: is map tag"); m_evt_handler->set_key_tag(m_pending_tags.annotations[0].str); _clear_annotations(&m_pending_tags); } break; case 2u: _c4dbgpf("annotations_after_start_mapblck_as_key: 2 tags: {} -> {}", prs_(m_pending_tags.annotations[0].str), prs_(m_pending_tags.annotations[1].str)); m_evt_handler->set_key_tag(m_pending_tags.annotations[0].str); break; } switch(m_pending_anchors.num_entries) { case 1u: _c4dbgpf("annotations_after_start_mapblck_as_key: 1 anchor={} line={} currline=", m_pending_anchors.annotations[0].str, m_pending_anchors.annotations[0].line, m_evt_handler->m_curr->pos.line); if(m_pending_anchors.annotations[0].line != m_evt_handler->m_curr->pos.line) { _c4dbgp("annotations_after_start_mapblck_as_key: is map anchor"); m_evt_handler->set_key_anchor(m_pending_anchors.annotations[0].str); _clear_annotations(&m_pending_anchors); } break; case 2u: _c4dbgpf("annotations_after_start_mapblck_as_key: 2 anchors: {} -> {}", m_pending_anchors.annotations[0].str, m_pending_anchors.annotations[1].str); m_evt_handler->set_key_anchor(m_pending_anchors.annotations[0].str); break; } } template void ParseEngine::_handle_annotations_and_indentation_after_start_mapblck(size_t key_indentation, size_t key_line) { _c4dbgp("annotations_after_start_mapblck"); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_pending_tags.num_entries <= 2, m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_pending_anchors.num_entries <= 2, m_evt_handler->m_curr->pos); if(m_pending_anchors.num_entries || m_pending_tags.num_entries) { key_indentation = _select_indentation_from_annotations(key_indentation, key_line); switch(m_pending_tags.num_entries) { case 1u: _c4dbgpf("annotations_after_start_mapblck: 1 tag: {}", prs_(m_pending_tags.annotations[0].str)); m_evt_handler->set_key_tag(m_pending_tags.annotations[0].str); _clear_annotations(&m_pending_tags); break; case 2u: _c4dbgpf("annotations_after_start_mapblck: 2 tags: {} -> {}", prs_(m_pending_tags.annotations[0].str), prs_(m_pending_tags.annotations[1].str)); m_evt_handler->set_key_tag(m_pending_tags.annotations[1].str); _clear_annotations(&m_pending_tags); break; } switch(m_pending_anchors.num_entries) { case 1u: _c4dbgpf("annotations_after_start_mapblck: 1 anchors: {} -> {}", m_pending_anchors.annotations[0].str); m_evt_handler->set_key_anchor(m_pending_anchors.annotations[0].str); _clear_annotations(&m_pending_anchors); break; case 2u: _c4dbgpf("annotations_after_start_mapblck: 2 anchors: {} -> {}", m_pending_anchors.annotations[0].str, m_pending_anchors.annotations[1].str); m_evt_handler->set_key_anchor(m_pending_anchors.annotations[1].str); _clear_annotations(&m_pending_anchors); break; } } _set_indentation(key_indentation); } template size_t ParseEngine::_select_indentation_from_annotations(size_t val_indentation, size_t val_line) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_pending_tags.num_entries | m_pending_anchors.num_entries, m_evt_handler->m_curr->pos); // select the left-most annotation on the max line auto const *C4_RESTRICT curr = m_pending_anchors.num_entries ? &m_pending_anchors.annotations[0] : &m_pending_tags.annotations[0]; for(size_t i = 0; i < m_pending_anchors.num_entries; ++i) { auto const& C4_RESTRICT ann = m_pending_anchors.annotations[i]; if(ann.line > curr->line) curr = &ann; else if(ann.indentation < curr->indentation) curr = &ann; } for(size_t j = 0; j < m_pending_tags.num_entries; ++j) { auto const& C4_RESTRICT ann = m_pending_tags.annotations[j]; if(ann.line > curr->line) curr = &ann; else if(ann.indentation < curr->indentation) curr = &ann; } return curr->line < val_line ? val_indentation : curr->indentation; } template void ParseEngine::_handle_keyref(csubstr alias) { if C4_LIKELY(!(m_pending_anchors.num_entries | m_pending_tags.num_entries)) m_evt_handler->set_key_ref(alias); else _c4err("aliases cannot have anchors or tags"); } template void ParseEngine::_handle_valref(csubstr alias) { if C4_LIKELY(!(m_pending_anchors.num_entries | m_pending_tags.num_entries)) m_evt_handler->set_val_ref(alias); else _c4err("aliases cannot have anchors or tags"); } template csubstr ParseEngine::_resolve_tag(csubstr tag) { _c4dbgpf("resolving tag: {} curr_doc={}", prs_(tag), m_evt_handler->m_curr_doc); _c4assert(tag.is_sub(_buf())); TagCache::LookupResult ret = m_evt_handler->tag_cache().find(tag, m_evt_handler->m_curr_doc); if(ret) { _c4dbgpf("resolving tag: found in cache[{}]: {}", ret.pos, prs_(ret.resolved)); return ret.resolved; } _c4dbgpf("resolving tag: not in cache: {} curr_doc={}", prs_(tag), m_evt_handler->m_curr_doc); size_t bufsz = 0; substr buf = m_evt_handler->arena_rem(); TagDirectives const& C4_RESTRICT tds = m_evt_handler->tag_directives(); csubstr ttag = tds.resolve(buf, &bufsz, tag, m_evt_handler->m_curr_doc, m_evt_handler->m_curr->pos, m_evt_handler->m_stack.m_callbacks); _c4dbgpf("resolving tag: bufsz={} ttag.len={} !!ttag.str={}", bufsz, ttag.len, !!ttag.str); _c4assert((bufsz > buf.len) == (!ttag.str)); _c4assert(!!bufsz == (ttag.len == bufsz)); // try again if the arena size was not enough if(!ttag.str) { _c4dbgpf("tag requires arena, but it was small. arena.len={} arena.slack={} tag.required={}", m_evt_handler->arena_rem().len, m_evt_handler->arena().len, ttag.len); _c4assert(ttag.len == bufsz); buf = _alloc_arena(bufsz, &tag); if(buf.str) // the alloc may fail eg with the ints handler { ttag = tds.resolve(buf, &bufsz, tag, m_evt_handler->m_curr_doc, m_evt_handler->m_curr->pos, m_evt_handler->m_stack.m_callbacks); } _c4assert(ttag.len == bufsz); _c4assert(!ttag.str || ttag.is_sub(m_evt_handler->arena())); } else if(bufsz) // if we succeeded writing into the arena, grow it as needed { _c4dbgp("tag required arena. update size"); _c4assert(ttag.len == bufsz); _c4assert(ttag.is_sub(buf)); (void)_alloc_arena(bufsz); } C4_SUPPRESS_WARNING_MSVC_WITH_PUSH(4127) // conditional expression is constant if C4_IF_CONSTEXPR (EventHandler::requires_strings_on_buffers) // NOLINT { _c4dbgpf("handler requires tags in buffers. !!ttag.str={} in_arena={} in_src={}", !!ttag.str, ttag.is_sub(m_evt_handler->arena()), ttag.is_sub(_buf())); // is the resolved tag not in any of those buffers? if(ttag.str && !ttag.is_sub(m_evt_handler->arena()) && !ttag.is_sub(_buf())) { _c4dbgpf("copying resolved tag to arena: slack={} required={}", m_evt_handler->arena_rem().len, ttag.len); buf = _alloc_arena(ttag.len, &tag); if(buf.str) // the alloc may fail eg with the ints handler memcpy(buf.str, ttag.str, ttag.len); ttag.str = buf.str; // keep the current len! _c4assert(!ttag.str || ttag.is_sub(m_evt_handler->arena())); } } C4_SUPPRESS_WARNING_MSVC_POP _c4dbgpf("resolved tag: {} --> [{}]~~~{}~~~", prs_(tag), ttag.len, maybe_null_str_(ttag)); _c4assert(ttag.len > 0); // cache the hard-earned result! m_evt_handler->tag_cache().add(tag, ttag, m_evt_handler->m_curr_doc, ret.pos); return ttag; } template bool ParseEngine::_validate_directive_yaml(csubstr *C4_RESTRICT directive, csubstr *C4_RESTRICT version) const { _c4assert(directive->begins_with("%YAML")); size_t version_start = directive->first_not_of(" \t", 5); if(version_start != npos) { csubstr digits = "0123456789"; size_t major_end = directive->first_not_of(digits, version_start); if(major_end != npos && directive->str[major_end] == '.') // single dot { size_t minor_end = directive->first_not_of(digits, major_end + 1); if(minor_end == npos) minor_end = directive->len; _set_first_strict(*directive, minor_end); *version = directive->range(version_start, minor_end); _c4dbgpf("%YAML: version={} full={}", *version, prs_(*directive, true)); return true; } } return false; } template bool ParseEngine::_validate_directive_tag(csubstr *C4_RESTRICT directive, csubstr *C4_RESTRICT handle, csubstr *C4_RESTRICT prefix) const { _c4assert(directive->begins_with("%TAG")); csubstr whitespace = " \t"; size_t handle_start = directive->first_not_of(whitespace, 4); if(handle_start != npos && directive->str[handle_start] == '!') { size_t handle_end = directive->first_of(whitespace, handle_start); if(handle_end != npos) { size_t prefix_start = directive->first_not_of(whitespace, handle_end); if(prefix_start != npos) { size_t prefix_end = directive->first_of(whitespace, prefix_start); if(prefix_end == npos) prefix_end = directive->len; _set_first_strict(*directive, prefix_end); *handle = directive->range(handle_start, handle_end); *prefix = directive->range(prefix_start, prefix_end); _c4dbgpf("%TAG: handle={} prefix={} full={}", *handle, *prefix, prs_(*directive, true)); if(is_valid_tag_handle(*handle)) return true; } } } return false; } template void ParseEngine::_handle_directive(csubstr directive) { _c4dbgpf("handle_directive: rem={}", prs_(directive, true)); _c4assert(m_evt_handler->m_curr->line_contents.rem.begins_with('%')); _c4assert(directive.str == m_evt_handler->m_curr->line_contents.rem.str); const char *err = nullptr; csubstr rem; size_t pos; auto isdirective = [](csubstr str, csubstr dir) { if(str.begins_with(dir)) { csubstr rest = str.sub(dir.len); return (!rest.len || rest.str[0] == ' ' || rest.str[0] == '\t'); } return false; }; if(isdirective(directive, "%TAG")) { csubstr handle; csubstr prefix; if C4_UNLIKELY(!_validate_directive_tag(&directive, &handle, &prefix)) { err = "invalid %TAG directive"; goto directive_error; // NOLINT } m_evt_handler->add_directive_tag(handle, prefix); } else if(isdirective(directive, "%YAML")) { csubstr version; if C4_UNLIKELY(!_validate_directive_yaml(&directive, &version)) { err = "invalid %YAML directive"; goto directive_error; // NOLINT } if C4_UNLIKELY(m_has_directives_yaml) { err = "multiple %YAML directives"; goto directive_error; // NOLINT } m_has_directives_yaml = true; m_evt_handler->add_directive_yaml(version); } m_has_directives = true; rem = m_evt_handler->m_curr->line_contents.rem; pos = rem.first_not_of(" \t", directive.len); pos = pos != npos ? pos : rem.len; _line_progressed(pos); rem = rem.sub(pos); _c4dbgpf("handle_directive: rest={}", prs_(rem)); if C4_UNLIKELY(rem.len && !rem.begins_with('#')) { err = "invalid tokens after directive"; goto directive_error; // NOLINT } directive_error: if C4_UNLIKELY(err != nullptr) _c4err(err); } template bool ParseEngine::_handle_bom() { const csubstr rem = m_evt_handler->m_curr->line_contents.rem; if(rem.len) { const csubstr rest = rem.sub(1); // https://yaml.org/spec/1.2.2/#52-character-encodings #define _rymlisascii(c) ((c) > '\0' && (c) <= '\x7f') // is the character ASCII? if(rem.begins_with(csubstr{"\x00\x00\xfe\xff", 4}) // no bom: || (rem.begins_with(csubstr{"\x00\x00\x00", 3}) && rem.len >= 4u && _rymlisascii(rem.str[3]))) { _c4err("UTF32BE not supported"); } else if(rem.begins_with(csubstr{"\xff\xfe\x00\x00", 4}) // no bom: || (rest.begins_with(csubstr{"\x00\x00\x00", 3}) && rem.len >= 4u && _rymlisascii(rem.str[0]))) { _c4err("UTF32LE not supported"); } else if(rem.begins_with("\xfe\xff") || (rem.begins_with('\x00') && rem.len >= 2u && _rymlisascii(rem.str[1]))) { _c4err("UTF16BE not supported"); } else if(rem.begins_with("\xff\xfe") || (rest.begins_with('\x00') && rem.len >= 2u && _rymlisascii(rem.str[0]))) { _c4err("UTF16LE not supported"); } else if(rem.begins_with("\xef\xbb\xbf")) { _c4dbgp("byte order mark: UTF8"); _handle_bom(UTF8); _line_progressed(3); m_bom_len = 3; return true; } #undef _rymlisascii } return false; } template void ParseEngine::_handle_bom(Encoding_e enc) { if(m_encoding == NOBOM) { if(enc == UTF8 || /*beginning of file*/(m_evt_handler->m_curr->line_contents.rem.str == _buf().str)) m_encoding = enc; else _c4err("non-UTF8 byte order mark can appear only at the beginning of the file"); // LCOV_EXCL_LINE } else if(enc != m_encoding) { _c4err("byte order mark can only be set once"); // LCOV_EXCL_LINE } } //----------------------------------------------------------------------------- template void ParseEngine::_handle_seq_json() { seqjson_start: _c4dbgpf("handle2_seq_json: node_id={} level={} indentation={}", m_evt_handler->m_curr->node_id, m_evt_handler->m_curr->level, m_evt_handler->m_curr->indref); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKEY), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_all(RSEQ), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_all(RFLOW), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RVAL|RNXT), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_all(RVAL) != has_all(RNXT), m_evt_handler->m_curr->pos); _handle_flow_skip_whitespace(); csubstr rem = m_evt_handler->m_curr->line_contents.rem; if(!rem.len) goto seqjson_again; if(has_any(RVAL)) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RNXT), m_evt_handler->m_curr->pos); const char first = rem.str[0]; _c4dbgpf("mapjson[RVAL]: '{}'", first); switch(first) { case '"': { _c4dbgp("seqjson[RVAL]: scanning double-quoted scalar"); ScannedScalar sc = _scan_scalar_dquot(); csubstr maybe_filtered = _maybe_filter_val_scalar_dquot(sc); m_evt_handler->set_val_scalar_dquoted(maybe_filtered); addrem_flags(RNXT, RVAL); break; } case '[': { _c4dbgp("seqjson[RVAL]: start child seqjson"); addrem_flags(RNXT, RVAL); m_evt_handler->begin_seq_val_flow(); addrem_flags(RVAL, RNXT); _line_progressed(1); break; } case '{': { _c4dbgp("seqjson[RVAL]: start child mapjson"); addrem_flags(RNXT, RVAL); m_evt_handler->begin_map_val_flow(); addrem_flags(RMAP|RKEY, RSEQ|RVAL|RNXT); _line_progressed(1); goto seqjson_finish; } case ']': // this happens on a trailing comma like ", ]" { _c4dbgp("seqjson[RVAL]: end!"); rem_flags(RSEQ); _end_seq_flow(); _line_progressed(1); if(!has_all(RSEQ|RFLOW)) goto seqjson_finish; break; } default: { ScannedScalar sc; if(_scan_scalar_seq_json(&sc)) { _c4dbgp("seqjson[RVAL]: it's a plain scalar."); csubstr maybe_filtered = _maybe_filter_val_scalar_plain(sc, m_evt_handler->m_curr->indref); m_evt_handler->set_val_scalar_plain(maybe_filtered); addrem_flags(RNXT, RVAL); } else { _c4err("parse error"); } } } } else // RNXT { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RNXT), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RVAL), m_evt_handler->m_curr->pos); const char first = rem.str[0]; _c4dbgpf("mapjson[RNXT]: '{}'", first); switch(first) { case ',': { _c4dbgp("seqjson[RNXT]: expect next val"); addrem_flags(RVAL, RNXT); m_evt_handler->add_sibling(); _line_progressed(1); break; } case ']': { _c4dbgp("seqjson[RNXT]: end!"); _end_seq_flow(); _line_progressed(1); goto seqjson_finish; } default: _c4err("parse error"); } } seqjson_again: _c4dbgt("seqjson: go again", 0); if(_finished_line()) { if C4_LIKELY(!_finished_file()) { _line_ended(); _scan_line(); _c4dbgnextline(); } else { _c4err("missing terminating ]"); } } goto seqjson_start; seqjson_finish: _c4dbgp("seqjson: finish"); } //----------------------------------------------------------------------------- template void ParseEngine::_handle_map_json() { mapjson_start: _c4dbgpf("handle2_map_json: node_id={} level={} indentation={}", m_evt_handler->m_curr->node_id, m_evt_handler->m_curr->level, m_evt_handler->m_curr->indref); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_all(RMAP), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_all(RFLOW), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(QMRK), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RKEY|RKCL|RVAL|RNXT), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, 1 == (has_any(RKEY) + has_any(RKCL) + has_any(RVAL) + has_any(RNXT)), m_evt_handler->m_curr->pos); _handle_flow_skip_whitespace(); csubstr rem = m_evt_handler->m_curr->line_contents.rem; if(!rem.len) goto mapjson_again; if(has_any(RKEY)) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKCL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RVAL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RNXT), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(QMRK), m_evt_handler->m_curr->pos); const char first = rem.str[0]; _c4dbgpf("mapjson[RKEY]: '{}'", first); switch(first) { case '"': { _c4dbgp("mapjson[RKEY]: scanning double-quoted scalar"); ScannedScalar sc = _scan_scalar_dquot(); csubstr maybe_filtered = _maybe_filter_key_scalar_dquot(sc); m_evt_handler->set_key_scalar_dquoted(maybe_filtered); addrem_flags(RKCL, RKEY); break; } case '}': // this happens on a trailing comma like ", }" { _c4dbgp("mapjson[RKEY]: end!"); _end_map_flow(); _line_progressed(1); goto mapjson_finish; } default: _c4err("parse error"); } } else if(has_any(RVAL)) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKEY), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKCL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RNXT), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(QMRK), m_evt_handler->m_curr->pos); const char first = rem.str[0]; _c4dbgpf("mapjson[RVAL]: '{}'", first); switch(first) { case '"': { _c4dbgp("mapjson[RVAL]: scanning double-quoted scalar"); ScannedScalar sc = _scan_scalar_dquot(); csubstr maybe_filtered = _maybe_filter_val_scalar_dquot(sc); m_evt_handler->set_val_scalar_dquoted(maybe_filtered); addrem_flags(RNXT, RVAL); break; } case '[': { _c4dbgp("mapjson[RVAL]: start val seqjson"); addrem_flags(RNXT, RVAL); m_evt_handler->begin_seq_val_flow(); _set_indentation(m_evt_handler->m_parent->indref); addrem_flags(RSEQ|RVAL, RMAP|RNXT); _line_progressed(1); goto mapjson_finish; } case '{': { _c4dbgp("mapjson[RVAL]: start val mapjson"); addrem_flags(RNXT, RVAL); m_evt_handler->begin_map_val_flow(); _set_indentation(m_evt_handler->m_parent->indref); addrem_flags(RKEY, RNXT); _line_progressed(1); // keep going in this function break; } default: { ScannedScalar sc; if(_scan_scalar_map_json(&sc)) { _c4dbgp("mapjson[RVAL]: plain scalar."); csubstr maybe_filtered = _maybe_filter_val_scalar_plain(sc, m_evt_handler->m_curr->indref); m_evt_handler->set_val_scalar_plain(maybe_filtered); addrem_flags(RNXT, RVAL); } else { _c4err("parse error"); } break; } } } else if(has_any(RKCL)) // read the key colon { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKEY), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RVAL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RNXT), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(QMRK), m_evt_handler->m_curr->pos); const char first = rem.str[0]; _c4dbgpf("mapjson[RKCL]: '{}'", first); if(first == ':') { _c4dbgp("mapjson[RKCL]: found the colon"); addrem_flags(RVAL, RKCL); _line_progressed(1); } else { _c4err("parse error"); } } else if(has_any(RNXT)) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKEY), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKCL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RVAL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(QMRK), m_evt_handler->m_curr->pos); _c4dbgpf("mapjson[RNXT]: '{}'", rem.str[0]); if(rem.begins_with(',')) { _c4dbgp("mapjson[RNXT]: expect next keyval"); m_evt_handler->add_sibling(); addrem_flags(RKEY, RNXT); _line_progressed(1); } else if(rem.begins_with('}')) { _c4dbgp("mapjson[RNXT]: end!"); _end_map_flow(); _line_progressed(1); goto mapjson_finish; } else { _c4err("parse error"); // LCOV_EXCL_LINE } } mapjson_again: _c4dbgt("mapjson: go again", 0); if(_finished_line()) { if C4_LIKELY(!_finished_file()) { _line_ended(); _scan_line(); _c4dbgnextline(); } else { _c4err("missing terminating }"); } } goto mapjson_start; mapjson_finish: _c4dbgp("mapjson: finish"); } //----------------------------------------------------------------------------- template void ParseEngine::_handle_seq_imap() { seqimap_start: _c4dbgpf("handle2_seq_imap: node_id={} level={} indref={}", m_evt_handler->m_curr->node_id, m_evt_handler->m_curr->level, m_evt_handler->m_curr->indref); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_all(RSEQIMAP), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKEY), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RVAL|RNXT|QMRK|RKCL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, 1 == has_all(RVAL) + has_all(RNXT) + has_all(QMRK) + has_all(RKCL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_stack.size() >= 3, m_evt_handler->m_curr->pos); _handle_flow_skip_whitespace(); csubstr rem = m_evt_handler->m_curr->line_contents.rem; if(!rem.len) goto seqimap_again; if(has_any(RVAL)) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RVAL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RNXT), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(QMRK), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKCL), m_evt_handler->m_curr->pos); const char first = rem.str[0]; _c4dbgpf("seqimap[RVAL]: '{}'", _c4prc(first)); ScannedScalar sc; if(first == '\'') { _c4dbgp("seqimap[RVAL]: scanning single-quoted scalar"); sc = _scan_scalar_squot(); csubstr maybe_filtered = _maybe_filter_val_scalar_squot(sc); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_squoted(maybe_filtered); _end_map_flow(); goto seqimap_finish; } else if(first == '"') { _c4dbgp("seqimap[RVAL]: scanning double-quoted scalar"); sc = _scan_scalar_dquot(); csubstr maybe_filtered = _maybe_filter_val_scalar_dquot(sc); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_dquoted(maybe_filtered); _end_map_flow(); goto seqimap_finish; } // block scalars (ie | and >) cannot appear in flow containers else if(_scan_scalar_plain_map_flow(&sc)) { _c4dbgp("seqimap[RVAL]: it's a scalar."); csubstr maybe_filtered = _maybe_filter_val_scalar_plain(sc, m_evt_handler->m_curr->indref); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_plain(maybe_filtered); _end_map_flow(); goto seqimap_finish; } else if(first == '[') { _c4dbgp("seqimap[RVAL]: start child seqflow"); addrem_flags(RNXT, RVAL); _handle_annotations_before_blck_val_scalar(); m_evt_handler->begin_seq_val_flow(); addrem_flags(RVAL, RNXT|RSEQIMAP); _set_indentation(m_evt_handler->m_parent->indref); _line_progressed(1); goto seqimap_finish; } else if(first == '{') { _c4dbgp("seqimap[RVAL]: start child mapflow"); addrem_flags(RNXT, RVAL); _handle_annotations_before_blck_val_scalar(); m_evt_handler->begin_map_val_flow(); addrem_flags(RMAP|RKEY, RSEQ|RVAL|RSEQIMAP|RNXT); _set_indentation(m_evt_handler->m_parent->indref); _line_progressed(1); goto seqimap_finish; } else if(first == ',' || first == ']') { _c4dbgp("seqimap[RVAL]: finish without val."); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_plain_empty(); _end_map_flow(); goto seqimap_finish; } else if(first == '*') { csubstr ref = _scan_ref_seq(); _c4dbgpf("seqimap[RVAL]: ref! {}", prs_(ref)); _handle_valref(ref); addrem_flags(RNXT, RVAL); } else if(first == '&') { csubstr anchor = _scan_anchor(); _c4dbgpf("seqimap[RVAL]: anchor! {}", prs_(anchor)); _add_annotation(&m_pending_anchors, anchor); } else if(first == '!') { csubstr tag = _scan_tag(); _c4dbgpf("seqimap[RVAL]: tag! {}", prs_(tag)); _add_annotation(&m_pending_tags, tag); } else { _c4err("parse error"); // LCOV_EXCL_LINE } } else if(has_any(RNXT)) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RNXT), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RVAL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(QMRK), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKCL), m_evt_handler->m_curr->pos); const char first = rem.str[0]; _c4dbgpf("seqimap[RNXT]: '{}'", _c4prc(first)); if(first == ',' || first == ']') { // we may get here because a map or a seq started and we // return later _c4dbgp("seqimap: done"); _end_map_flow(); goto seqimap_finish; } else { _c4err("parse error"); // LCOV_EXCL_LINE } } else if(has_any(QMRK)) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(QMRK), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RVAL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RNXT), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKCL), m_evt_handler->m_curr->pos); const char first = rem.str[0]; _c4dbgpf("seqimap[QMRK]: '{}'", _c4prc(first)); ScannedScalar sc; if(first == '\'') { _c4dbgp("seqimap[QMRK]: scanning single-quoted scalar"); sc = _scan_scalar_squot(); csubstr maybe_filtered = _maybe_filter_key_scalar_squot(sc); m_evt_handler->set_key_scalar_squoted(maybe_filtered); addrem_flags(RKCL, QMRK); goto seqimap_again; } else if(first == '"') { _c4dbgp("seqimap[QMRK]: scanning double-quoted scalar"); sc = _scan_scalar_dquot(); csubstr maybe_filtered = _maybe_filter_key_scalar_dquot(sc); m_evt_handler->set_key_scalar_dquoted(maybe_filtered); addrem_flags(RKCL, QMRK); goto seqimap_again; } // block scalars (ie | and >) cannot appear in flow containers else if(_scan_scalar_plain_map_flow(&sc)) { _c4dbgp("seqimap[QMRK]: it's a scalar."); csubstr maybe_filtered = _maybe_filter_key_scalar_plain(sc, m_evt_handler->m_curr->indref); m_evt_handler->set_key_scalar_plain(maybe_filtered); addrem_flags(RKCL, QMRK); goto seqimap_again; } else if(first == '[') { _c4dbgp("seqimap[QMRK]: start child seqflow"); addrem_flags(RKCL, QMRK); m_evt_handler->begin_seq_key_flow(); addrem_flags(RSEQ|RVAL, RKCL|RSEQIMAP); _set_indentation(m_evt_handler->m_parent->indref); _line_progressed(1); goto seqimap_finish; } else if(first == '{') { _c4dbgp("seqimap[QMRK]: start child mapflow"); addrem_flags(RKCL, QMRK); m_evt_handler->begin_map_key_flow(); addrem_flags(RMAP|RKEY, RSEQ|RKCL|RSEQIMAP); _set_indentation(m_evt_handler->m_parent->indref); _line_progressed(1); goto seqimap_finish; } else if(first == ',' || first == ']') { _c4dbgp("seqimap[QMRK]: finish without key."); m_evt_handler->set_key_scalar_plain_empty(); m_evt_handler->set_val_scalar_plain_empty(); _end_map_flow(); goto seqimap_finish; } else if(first == '&') { csubstr anchor = _scan_anchor(); _c4dbgp("seqimap[QMRK]: anchor!"); m_evt_handler->set_key_anchor(anchor); } else if(first == '*') { csubstr ref = _scan_ref_seq(); _c4dbgp("seqimap[QMRK]: ref!"); _handle_keyref(ref); addrem_flags(RKCL, QMRK); } else { _c4err("parse error"); // LCOV_EXCL_LINE } } else if(has_any(RKCL)) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RVAL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RNXT), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(QMRK), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RKCL), m_evt_handler->m_curr->pos); const char first = rem.str[0]; _c4dbgpf("seqimap[RKCL]: '{}'", _c4prc(first)); if(first == ':') { _c4dbgp("seqimap[RKCL]: found ':'"); addrem_flags(RVAL, RKCL); _line_progressed(1); goto seqimap_again; } else if(first == ',' || first == ']') { _c4dbgp("seqimap[RKCL]: found ','. finish without val"); m_evt_handler->set_val_scalar_plain_empty(); _end_map_flow(); goto seqimap_finish; } else { _c4err("parse error"); // LCOV_EXCL_LINE } } seqimap_again: _c4dbgt("seqimap: go again", 0); if(_finished_line()) { if C4_LIKELY(!_finished_file()) { _line_ended(); _scan_line(); _c4dbgnextline(); } else { _c4err("parse error"); } } goto seqimap_start; seqimap_finish: _c4dbgp("seqimap: finish"); } //----------------------------------------------------------------------------- template void ParseEngine::_handle_seq_flow() { seqflow_start: _c4dbgpf("handle_seq_flow: node_id={} level={} indentation={}", m_evt_handler->m_curr->node_id, m_evt_handler->m_curr->level, m_evt_handler->m_curr->indref); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKEY), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_all(RSEQ), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_all(RFLOW), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RVAL|RNXT), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_all(RVAL) != has_all(RNXT), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_curr->indref != npos, m_evt_handler->m_curr->pos); if(m_evt_handler->m_curr->at_line_beginning()) { _handle_flow_line_beginning(); } _handle_flow_skip_whitespace(); if(!m_evt_handler->m_curr->line_contents.rem.len) goto seqflow_again; if(has_any(RVAL)) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RNXT), m_evt_handler->m_curr->pos); const char first = m_evt_handler->m_curr->line_contents.rem.str[0]; ScannedScalar sc; if(first == '\'') { _c4dbgp("seqflow[RVAL]: scanning single-quoted scalar"); sc = _scan_scalar_squot(); csubstr maybe_filtered = _maybe_filter_val_scalar_squot(sc); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_squoted(maybe_filtered); addrem_flags(RNXT, RVAL); _mark_seqflow_val_end(); } else if(first == '"') { _c4dbgp("seqflow[RVAL]: scanning double-quoted scalar"); sc = _scan_scalar_dquot(); csubstr maybe_filtered = _maybe_filter_val_scalar_dquot(sc); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_dquoted(maybe_filtered); addrem_flags(RNXT, RVAL); _mark_seqflow_val_end(); } // block scalars (ie | and >) cannot appear in flow containers else if(_scan_scalar_plain_seq_flow(&sc)) { _c4dbgp("seqflow[RVAL]: it's a scalar."); csubstr maybe_filtered = _maybe_filter_val_scalar_plain(sc, m_evt_handler->m_curr->indref); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_plain(maybe_filtered); addrem_flags(RNXT, RVAL); _mark_seqflow_val_end(); } else if(first == '[') { _c4dbgp("seqflow[RVAL]: start child seqflow"); addrem_flags(RNXT, RVAL); _handle_annotations_before_blck_val_scalar(); m_evt_handler->begin_seq_val_flow(); _set_indentation(m_evt_handler->m_parent->indref); addrem_flags(RVAL, RNXT); _line_progressed(1); } else if(first == '{') { _c4dbgp("seqflow[RVAL]: start child mapflow"); addrem_flags(RNXT, RVAL); _handle_annotations_before_blck_val_scalar(); m_evt_handler->begin_map_val_flow(); _set_indentation(m_evt_handler->m_parent->indref); addrem_flags(RMAP|RKEY, RSEQ|RVAL|RNXT); _line_progressed(1); goto seqflow_finish; } else if(first == ']') // this happens on cases such as [] or [.., ] { _c4dbgp("seqflow[RVAL]: end!"); if(m_pending_anchors.num_entries | m_pending_tags.num_entries) { _c4dbgp("seqflow[RVAL]: add pending annotations"); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_plain_empty(); } _line_progressed(1); _end_seq_flow(); goto seqflow_finish; } else if(first == '*') { csubstr ref = _scan_ref_seq(); _c4dbgpf("seqflow[RVAL]: ref! {}", prs_(ref)); _handle_valref(ref); addrem_flags(RNXT, RVAL); } else if(first == '&') { csubstr anchor = _scan_anchor(); _c4dbgpf("seqflow[RVAL]: anchor! {}", prs_(anchor)); _add_annotation(&m_pending_anchors, anchor); } else if(first == '!') { csubstr tag = _scan_tag(); _c4dbgpf("seqflow[RVAL]: tag! {}", prs_(tag)); _add_annotation(&m_pending_tags, tag); } else if(first == ':') { _c4dbgpf("seqflow[RVAL]: actually seqimap at node[{}], with empty key", m_evt_handler->m_curr->node_id); addrem_flags(RNXT, RVAL); m_evt_handler->begin_map_val_flow(); _set_indentation(m_evt_handler->m_parent->indref); _handle_annotations_before_blck_key_scalar(); m_evt_handler->set_key_scalar_plain_empty(); addrem_flags(RSEQIMAP|RVAL, RSEQ|RNXT); _line_progressed(1); goto seqflow_finish; } else if(first == '?') { _c4dbgp("seqflow[RVAL]: start child mapflow, explicit key"); addrem_flags(RNXT, RVAL); m_evt_handler->begin_map_val_flow(); _set_indentation(m_evt_handler->m_parent->indref); addrem_flags(RSEQIMAP|QMRK, RSEQ|RNXT); _line_progressed(1); _maybe_skip_whitespace_tokens(); goto seqflow_finish; } else if(first == ',') { if(m_pending_anchors.num_entries || m_pending_tags.num_entries) { _c4dbgp("seqflow[RVAL]: add pending annotations"); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_plain_empty(); addrem_flags(RNXT, RVAL); _mark_seqflow_val_end(); } else { _c4err("parse error"); } } else { _c4err("parse error"); } } else // RNXT { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RNXT), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RVAL), m_evt_handler->m_curr->pos); const char first = m_evt_handler->m_curr->line_contents.rem.str[0]; if(first == ',') { _c4dbgp("seqflow[RNXT]: expect next val"); addrem_flags(RVAL, RNXT); m_evt_handler->add_sibling(); _line_progressed(1); if(m_evt_handler->m_curr->line_contents.rem.begins_with('#')) { _c4err("parse error: invalid comment after comma"); } _mark_seqflow_val_end(); } else if(first == ']') { _c4dbgp("seqflow[RNXT]: end!"); _line_progressed(1); _end_seq_flow(); goto seqflow_finish; } else if(first == ':') { _c4dbgpf("seqflow[RNXT]: line@valend={} line@now={}", m_prev_val_end, m_evt_handler->m_curr->pos.line); if(m_prev_val_end != NONE && m_evt_handler->m_curr->pos.line == m_prev_val_end) { _c4dbgpf("seqflow[RNXT]: actually seqimap at node[{}]", m_evt_handler->m_curr->node_id); m_evt_handler->actually_val_is_first_key_of_new_map_flow(); _set_indentation(m_evt_handler->m_parent->indref); _line_progressed(1); addrem_flags(RSEQIMAP|RVAL, RNXT); goto seqflow_finish; } else { _c4err("parse error"); } } else { _c4err("parse error"); } } seqflow_again: _c4dbgt("seqflow: go again", 0); if(_finished_line()) { if C4_LIKELY(!_finished_file()) { _line_ended(); _scan_line(); _c4dbgnextline(); } else { _c4err("missing terminating ]"); } } goto seqflow_start; seqflow_finish: _c4dbgp("seqflow: finish"); } //----------------------------------------------------------------------------- template void ParseEngine::_handle_map_flow() { mapflow_start: _c4dbgpf("handle_map_flow: node_id={} level={} indentation={}", m_evt_handler->m_curr->node_id, m_evt_handler->m_curr->level, m_evt_handler->m_curr->indref); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_all(RMAP), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_all(RFLOW), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RKEY|RKCL|RVAL|RNXT|QMRK), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, 1 == (has_any(RKEY) + has_any(RKCL) + has_any(RVAL) + has_any(RNXT) + has_any(QMRK)), m_evt_handler->m_curr->pos); if(m_evt_handler->m_curr->at_line_beginning()) { _handle_flow_line_beginning(); } _handle_flow_skip_whitespace(); if(!m_evt_handler->m_curr->line_contents.rem.len) goto mapflow_again; if(has_any(RKEY)) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKCL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RVAL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RNXT), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(QMRK), m_evt_handler->m_curr->pos); const char first = m_evt_handler->m_curr->line_contents.rem.str[0]; _c4dbgpf("mapflow[RKEY]: '{}'", first); ScannedScalar sc; if(first == '\'') { _c4dbgp("mapflow[RKEY]: scanning single-quoted scalar"); sc = _scan_scalar_squot(); csubstr maybe_filtered = _maybe_filter_key_scalar_squot(sc); _handle_annotations_before_blck_key_scalar(); m_evt_handler->set_key_scalar_squoted(maybe_filtered); addrem_flags(RKCL, RKEY|QMRK); } else if(first == '"') { _c4dbgp("mapflow[RKEY]: scanning double-quoted scalar"); sc = _scan_scalar_dquot(); csubstr maybe_filtered = _maybe_filter_key_scalar_dquot(sc); _handle_annotations_before_blck_key_scalar(); m_evt_handler->set_key_scalar_dquoted(maybe_filtered); addrem_flags(RKCL, RKEY|QMRK); } // block scalars (ie | and >) cannot appear in flow containers else if(_scan_scalar_plain_map_flow(&sc)) { _c4dbgp("mapflow[RKEY]: plain scalar"); csubstr maybe_filtered = _maybe_filter_key_scalar_plain(sc, m_evt_handler->m_curr->indref); _handle_annotations_before_blck_key_scalar(); m_evt_handler->set_key_scalar_plain(maybe_filtered); addrem_flags(RKCL, RKEY|QMRK); } else if(first == '?') { _c4dbgp("mapflow[RKEY]: explicit key"); _handle_annotations_before_blck_key_scalar(); addrem_flags(QMRK, RKEY); _line_progressed(1); _maybe_skip_whitespace_tokens(); } else if(first == ':') { _c4dbgp("mapflow[RKEY]: setting empty key"); _handle_annotations_before_blck_key_scalar(); m_evt_handler->set_key_scalar_plain_empty(); addrem_flags(RVAL, RKEY|QMRK); _line_progressed(1); _maybe_skip_whitespace_tokens(); } else if(first == ',') { _c4dbgp("mapflow[RKEY]: comma!"); if(!_handle_annotations_before_unexpected_flow_token_rkey()) _c4err("unexpected comma"); addrem_flags(RNXT, RKEY|QMRK); // keep going in this function } else if(first == '}') // this happens on a trailing comma like ", }" { _c4dbgp("mapflow[RKEY]: end!"); (void)_handle_annotations_before_unexpected_flow_token_rkey(); _line_progressed(1); _end_map_flow(); goto mapflow_finish; } else if(first == '&') { csubstr anchor = _scan_anchor(); _c4dbgpf("mapflow[RKEY]: key anchor! {}", prs_(anchor)); _add_annotation(&m_pending_anchors, anchor); } else if(first == '!') { csubstr tag = _scan_tag(); _c4dbgpf("mapflow[RKEY]: tag! {}", prs_(tag)); _add_annotation(&m_pending_tags, tag); } else if(first == '*') { csubstr ref = _scan_ref_map(); _c4dbgpf("mapflow[RKEY]: key ref! {}", prs_(ref)); _handle_keyref(ref); addrem_flags(RKCL, RKEY); } else if(first == '[') { // RYML's tree cannot store container keys, but that's // handled inside the tree event handler. Other handler // types may be able to handle it. _c4dbgp("mapflow[RKEY]: start child seqflow (!)"); _handle_annotations_before_blck_key_scalar(); addrem_flags(RKCL, RKEY); m_evt_handler->begin_seq_key_flow(); addrem_flags(RSEQ|RVAL, RMAP|RKCL); _set_indentation(m_evt_handler->m_parent->indref); _line_progressed(1); goto mapflow_finish; } else if(first == '{') { // RYML's tree cannot store container keys, but that's // handled inside the tree event handler. Other handler // types may be able to handle it. _c4dbgp("mapflow[RKEY]: start child mapflow (!)"); _handle_annotations_before_blck_key_scalar(); addrem_flags(RKCL, RKEY); m_evt_handler->begin_map_key_flow(); addrem_flags(RKEY, RVAL|RKCL); _set_indentation(m_evt_handler->m_parent->indref); _line_progressed(1); // keep going in this function } else { _c4err("parse error"); // LCOV_EXCL_LINE } } else if(has_any(RKCL)) // read the key colon { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKEY), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RVAL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RNXT), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(QMRK), m_evt_handler->m_curr->pos); const char first = m_evt_handler->m_curr->line_contents.rem.str[0]; _c4dbgpf("mapflow[RKCL]: '{}'", first); if(first == ':') { _c4dbgp("mapflow[RKCL]: found the colon"); addrem_flags(RVAL, RKCL); _line_progressed(1); } else if(first == '}') { _c4dbgp("mapflow[RKCL]: end with missing val!"); addrem_flags(RVAL, RKCL); m_evt_handler->set_val_scalar_plain_empty(); _line_progressed(1); _end_map_flow(); goto mapflow_finish; } else if(first == ',') { _c4dbgp("mapflow[RKCL]: got comma. val is missing"); m_evt_handler->set_val_scalar_plain_empty(); m_evt_handler->add_sibling(); addrem_flags(RKEY, RKCL); _line_progressed(1); if(m_evt_handler->m_curr->line_contents.rem.begins_with('#')) { _c4err("parse error: invalid comment after comma"); } } else { _c4err("parse error"); } } else if(has_any(RVAL)) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKEY), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKCL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RNXT), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(QMRK), m_evt_handler->m_curr->pos); const char first = m_evt_handler->m_curr->line_contents.rem.str[0]; _c4dbgpf("mapflow[RVAL]: '{}'", first); ScannedScalar sc; if(first == '\'') { _c4dbgp("mapflow[RVAL]: scanning single-quoted scalar"); sc = _scan_scalar_squot(); csubstr maybe_filtered = _maybe_filter_val_scalar_squot(sc); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_squoted(maybe_filtered); addrem_flags(RNXT, RVAL); } else if(first == '"') { _c4dbgp("mapflow[RVAL]: scanning double-quoted scalar"); sc = _scan_scalar_dquot(); csubstr maybe_filtered = _maybe_filter_val_scalar_dquot(sc); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_dquoted(maybe_filtered); addrem_flags(RNXT, RVAL); } // block scalars (ie | and >) cannot appear in flow containers else if(_scan_scalar_plain_map_flow(&sc)) { _c4dbgp("mapflow[RVAL]: plain scalar."); csubstr maybe_filtered = _maybe_filter_val_scalar_plain(sc, m_evt_handler->m_curr->indref); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_plain(maybe_filtered); addrem_flags(RNXT, RVAL); } else if(first == '[') { _c4dbgp("mapflow[RVAL]: start val seqflow"); addrem_flags(RNXT, RVAL); _handle_annotations_before_blck_val_scalar(); m_evt_handler->begin_seq_val_flow(); _set_indentation(m_evt_handler->m_parent->indref); addrem_flags(RSEQ|RVAL, RMAP|RNXT); _line_progressed(1); goto mapflow_finish; } else if(first == '{') { _c4dbgp("mapflow[RVAL]: start val mapflow"); addrem_flags(RNXT, RVAL); _handle_annotations_before_blck_val_scalar(); m_evt_handler->begin_map_val_flow(); _set_indentation(m_evt_handler->m_parent->indref); addrem_flags(RKEY, RNXT); _line_progressed(1); // keep going in this function } else if(first == '}') { _c4dbgp("mapflow[RVAL]: end!"); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_plain_empty(); _line_progressed(1); _end_map_flow(); goto mapflow_finish; } else if(first == ',') { _c4dbgp("mapflow[RVAL]: empty val!"); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_plain_empty(); addrem_flags(RNXT, RVAL); // keep going in this function } else if(first == '*') { csubstr ref = _scan_ref_map(); _c4dbgpf("mapflow[RVAL]: key ref! {}", prs_(ref)); _handle_valref(ref); addrem_flags(RNXT, RVAL); } else if(first == '&') { csubstr anchor = _scan_anchor(); _c4dbgpf("mapflow[RVAL]: key anchor! {}", prs_(anchor)); _add_annotation(&m_pending_anchors, anchor); } else if(first == '!') { csubstr tag = _scan_tag(); _c4dbgpf("mapflow[RVAL]: tag! {}", prs_(tag)); _add_annotation(&m_pending_tags, tag); } else { _c4err("parse error"); } } else if(has_any(RNXT)) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKEY), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKCL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RVAL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(QMRK), m_evt_handler->m_curr->pos); _c4dbgpf("mapflow[RNXT]: '{}'", m_evt_handler->m_curr->line_contents.rem.str[0]); if(m_evt_handler->m_curr->line_contents.rem.begins_with(',')) { _c4dbgp("mapflow[RNXT]: expect next keyval"); m_evt_handler->add_sibling(); addrem_flags(RKEY, RNXT); _line_progressed(1); if(m_evt_handler->m_curr->line_contents.rem.begins_with('#')) { _c4err("parse error: invalid comment after comma"); } } else if(m_evt_handler->m_curr->line_contents.rem.begins_with('}')) { _c4dbgp("mapflow[RNXT]: end!"); _line_progressed(1); _end_map_flow(); goto mapflow_finish; } else { _c4err("parse error"); } } else if(has_any(QMRK)) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKEY), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKCL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RVAL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RNXT), m_evt_handler->m_curr->pos); const char first = m_evt_handler->m_curr->line_contents.rem.str[0]; _c4dbgpf("mapflow[QMRK]: '{}'", first); ScannedScalar sc; if(first == '\'') { _c4dbgp("mapflow[QMRK]: scanning single-quoted scalar"); sc = _scan_scalar_squot(); csubstr maybe_filtered = _maybe_filter_key_scalar_squot(sc); _handle_annotations_before_blck_key_scalar(); m_evt_handler->set_key_scalar_squoted(maybe_filtered); addrem_flags(RKCL, QMRK); } else if(first == '"') { _c4dbgp("mapflow[QMRK]: scanning double-quoted scalar"); sc = _scan_scalar_dquot(); csubstr maybe_filtered = _maybe_filter_key_scalar_dquot(sc); _handle_annotations_before_blck_key_scalar(); m_evt_handler->set_key_scalar_dquoted(maybe_filtered); addrem_flags(RKCL, QMRK); } // block scalars (ie | and >) cannot appear in flow containers else if(_scan_scalar_plain_map_flow(&sc)) { _c4dbgp("mapflow[QMRK]: plain scalar"); csubstr maybe_filtered = _maybe_filter_key_scalar_plain(sc, m_evt_handler->m_curr->indref); _handle_annotations_before_blck_key_scalar(); m_evt_handler->set_key_scalar_plain(maybe_filtered); addrem_flags(RKCL, QMRK); } else if(first == ':') { _c4dbgp("mapflow[QMRK]: setting empty key"); _handle_annotations_before_blck_key_scalar(); m_evt_handler->set_key_scalar_plain_empty(); addrem_flags(RVAL, QMRK); _line_progressed(1); _maybe_skip_whitespace_tokens(); } else if(first == '}') // this happens on a trailing comma like ", }" { _c4dbgp("mapflow[QMRK]: end!"); _handle_annotations_before_blck_key_scalar(); m_evt_handler->set_key_scalar_plain_empty(); m_evt_handler->set_val_scalar_plain_empty(); _end_map_flow(); _line_progressed(1); goto mapflow_finish; } else if(first == ',') { _c4dbgp("mapflow[QMRK]: empty key+val!"); _handle_annotations_before_blck_key_scalar(); m_evt_handler->set_key_scalar_plain_empty(); m_evt_handler->set_val_scalar_plain_empty(); addrem_flags(RNXT, QMRK); } else if(first == '&') { csubstr anchor = _scan_anchor(); _c4dbgpf("mapflow[QMRK]: key anchor! {}", prs_(anchor)); _add_annotation(&m_pending_anchors, anchor); } else if(first == '*') { csubstr ref = _scan_ref_map(); _c4dbgpf("mapflow[QMRK]: key ref! {}", prs_(ref)); _handle_keyref(ref); addrem_flags(RKCL, QMRK); } else if(first == '[') { // RYML's tree cannot store container keys, but that's // handled inside the tree sink. Other sink types may be // able to handle it. _c4dbgp("mapflow[QMRK]: start child seqflow (!)"); addrem_flags(RKCL, QMRK); _handle_annotations_before_blck_key_scalar(); m_evt_handler->begin_seq_key_flow(); addrem_flags(RSEQ|RVAL, RMAP|RKCL); _set_indentation(m_evt_handler->m_parent->indref); _line_progressed(1); goto mapflow_finish; } else if(first == '{') { // RYML's tree cannot store container keys, but that's // handled inside the tree sink. Other sink types may be // able to handle it. _c4dbgp("mapflow[QMRK]: start child mapflow (!)"); addrem_flags(RKCL, QMRK); _handle_annotations_before_blck_key_scalar(); m_evt_handler->begin_map_key_flow(); _set_indentation(m_evt_handler->m_parent->indref); addrem_flags(RKEY, RKCL); _line_progressed(1); // keep going in this function } else if(first == '!') { csubstr tag = _scan_tag(); _c4dbgpf("mapflow[QMRK]: tag! {}", prs_(tag)); _add_annotation(&m_pending_tags, tag); } else { _c4err("parse error"); // LCOV_EXCL_LINE } } mapflow_again: _c4dbgt("mapflow: go again", 0); if(_finished_line()) { if C4_LIKELY(!_finished_file()) { _line_ended(); _scan_line(); _c4dbgnextline(); } else { _c4err("missing terminating }"); } } goto mapflow_start; mapflow_finish: _c4dbgp("mapflow: finish"); } //----------------------------------------------------------------------------- template void ParseEngine::_handle_seq_block() { seqblck_start: _c4dbgpf("handle_seq_block: seq_id={} node_id={} level={} indent={}", m_evt_handler->m_parent->node_id, m_evt_handler->m_curr->node_id, m_evt_handler->m_curr->level, m_evt_handler->m_curr->indref); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_all(RSEQ), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_all(RBLCK), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RVAL|RNXT), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, 1 == (has_any(RVAL) + has_any(RNXT)), m_evt_handler->m_curr->pos); _maybe_skip_comment_strict(); if(!m_evt_handler->m_curr->line_contents.rem.len) goto seqblck_again; if(has_any(RVAL)) { _c4dbgpf("seqblck[RVAL]: col={}", m_evt_handler->m_curr->pos.col); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RNXT), m_evt_handler->m_curr->pos); if(m_evt_handler->m_curr->at_line_beginning()) { _c4dbgpf("seqblck[RVAL]: indref={} indentation={}", m_evt_handler->m_curr->indref+1, m_evt_handler->m_curr->line_contents.indentation); if(m_evt_handler->m_curr->indentation_ge_extra()) { _c4dbgpf("seqblck[RVAL]: skip {} from indentation", m_evt_handler->m_curr->line_contents.indentation); _line_progressed(m_evt_handler->m_curr->line_contents.indentation); if(!m_evt_handler->m_curr->line_contents.rem.len) goto seqblck_again; } else if(m_evt_handler->m_curr->indentation_lt_extra()) { _c4dbgp("seqblck[RVAL]: smaller indentation than RVAL!"); if(m_evt_handler->m_curr->indentation_eq()) { _c4dbgp("seqblck[RVAL]: smaller indentation than RVAL!"); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_plain_empty(); addrem_flags(RNXT, RVAL); goto seqblck_again; } else { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_curr->indentation_lt(), m_evt_handler->m_curr->pos); _c4dbgp("seqblck[RVAL]: smaller indentation!"); _handle_indentation_pop_from_block_seq(); goto seqblck_finish; } } else if(m_evt_handler->m_curr->line_contents.indentation == npos) { _c4dbgp("seqblck[RVAL]: empty line!"); _line_progressed(m_evt_handler->m_curr->line_contents.rem.len); goto seqblck_again; } } RYML_ASSERT_PARSE_CB_(callbacks(), m_evt_handler->m_curr->line_contents.rem.len, m_evt_handler->m_curr->pos); const size_t startmark = _handle_block_skip_leading_whitespace(); _c4dbgpf("seqblck[RVAL]: startmark={}", startmark); if(startmark == npos) { _c4dbgp("seqblck[RVAL]: whitespace only"); goto seqblck_again; } const size_t tabmark = _handle_block_get_whitespace_mark(); const char first = m_evt_handler->m_curr->line_contents.rem.str[0]; _c4dbgpf("seqblck[RVAL]: first='{}' currcol={}", first, m_evt_handler->m_curr->pos.col - 1); const size_t startline = m_evt_handler->m_curr->pos.line; _c4assert(m_evt_handler->m_curr->line_contents.current_col() >= m_bom_len); const size_t startindent = m_evt_handler->m_curr->line_contents.current_col() - m_bom_len; ScannedScalar sc; if(first == '\'') { _c4dbgp("seqblck[RVAL]: single-quoted scalar"); sc = _scan_scalar_squot(); if(!_maybe_scan_following_colon()) { _c4dbgp("seqblck[RVAL]: set as val"); _handle_annotations_before_blck_val_scalar(); csubstr maybe_filtered = _maybe_filter_val_scalar_squot(sc); // VAL! m_evt_handler->set_val_scalar_squoted(maybe_filtered); addrem_flags(RNXT, RVAL); } else { _c4dbgp("seqblck[RVAL]: start mapblck, set scalar as key"); _handle_block_check_leading_tabs(startmark); addrem_flags(RNXT, RVAL); _handle_annotations_before_start_mapblck(startline); _handle_colon(); m_evt_handler->begin_map_val_block(); _handle_annotations_and_indentation_after_start_mapblck(startindent, startline); csubstr maybe_filtered = _maybe_filter_key_scalar_squot(sc); // KEY! m_evt_handler->set_key_scalar_squoted(maybe_filtered); addrem_flags(RMAP|RVAL, RSEQ|RNXT); _maybe_skip_whitespace_tokens(); goto seqblck_finish; } } else if(first == '"') { _c4dbgp("seqblck[RVAL]: double-quoted scalar"); sc = _scan_scalar_dquot(); if(!_maybe_scan_following_colon()) { _c4dbgp("seqblck[RVAL]: set as val"); _handle_annotations_before_blck_val_scalar(); csubstr maybe_filtered = _maybe_filter_val_scalar_dquot(sc); // VAL! m_evt_handler->set_val_scalar_dquoted(maybe_filtered); addrem_flags(RNXT, RVAL); } else { _c4dbgp("seqblck[RVAL]: start mapblck, set scalar as key"); addrem_flags(RNXT, RVAL); _handle_block_check_leading_tabs(startmark); _handle_annotations_before_start_mapblck(startline); _handle_colon(); m_evt_handler->begin_map_val_block(); _handle_annotations_and_indentation_after_start_mapblck(startindent, startline); csubstr maybe_filtered = _maybe_filter_key_scalar_dquot(sc); // KEY! m_evt_handler->set_key_scalar_dquoted(maybe_filtered); addrem_flags(RMAP|RVAL, RSEQ|RNXT); _maybe_skip_whitespace_tokens(); goto seqblck_finish; } } // block scalars can only appear as keys when in QMRK scope // (ie, after ? tokens), so no need to scan following colon in // here. else if(first == '|') { _c4dbgp("seqblck[RVAL]: block-literal scalar"); ScannedBlock sb; _scan_block(&sb, m_evt_handler->m_curr->indref + 1); _handle_annotations_before_blck_val_scalar(); csubstr maybe_filtered = _maybe_filter_val_scalar_literal(sb); m_evt_handler->set_val_scalar_literal(maybe_filtered); addrem_flags(RNXT, RVAL); } else if(first == '>') { _c4dbgp("seqblck[RVAL]: block-folded scalar"); ScannedBlock sb; _scan_block(&sb, m_evt_handler->m_curr->indref + 1); _handle_annotations_before_blck_val_scalar(); csubstr maybe_filtered = _maybe_filter_val_scalar_folded(sb); m_evt_handler->set_val_scalar_folded(maybe_filtered); addrem_flags(RNXT, RVAL); } else if(_scan_scalar_plain_seq_blck(&sc)) { _c4dbgp("seqblck[RVAL]: plain scalar."); if(!_maybe_scan_following_colon()) { _c4dbgp("seqblck[RVAL]: set as val"); _handle_annotations_before_blck_val_scalar(); csubstr maybe_filtered = _maybe_filter_val_scalar_plain(sc, m_evt_handler->m_curr->indref); // VAL! m_evt_handler->set_val_scalar_plain(maybe_filtered); addrem_flags(RNXT, RVAL); } else { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_curr->indref != npos, m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, startindent > m_evt_handler->m_curr->indref, m_evt_handler->m_curr->pos); _c4dbgp("seqblck[RVAL]: start mapblck, set scalar as key"); _handle_block_check_leading_tabs(startmark, tabmark); addrem_flags(RNXT, RVAL); _handle_annotations_before_start_mapblck(startline); _handle_colon(); m_evt_handler->begin_map_val_block(); _handle_annotations_and_indentation_after_start_mapblck(startindent, startline); csubstr maybe_filtered = _maybe_filter_key_scalar_plain(sc, m_evt_handler->m_curr->indref); // KEY! m_evt_handler->set_key_scalar_plain(maybe_filtered); addrem_flags(RMAP|RVAL, RSEQ|RNXT); _maybe_skip_whitespace_tokens(); goto seqblck_finish; } } else if(first == '[') { _c4dbgp("seqblck[RVAL]: start child seqflow"); addrem_flags(RNXT, RVAL); _handle_annotations_before_blck_val_scalar(); m_evt_handler->begin_seq_val_flow(); addrem_flags(RFLOW|RVAL, RBLCK|RNXT); _line_progressed(1); _set_indentation(m_evt_handler->m_parent->indref + 1u); goto seqblck_finish; } else if(first == '{') { _c4dbgp("seqblck[RVAL]: start child mapflow"); addrem_flags(RNXT, RVAL); _handle_annotations_before_blck_val_scalar(); m_evt_handler->begin_map_val_flow(); addrem_flags(RMAP|RKEY|RFLOW, RBLCK|RSEQ|RVAL|RNXT); _line_progressed(1); _set_indentation(m_evt_handler->m_parent->indref + 1u); goto seqblck_finish; } else if(first == '-') { _c4dbgp("seqblck[RVAL]: dash"); _handle_block_check_leading_tabs(startmark); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_curr->indref != npos, m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, startindent > m_evt_handler->m_curr->indref, m_evt_handler->m_curr->pos); _c4dbgp("seqblck[RVAL]: start child seqblck"); RYML_ASSERT_PARSE_CB_(this->callbacks(), startindent > m_evt_handler->m_curr->indref, m_evt_handler->m_curr->pos); addrem_flags(RNXT, RVAL); _handle_annotations_before_blck_val_scalar(); m_evt_handler->begin_seq_val_block(); addrem_flags(RVAL, RNXT); _set_indentation(startindent); // keep going on inside this function _line_progressed(1); } else if(first == ':') { _c4dbgp("seqblck[RVAL]: start child mapblck with empty key"); addrem_flags(RNXT, RVAL); _handle_annotations_before_start_mapblck(startline); _handle_colon(); m_evt_handler->begin_map_val_block(); _handle_annotations_and_indentation_after_start_mapblck(startindent, startline); m_evt_handler->set_key_scalar_plain_empty(); addrem_flags(RMAP|RVAL, RSEQ|RNXT); _line_progressed(1); _maybe_skip_whitespace_tokens(); goto seqblck_finish; } else if(first == '&') { const csubstr anchor = _scan_anchor(); _c4dbgpf("seqblck[RVAL]: anchor! {}", prs_(anchor)); // we need to buffer the anchors, as there may be two // consecutive anchors in here _add_annotation(&m_pending_anchors, anchor, startindent, startline); } else if(first == '*') { csubstr ref = _scan_ref_seq(); _c4dbgpf("seqblck[RVAL]: ref! {}", prs_(ref)); if(!_maybe_scan_following_colon()) { _c4dbgp("seqblck[RVAL]: set ref as val!"); _handle_valref(ref); addrem_flags(RNXT, RVAL); } else { _c4dbgp("seqblck[RVAL]: ref is key of map"); addrem_flags(RNXT, RVAL); _handle_annotations_before_start_mapblck(startline); m_evt_handler->begin_map_val_block(); _handle_annotations_and_indentation_after_start_mapblck(startindent, startline); _handle_keyref(ref); addrem_flags(RMAP|RVAL, RSEQ|RNXT); _set_indentation(startindent); _maybe_skip_whitespace_tokens(); goto seqblck_finish; } } else if(first == '!') { csubstr tag = _scan_tag(); _c4dbgpf("seqblck[RVAL]: val tag! {}", prs_(tag)); // we need to buffer the tags, as there may be two // consecutive tags in here _add_annotation(&m_pending_tags, tag, startindent, startline); } else if(first == '?') { _c4dbgp("seqblck[RVAL]: start child mapblck, explicit key"); addrem_flags(RNXT, RVAL); m_evt_handler->begin_map_val_block(); addrem_flags(RMAP|QMRK, RSEQ|RNXT); _set_indentation(startindent); _line_progressed(1); _maybe_skipchars(' '); if(_is_blck_seq_token_maybe(m_evt_handler->m_curr->line_contents.rem)) { _c4dbgp("seqblck[RVAL]: seqblck starts after ?"); addrem_flags(RKCL, QMRK); m_evt_handler->begin_seq_key_block(); addrem_flags(RSEQ|RVAL, RMAP|RKCL); _save_indentation(); _line_progressed(1); _maybe_skipchars(' '); } goto seqblck_finish; } else { _c4err("parse error"); } } else // RNXT { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RNXT), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RVAL), m_evt_handler->m_curr->pos); // // handle indentation // _c4dbgpf("seqblck[RNXT]: indref={} indentation={}", m_evt_handler->m_curr->indref, m_evt_handler->m_curr->line_contents.indentation); if C4_LIKELY(m_evt_handler->m_curr->at_line_beginning()) { _c4dbgp("seqblck[RNXT]: at line begin"); if(m_evt_handler->m_curr->indentation_ge()) { _c4dbgpf("seqblck[RNXT]: skip {} from indref", m_evt_handler->m_curr->indref); _line_progressed(m_evt_handler->m_curr->indref); if(!m_evt_handler->m_curr->line_contents.rem.len) goto seqblck_again; } else if(m_evt_handler->m_curr->indentation_lt()) { _c4dbgp("seqblck[RNXT]: smaller indentation!"); _handle_indentation_pop_from_block_seq(); if(has_all(RSEQ|RBLCK)) { _c4dbgp("seqblck[RNXT]: still seqblck!"); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RNXT), m_evt_handler->m_curr->pos); _line_progressed(m_evt_handler->m_curr->line_contents.indentation); if(!m_evt_handler->m_curr->line_contents.rem.len) goto seqblck_again; // LCOV_EXCL_LINE } else { _c4dbgp("seqblck[RNXT]: no longer seqblck!"); goto seqblck_finish; } } else if(m_evt_handler->m_curr->line_contents.indentation == npos) { _c4dbgpf("seqblck[RNXT]: blank line, len={}", m_evt_handler->m_curr->line_contents.rem); _line_progressed(m_evt_handler->m_curr->line_contents.rem.len); if(!m_evt_handler->m_curr->line_contents.rem.len) goto seqblck_again; // LCOV_EXCL_LINE } } else { _c4dbgp("seqblck[RNXT]: NOT at line begin"); if(!m_evt_handler->m_curr->line_contents.rem.begins_with_any(" \t")) { _c4err("parse error"); } else { _skipchars(" \t"); if(!m_evt_handler->m_curr->line_contents.rem.len) { _c4dbgp("seqblck[RNXT]: again"); goto seqblck_again; // LCOV_EXCL_LINE } } } // // now handle the tokens // _c4assert(m_evt_handler->m_curr->line_contents.rem.len > 0); const char first = m_evt_handler->m_curr->line_contents.rem.str[0]; _c4dbgpf("seqblck[RNXT]: '{}' node_id={}", _c4prc(first), m_evt_handler->m_curr->node_id); if(first == '-') { if(m_evt_handler->m_curr->indref > 0 || m_evt_handler->m_curr->line_contents.indentation > 0 || !_is_doc_begin_token(m_evt_handler->m_curr->line_contents.rem)) { if C4_LIKELY(_is_blck_seq_token_maybe(m_evt_handler->m_curr->line_contents.rem)) { _c4dbgp("seqblck[RNXT]: expect next val"); addrem_flags(RVAL, RNXT); m_evt_handler->add_sibling(); _line_progressed(1); } else { _c4err("parse error"); } } else { _c4dbgp("seqblck[RNXT]: start doc"); _start_doc_suddenly(); _line_progressed(3); _maybe_skip_whitespace_tokens(); goto seqblck_finish; } } else if(first == ':') { // This happens for example in `- [a: b]: c` (after // terminating the seq, ie, after `]`). All other cases // (ie colon after scalars) are caught elsewhere (ie, in // RVAL state). if C4_LIKELY(m_evt_handler->m_parent && (m_evt_handler->m_parent->flags & RMAP)) { _c4dbgp("seqblck[RNXT]: actually this seq was '?' key of parent map"); m_evt_handler->end_seq_block(); goto seqblck_finish; } else { _c4err("parse error"); } } else if(first == '.') { _c4dbgp("seqblck[RNXT]: maybe doc?"); if(_is_doc_end_token(m_evt_handler->m_curr->line_contents.rem)) { _c4dbgp("seqblck[RNXT]: end doc"); _end_doc_suddenly(); _line_progressed(3); _maybe_skip_whitespace_tokens(); _check_doc_end_tokens(); goto seqblck_finish; } else { _c4err("parse error"); } } else { // may be an indentless sequence nested in a map... #ifdef RYML_DBG _print_state_stack(); #endif if(m_evt_handler->m_parent && has_all(RMAP|RBLCK, m_evt_handler->m_parent) && m_evt_handler->m_curr->indref == m_evt_handler->m_parent->indref) { _c4dbgpf("seqblck[RNXT]: end indentless seq, go to parent={}. node={}", m_evt_handler->m_parent->node_id, m_evt_handler->m_curr->node_id); RYML_ASSERT_PARSE_CB_(this->callbacks(), m_evt_handler->m_curr != m_evt_handler->m_parent, m_evt_handler->m_curr->pos); _handle_indentation_pop(m_evt_handler->m_parent); RYML_ASSERT_PARSE_CB_(this->callbacks(), has_all(RMAP|RBLCK), m_evt_handler->m_curr->pos); m_evt_handler->add_sibling(); addrem_flags(RKEY, RNXT); goto seqblck_finish; } else if(first == '\t') { size_t pos = m_evt_handler->m_curr->line_contents.rem.first_not_of('\t'); if(pos == npos) { _line_progressed(m_evt_handler->m_curr->line_contents.rem.len); goto seqblck_again; } } _c4err("parse error"); } } seqblck_again: _c4dbgt("seqblck: go again", 0); if(_finished_line()) { m_bom_len = 0; _line_ended(); _scan_line(); if(_finished_file()) { _c4dbgp("seqblck: finish!"); _end_seq_blck(); goto seqblck_finish; } _c4dbgnextline(); } goto seqblck_start; seqblck_finish: _c4dbgp("seqblck: finish"); } //----------------------------------------------------------------------------- template void ParseEngine::_handle_map_block() { mapblck_start: _c4dbgpf("handle_map_block: map_id={} node_id={} level={} indref={}", m_evt_handler->m_parent->node_id, m_evt_handler->m_curr->node_id, m_evt_handler->m_curr->level, m_evt_handler->m_curr->indref); // states: RKEY -> RVAL -> RNXT // states: QMRK -> RKCL -> RVAL -> RNXT RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_all(RMAP), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_all(RBLCK), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RKEY|RKCL|RVAL|RNXT|QMRK), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, 1 == (has_any(RKEY) + has_any(RKCL) + has_any(RVAL) + has_any(RNXT) + has_any(QMRK)), m_evt_handler->m_curr->pos); _maybe_skip_comment(); if(!m_evt_handler->m_curr->line_contents.rem.len) goto mapblck_again; if(has_any(RKEY)) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKCL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(QMRK), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RVAL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RNXT), m_evt_handler->m_curr->pos); // // handle indentation // if(m_evt_handler->m_curr->at_line_beginning()) { if(m_evt_handler->m_curr->indentation_eq()) { _c4dbgpf("mapblck[RKEY]: skip {} from indref", m_evt_handler->m_curr->indref); _line_progressed(m_evt_handler->m_curr->indref); if(!m_evt_handler->m_curr->line_contents.rem.len) goto mapblck_again; } else if(m_evt_handler->m_curr->indentation_lt()) { _c4dbgp("mapblck[RKEY]: smaller indentation!"); _handle_indentation_pop_from_block_map(); _line_progressed(m_evt_handler->m_curr->line_contents.indentation); if(has_all(RMAP|RBLCK)) { _c4dbgp("mapblck[RKEY]: still mapblck!"); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_any(RKEY), m_evt_handler->m_curr->pos); if(!m_evt_handler->m_curr->line_contents.rem.len) goto mapblck_again; } else { _c4dbgp("mapblck[RKEY]: no longer mapblck!"); goto mapblck_finish; } } else { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_curr->indentation_gt(), m_evt_handler->m_curr->pos); _c4err("invalid indentation"); } } // // now handle the tokens // const char first = m_evt_handler->m_curr->line_contents.rem.str[0]; const size_t startline = m_evt_handler->m_curr->pos.line; const size_t startindent = m_evt_handler->m_curr->line_contents.current_col(); _c4dbgpf("mapblck[RKEY]: '{}'", _c4prc(first)); ScannedScalar sc; if(first == '\'') { _c4dbgp("mapblck[RKEY]: scanning single-quoted scalar"); sc = _scan_scalar_squot(); csubstr maybe_filtered = _maybe_filter_val_scalar_squot(sc); _handle_annotations_before_blck_key_scalar(); m_evt_handler->set_key_scalar_squoted(maybe_filtered); addrem_flags(RVAL, RKEY); if(!_maybe_scan_following_colon()) _c4err("could not find ':' colon after key"); _handle_colon(); _maybe_skip_whitespace_tokens(); } else if(first == '"') { _c4dbgp("mapblck[RKEY]: scanning double-quoted scalar"); sc = _scan_scalar_dquot(); csubstr maybe_filtered = _maybe_filter_val_scalar_dquot(sc); _handle_annotations_before_blck_key_scalar(); m_evt_handler->set_key_scalar_dquoted(maybe_filtered); addrem_flags(RVAL, RKEY); if(!_maybe_scan_following_colon()) _c4err("could not find ':' colon after key"); _handle_colon(); _maybe_skip_whitespace_tokens(); } // block scalars (| and >) can not be used as keys unless they // appear in an explicit QMRK scope (ie, after the ? token), else if C4_UNLIKELY(first == '|') { _c4err("block map: literal keys must be enclosed in '?'"); } else if C4_UNLIKELY(first == '>') { _c4err("block map: folded keys must be enclosed in '?'"); } else if(_scan_scalar_plain_map_blck(&sc)) { _c4dbgp("mapblck[RKEY]: plain scalar"); csubstr maybe_filtered = _maybe_filter_val_scalar_plain(sc, m_evt_handler->m_curr->indref); _handle_annotations_before_blck_key_scalar(); m_evt_handler->set_key_scalar_plain(maybe_filtered); addrem_flags(RVAL, RKEY); if(!_maybe_scan_following_colon()) _c4err("could not find ':' colon after key"); _handle_colon(); _maybe_skip_whitespace_tokens(); } else if(first == '?') { _c4dbgp("mapblck[RKEY]: key token!"); addrem_flags(QMRK, RKEY); _line_progressed(1); _maybe_skipchars(' '); if(_is_blck_seq_token_maybe(m_evt_handler->m_curr->line_contents.rem)) { _c4dbgp("mapblck[RKEY]: seqblck starts after ?"); addrem_flags(RKCL, QMRK); m_evt_handler->begin_seq_key_block(); addrem_flags(RSEQ|RVAL, RMAP|RKCL); _save_indentation(); _line_progressed(1); _maybe_skipchars(' '); goto mapblck_finish; } goto mapblck_again; } else if(first == ':') { _c4dbgp("mapblck[RKEY]: setting empty key"); _handle_annotations_before_blck_key_scalar(); m_evt_handler->set_key_scalar_plain_empty(); addrem_flags(RVAL, RKEY); _line_progressed(1); _handle_colon(); _maybe_skip_whitespace_tokens(); } else if(first == '*') { csubstr ref = _scan_ref_map(); _c4dbgpf("mapblck[RKEY]: key ref! {}", prs_(ref)); _handle_keyref(ref); addrem_flags(RVAL, RKEY); if(!_maybe_scan_following_colon()) _c4err("could not find ':' colon after key"); _handle_colon(); _maybe_skip_whitespace_tokens(); } else if(first == '&') { csubstr anchor = _scan_anchor(); _c4dbgpf("mapblck[RKEY]: key anchor! {}", prs_(anchor)); _add_annotation(&m_pending_anchors, anchor, startindent, startline); } else if(first == '!') { csubstr tag = _scan_tag(); _c4dbgpf("mapblck[RKEY]: key tag! {}", prs_(tag)); _add_annotation(&m_pending_tags, tag, startindent, startline); } else if(first == '[') { // RYML's tree cannot store container keys, but that's // handled inside the tree handler. Other handlers may be // able to handle it. _c4dbgp("mapblck[RKEY]: start child seqflow (!)"); _handle_annotations_before_blck_key_scalar(); m_evt_handler->begin_seq_key_flow(); addrem_flags(RSEQ|RFLOW|RVAL, RKEY|RMAP|RBLCK); _line_progressed(1); _set_indentation(startindent); goto mapblck_finish; } else if(first == '{') { // RYML's tree cannot store container keys, but that's // handled inside the tree handler. Other handlers may be // able to handle it. _c4dbgp("mapblck[RKEY]: start child mapflow (!)"); _handle_annotations_before_blck_key_scalar(); m_evt_handler->begin_map_key_flow(); addrem_flags(RFLOW|RKEY, RBLCK); _line_progressed(1); _set_indentation(startindent); goto mapblck_finish; } else if(first == '-') { _c4dbgp("mapblck[RKEY]: maybe doc?"); if(m_evt_handler->m_curr->line_contents.indentation == 0 && _is_doc_begin_token(m_evt_handler->m_curr->line_contents.rem)) { _c4dbgp("mapblck[RKEY]: end+start doc"); _start_doc_suddenly(); _line_progressed(3); _maybe_skip_whitespace_tokens(); goto mapblck_finish; } else { _c4err("parse error"); } } else if(first == '.') { _c4dbgp("mapblck[RKEY]: maybe end doc?"); if(m_evt_handler->m_curr->line_contents.indentation == 0 && _is_doc_end_token(m_evt_handler->m_curr->line_contents.rem)) { _c4dbgp("mapblck[RKEY]: end doc"); _end_doc_suddenly(); _line_progressed(3); _maybe_skip_whitespace_tokens(); _check_doc_end_tokens(); goto mapblck_finish; } else { _c4err("parse error"); // LCOV_EXCL_LINE } } else { _c4err("parse error"); } } else if(has_any(RVAL)) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKEY), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKCL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RNXT), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(QMRK), m_evt_handler->m_curr->pos); // // handle indentation // if(m_evt_handler->m_curr->at_line_beginning()) { _c4dbgpf("mapblck[RVAL]: indref={} indentation={}", m_evt_handler->m_curr->indref+1, m_evt_handler->m_curr->line_contents.indentation); m_evt_handler->m_curr->more_indented = false; RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_curr->indref != npos, m_evt_handler->m_curr->pos); if(m_evt_handler->m_curr->indentation_eq_extra()) { _c4dbgp("mapblck[RVAL]: skip indentation!"); _line_progressed(m_evt_handler->m_curr->indref + 1); if(!m_evt_handler->m_curr->line_contents.rem.len) goto mapblck_again; } else if(m_evt_handler->m_curr->indentation_gt_extra()) { _c4dbgp("mapblck[RVAL]: more indented!"); m_evt_handler->m_curr->more_indented = true; _line_progressed(m_evt_handler->m_curr->line_contents.indentation); if(!m_evt_handler->m_curr->line_contents.rem.len) goto mapblck_again; // LCOV_EXCL_LINE } else if(m_evt_handler->m_curr->indentation_lt_extra()) { if(m_evt_handler->m_curr->indentation_eq()) { _c4dbgp("mapblck[RVAL]: smaller indentation than RVAL!"); // watchout for indentless seqs if(!_is_blck_seq_token_maybe(m_evt_handler->m_curr->line_contents.rem.sub(m_evt_handler->m_curr->line_contents.indentation))) { _c4dbgp("mapblck[RVAL]: smaller indentation than RVAL!"); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_plain_empty(); addrem_flags(RNXT, RVAL); goto mapblck_again; } } else { _c4dbgp("mapblck[RVAL]: smaller indentation than RKEY!"); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_curr->indentation_lt(), m_evt_handler->m_curr->pos); _handle_indentation_pop_from_block_map(); if(has_all(RMAP|RBLCK)) { _c4dbgp("mapblck[RVAL]: still mapblck!"); _line_progressed(m_evt_handler->m_curr->line_contents.indentation); if(has_any(RNXT)) { _c4dbgp("mapblck[RVAL]: speculatively expect next keyval"); m_evt_handler->add_sibling(); addrem_flags(RKEY, RNXT); } goto mapblck_again; } else { _c4dbgp("mapblck[RVAL]: no longer mapblck!"); goto mapblck_finish; } } } } const size_t startcol = _handle_block_skip_leading_whitespace(); if(startcol == npos) { _c4dbgp("mapblck[RVAL]: whitespace only"); goto mapblck_again; // LCOV_EXCL_LINE } const size_t tabmark = _handle_block_get_whitespace_mark(); // // now handle the tokens // _c4assert(m_evt_handler->m_curr->line_contents.rem.len); const char first = m_evt_handler->m_curr->line_contents.rem.str[0]; const size_t startline = m_evt_handler->m_curr->pos.line; const size_t startindent = m_evt_handler->m_curr->line_contents.current_col(); _c4dbgpf("mapblck[RVAL]: '{}'", _c4prc(first)); ScannedScalar sc; if(first == '\'') { _c4dbgp("mapblck[RVAL]: scanning single-quoted scalar"); sc = _scan_scalar_squot(); if(!_maybe_scan_following_colon()) { _c4dbgp("mapblck[RVAL]: set as val"); _handle_annotations_before_blck_val_scalar(); csubstr maybe_filtered = _maybe_filter_val_scalar_squot(sc); // VAL! m_evt_handler->set_val_scalar_squoted(maybe_filtered); addrem_flags(RNXT, RVAL); } else { _c4assert(m_evt_handler->m_curr->indref != npos); _c4assert(startindent > m_evt_handler->m_curr->indref); _c4dbgp("mapblck[RVAL]: start new block map, set scalar as key"); _handle_block_check_leading_tabs(startcol); _handle_annotations_before_start_mapblck(startline); addrem_flags(RNXT, RVAL); _handle_colon(); m_evt_handler->begin_map_val_block(); _handle_annotations_and_indentation_after_start_mapblck(startindent, startline); csubstr maybe_filtered = _maybe_filter_key_scalar_squot(sc); // KEY! m_evt_handler->set_key_scalar_squoted(maybe_filtered); _maybe_skip_whitespace_tokens(); // keep the child state on RVAL addrem_flags(RVAL, RNXT); } } else if(first == '"') { _c4dbgp("mapblck[RVAL]: scanning double-quoted scalar"); sc = _scan_scalar_dquot(); if(!_maybe_scan_following_colon()) { _c4dbgp("mapblck[RVAL]: set as val"); _handle_annotations_before_blck_val_scalar(); csubstr maybe_filtered = _maybe_filter_val_scalar_dquot(sc); // VAL! m_evt_handler->set_val_scalar_dquoted(maybe_filtered); addrem_flags(RNXT, RVAL); } else { _c4assert(m_evt_handler->m_curr->indref != npos); _c4assert(startindent > m_evt_handler->m_curr->indref); _c4dbgp("mapblck[RVAL]: start new block map, set scalar as key"); _handle_block_check_leading_tabs(startcol); _handle_annotations_before_start_mapblck(startline); addrem_flags(RNXT, RVAL); _handle_colon(); m_evt_handler->begin_map_val_block(); _handle_annotations_and_indentation_after_start_mapblck(startindent, startline); csubstr maybe_filtered = _maybe_filter_key_scalar_dquot(sc); // KEY! m_evt_handler->set_key_scalar_dquoted(maybe_filtered); _maybe_skip_whitespace_tokens(); // keep the child state on RVAL addrem_flags(RVAL, RNXT); } } // block scalars can only appear as keys when in QMRK scope // (ie, after ? tokens), so no need to scan following colon else if(first == '|') { _c4dbgp("mapblck[RVAL]: scanning block-literal scalar"); ScannedBlock sb; _scan_block(&sb, m_evt_handler->m_curr->indref + 1); _handle_annotations_before_blck_val_scalar(); csubstr maybe_filtered = _maybe_filter_val_scalar_literal(sb); m_evt_handler->set_val_scalar_literal(maybe_filtered); addrem_flags(RNXT, RVAL); } else if(first == '>') { _c4dbgp("mapblck[RVAL]: scanning block-folded scalar"); ScannedBlock sb; _scan_block(&sb, m_evt_handler->m_curr->indref + 1); _handle_annotations_before_blck_val_scalar(); csubstr maybe_filtered = _maybe_filter_val_scalar_folded(sb); m_evt_handler->set_val_scalar_folded(maybe_filtered); addrem_flags(RNXT, RVAL); } else if(_scan_scalar_plain_map_blck(&sc)) { _c4dbgp("mapblck[RVAL]: plain scalar."); if(!_maybe_scan_following_colon()) { _c4dbgp("mapblck[RVAL]: set as val"); _handle_annotations_before_blck_val_scalar(); csubstr maybe_filtered = _maybe_filter_val_scalar_plain(sc, m_evt_handler->m_curr->indref); // VAL! m_evt_handler->set_val_scalar_plain(maybe_filtered); addrem_flags(RNXT, RVAL); } else { _c4assert(m_evt_handler->m_curr->indref != npos); _c4assert(startindent > m_evt_handler->m_curr->indref); _c4dbgpf("mapblck[RVAL]: start new block map, set scalar as key {}", m_evt_handler->m_curr->indref); _handle_block_check_leading_tabs(startcol, tabmark); addrem_flags(RNXT, RVAL); _handle_annotations_before_start_mapblck(startline); _handle_colon(); m_evt_handler->begin_map_val_block(); _handle_annotations_and_indentation_after_start_mapblck(startindent, startline); csubstr maybe_filtered = _maybe_filter_key_scalar_plain(sc, m_evt_handler->m_curr->indref); // KEY! m_evt_handler->set_key_scalar_plain(maybe_filtered); _maybe_skip_whitespace_tokens(); // keep the child state on RVAL addrem_flags(RVAL, RNXT); } } else if(first == '-' && _is_blck_seq_token_maybe(m_evt_handler->m_curr->line_contents.rem)) { if C4_UNLIKELY(!m_evt_handler->m_curr->at_first_token()) _c4err("parse error"); _c4dbgp("mapblck[RVAL]: start val seqblck"); _handle_block_check_leading_tabs(startcol); addrem_flags(RNXT, RVAL); _handle_annotations_before_blck_val_scalar(); m_evt_handler->begin_seq_val_block(); addrem_flags(RSEQ|RVAL, RMAP|RNXT); _set_indentation(startindent); _line_progressed(1); _maybe_skip_whitespace_tokens(); goto mapblck_finish; } else if(first == '[') { _c4dbgp("mapblck[RVAL]: start val seqflow"); addrem_flags(RNXT, RVAL); _handle_annotations_before_blck_val_scalar(); m_evt_handler->begin_seq_val_flow(); addrem_flags(RSEQ|RFLOW|RVAL, RMAP|RBLCK|RNXT); _set_indentation(m_evt_handler->m_parent->indref + 1u); _line_progressed(1); goto mapblck_finish; } else if(first == '{') { _c4dbgp("mapblck[RVAL]: start val mapflow"); addrem_flags(RNXT, RVAL); _handle_annotations_before_blck_val_scalar(); m_evt_handler->begin_map_val_flow(); addrem_flags(RKEY|RFLOW, RBLCK|RVAL|RNXT); m_evt_handler->m_curr->scalar_col = m_evt_handler->m_curr->line_contents.indentation; _set_indentation(m_evt_handler->m_parent->indref + 1u); _line_progressed(1); goto mapblck_finish; } else if(first == '*') { csubstr ref = _scan_ref_map(); _c4dbgpf("mapblck[RVAL]: ref! {}", prs_(ref)); if(_maybe_scan_following_colon()) { _c4dbgp("mapblck[RVAL]: start child map, block"); addrem_flags(RNXT, RVAL); _handle_annotations_before_blck_val_scalar(); m_evt_handler->begin_map_val_block(); _handle_keyref(ref); _set_indentation(startindent); // keep going in RVAL addrem_flags(RVAL, RNXT); } else { _c4dbgp("mapblck[RVAL]: was val ref"); _handle_valref(ref); addrem_flags(RNXT, RVAL); } _maybe_skip_whitespace_tokens(); } else if(first == '&') { csubstr anchor = _scan_anchor(); _c4dbgpf("mapblck[RVAL]: anchor! {}", prs_(anchor)); // we need to buffer the anchors, as there may be two // consecutive anchors in here _add_annotation(&m_pending_anchors, anchor, startindent, startline); } else if(first == '!') { csubstr tag = _scan_tag(); _c4dbgpf("mapblck[RVAL]: tag! {}", prs_(tag)); // we need to buffer the tags, as there may be two // consecutive tags in here _add_annotation(&m_pending_tags, tag, startindent, startline); } else if(first == '?') { if C4_UNLIKELY(!m_evt_handler->m_curr->at_first_token()) _c4err("parse error"); _c4dbgp("mapblck[RVAL]: start val mapblck"); addrem_flags(RNXT, RVAL); _handle_annotations_before_blck_val_scalar(); m_evt_handler->begin_map_val_block(); addrem_flags(QMRK, RNXT); _set_indentation(startindent); _line_progressed(1); _maybe_skipchars(' '); if(_is_blck_seq_token_maybe(m_evt_handler->m_curr->line_contents.rem)) { _c4dbgp("mapblck[RVAL]: seqblck starts after ?"); addrem_flags(RKCL, QMRK); m_evt_handler->begin_seq_key_block(); addrem_flags(RSEQ|RVAL, RMAP|RKCL); _save_indentation(); _line_progressed(1); _maybe_skipchars(' '); goto mapblck_finish; } goto mapblck_again; } else if(first == ':') { _c4dbgp("mapblck[RVAL]: start val mapblck"); addrem_flags(RNXT, RVAL); _handle_annotations_before_start_mapblck(startline); _handle_colon(); m_evt_handler->begin_map_val_block(); _handle_annotations_and_indentation_after_start_mapblck(startindent, startline); m_evt_handler->set_key_scalar_plain_empty(); // keep the child state on RVAL addrem_flags(RVAL, RNXT); _line_progressed(1); _maybe_skip_whitespace_tokens(); goto mapblck_again; } else { _c4err("parse error"); // LCOV_EXCL_LINE } } else if(has_any(RNXT)) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKEY), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKCL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RVAL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(QMRK), m_evt_handler->m_curr->pos); // // handle indentation // if(m_evt_handler->m_curr->at_line_beginning()) { _c4dbgpf("mapblck[RNXT]: indref={} indentation={}", m_evt_handler->m_curr->indref, m_evt_handler->m_curr->line_contents.indentation); if(m_evt_handler->m_curr->indentation_eq()) { _c4dbgpf("mapblck[RNXT]: skip {} from indref", m_evt_handler->m_curr->indref); _line_progressed(m_evt_handler->m_curr->indref); _c4dbgp("mapblck[RNXT]: speculatively expect next keyval"); m_evt_handler->add_sibling(); addrem_flags(RKEY, RNXT); goto mapblck_again; } else if(m_evt_handler->m_curr->indentation_lt()) { _c4dbgp("mapblck[RNXT]: smaller indentation!"); _handle_indentation_pop_from_block_map(); if(has_all(RMAP|RBLCK)) { _line_progressed(m_evt_handler->m_curr->line_contents.indentation); if(!has_any(RKCL)) { _c4dbgp("mapblck[RNXT]: speculatively expect next keyval"); m_evt_handler->add_sibling(); addrem_flags(RKEY, RNXT); } goto mapblck_again; } else { goto mapblck_finish; } } } else { _c4dbgp("mapblck[RNXT]: NOT at line begin"); if(!m_evt_handler->m_curr->line_contents.rem.begins_with_any(" \t")) { _c4err("parse error"); } else { _skipchars(" \t"); if(!m_evt_handler->m_curr->line_contents.rem.len) { _c4dbgp("seqblck[RNXT]: again"); goto mapblck_again; // LCOV_EXCL_LINE } } } // // handle tokens // RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_curr->line_contents.rem.len > 0, m_evt_handler->m_curr->pos); const char first = m_evt_handler->m_curr->line_contents.rem.str[0]; _c4dbgpf("mapblck[RNXT]: '{}'", _c4prc(first)); if(first == ' ') { _c4dbgp("mapblck[RNXT]: skip spaces"); _maybe_skip_whitespace_tokens(); } else { _c4err("parse error"); } } else if(has_any(QMRK)) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKEY), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKCL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RVAL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RNXT), m_evt_handler->m_curr->pos); if(_handle_map_block_qmrk()) goto mapblck_again; else goto mapblck_finish; } else if(has_any(RKCL)) // read the key colon (after QMRK) { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RKEY), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RVAL), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RNXT), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(QMRK), m_evt_handler->m_curr->pos); if(_handle_map_block_rkcl()) goto mapblck_again; else goto mapblck_finish; } mapblck_again: _c4dbgt("mapblck: again", 0); if(_finished_line()) { _line_ended(); _scan_line(); if(_finished_file()) { _c4dbgp("mapblck: file finished!"); _end_map_blck(); goto mapblck_finish; } _c4dbgnextline(); } goto mapblck_start; mapblck_finish: _c4dbgp("mapblck: finish"); } //----------------------------------------------------------------------------- // return true if we should remain in map_block template bool ParseEngine::_handle_map_block_qmrk() { // // handle indentation // if(m_evt_handler->m_curr->at_line_beginning()) { _c4dbgpf("mapblck[QMRK]: at line beginning. ind={} indref={}", m_evt_handler->m_curr->line_contents.indentation, m_evt_handler->m_curr->indref); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_curr->line_contents.indentation != npos, m_evt_handler->m_curr->pos); if(m_evt_handler->m_curr->indentation_eq_extra()) { _c4dbgpf("mapblck[QMRK]: skip {} from indref", m_evt_handler->m_curr->indref + 1); _line_progressed(m_evt_handler->m_curr->indref + 1); if(!m_evt_handler->m_curr->line_contents.rem.len) return true; // go again } // indentation can be larger in QMRK state else if(m_evt_handler->m_curr->indentation_gt_extra()) { _c4dbgp("mapblck[QMRK]: larger indentation !"); _line_progressed(m_evt_handler->m_curr->line_contents.indentation); if(!m_evt_handler->m_curr->line_contents.rem.len) return true; // go again } else { _c4dbgp("mapblck[QMRK]: smaller indentation!"); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_curr->indentation_lt_extra(), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_curr->line_contents.rem.len > 0, m_evt_handler->m_curr->pos); if(m_evt_handler->m_curr->indentation_eq() // defend against docs or indentless seqs && m_evt_handler->m_curr->line_contents.rem.str[0] != '-') { _c4dbgp("mapblck[QMRK]: QMRK finished!"); _handle_annotations_before_blck_key_scalar(); m_evt_handler->set_key_scalar_plain_empty(); addrem_flags(RKCL, QMRK); return true; // go again } else if(m_evt_handler->m_curr->indentation_lt()) { _c4dbgp("mapblck[QMRK]: indentation pop!"); _handle_indentation_pop_from_block_map(); _line_progressed(m_evt_handler->m_curr->line_contents.indentation); if(has_all(RMAP|RBLCK)) { _c4dbgp("mapblck[QMRK]: still mapblck!"); return true; // go again } else { _c4dbgp("mapblck[QMRK]: no longer mapblck!"); return false; // finish mapblck } } } } // // now handle the tokens // _c4assert(m_evt_handler->m_curr->line_contents.rem.len); const char first = m_evt_handler->m_curr->line_contents.rem.str[0]; const size_t startline = m_evt_handler->m_curr->pos.line; const size_t startindent = m_evt_handler->m_curr->line_contents.current_col(); _c4dbgpf("mapblck[QMRK]: '{}'", first); ScannedScalar sc; if(first == '\'') { _c4dbgp("mapblck[QMRK]: scanning single-quoted scalar"); sc = _scan_scalar_squot(); csubstr maybe_filtered = _maybe_filter_key_scalar_squot(sc); // KEY! addrem_flags(RKCL, QMRK); if(!_maybe_scan_following_colon()) { _c4dbgp("mapblck[QMRK]: set as key"); _handle_annotations_before_blck_key_scalar(); m_evt_handler->set_key_scalar_squoted(maybe_filtered); } else { _c4dbgp("mapblck[QMRK]: start new block map as key (!), set scalar as key"); _handle_annotations_before_start_mapblck_as_key(); m_evt_handler->begin_map_key_block(); _handle_annotations_and_indentation_after_start_mapblck(startindent, startline); m_evt_handler->set_key_scalar_squoted(maybe_filtered); _maybe_skip_whitespace_tokens(); _set_indentation(startindent); // keep the child state on RVAL addrem_flags(RVAL, RKCL); } } else if(first == '"') { _c4dbgp("mapblck[QMRK]: scanning double-quoted scalar"); sc = _scan_scalar_dquot(); csubstr maybe_filtered = _maybe_filter_key_scalar_dquot(sc); // KEY! addrem_flags(RKCL, QMRK); if(!_maybe_scan_following_colon()) { _c4dbgp("mapblck[QMRK]: set as key"); _handle_annotations_before_blck_key_scalar(); m_evt_handler->set_key_scalar_dquoted(maybe_filtered); } else { _c4dbgp("mapblck[QMRK]: start new block map as key (!), set scalar as key"); _handle_annotations_before_start_mapblck_as_key(); m_evt_handler->begin_map_key_block(); _handle_annotations_and_indentation_after_start_mapblck(startindent, startline); m_evt_handler->set_key_scalar_dquoted(maybe_filtered); _maybe_skip_whitespace_tokens(); _set_indentation(startindent); // keep the child state on RVAL addrem_flags(RVAL, RKCL); } } else if(first == '|') { _c4dbgp("mapblck[QMRK]: scanning block-literal scalar"); ScannedBlock sb; _scan_block(&sb, m_evt_handler->m_curr->indref + 1); csubstr maybe_filtered = _maybe_filter_key_scalar_literal(sb); // KEY! _handle_annotations_before_blck_key_scalar(); m_evt_handler->set_key_scalar_literal(maybe_filtered); addrem_flags(RKCL, QMRK); } else if(first == '>') { _c4dbgp("mapblck[QMRK]: scanning block-literal scalar"); ScannedBlock sb; _scan_block(&sb, m_evt_handler->m_curr->indref + 1); csubstr maybe_filtered = _maybe_filter_key_scalar_folded(sb); // KEY! _handle_annotations_before_blck_key_scalar(); m_evt_handler->set_key_scalar_folded(maybe_filtered); addrem_flags(RKCL, QMRK); } else if(_scan_scalar_plain_map_blck(&sc)) { _c4dbgp("mapblck[QMRK]: plain scalar"); csubstr maybe_filtered = _maybe_filter_key_scalar_plain(sc, m_evt_handler->m_curr->indref); // KEY! addrem_flags(RKCL, QMRK); if(!_maybe_scan_following_colon()) { _c4dbgp("mapblck[QMRK]: set as key"); _handle_annotations_before_blck_key_scalar(); m_evt_handler->set_key_scalar_plain(maybe_filtered); } else { _c4dbgp("mapblck[QMRK]: start new block map as key (!), set scalar as key"); _handle_annotations_before_start_mapblck_as_key(); m_evt_handler->begin_map_key_block(); _handle_annotations_and_indentation_after_start_mapblck(startindent, startline); m_evt_handler->set_key_scalar_plain(maybe_filtered); _maybe_skip_whitespace_tokens(); _set_indentation(startindent); // keep the child state on RVAL addrem_flags(RVAL, RKCL); } } else if(first == ':') { _c4dbgp("mapblck[QMRK]: start new block map as key (!), empty key"); addrem_flags(RKCL, QMRK); _handle_annotations_before_start_mapblck_as_key(); m_evt_handler->begin_map_key_block(); _handle_annotations_and_indentation_after_start_mapblck(startindent, startline); m_evt_handler->set_key_scalar_plain_empty(); _line_progressed(1); _maybe_skip_whitespace_tokens(); _set_indentation(startindent); // keep the child state on RVAL addrem_flags(RVAL, RKCL); } else if(first == '*') { csubstr ref = _scan_ref_map(); _c4dbgpf("mapblck[QMRK]: key ref! {}", prs_(ref)); addrem_flags(RKCL, QMRK); if(!_maybe_scan_following_colon()) { _c4dbgp("mapblck[QMRK]: set ref as key"); _handle_keyref(ref); } else { _c4dbgp("mapblck[QMRK]: start new block map as key (!), set ref as key"); _handle_annotations_before_start_mapblck_as_key(); m_evt_handler->begin_map_key_block(); _handle_annotations_and_indentation_after_start_mapblck(startindent, startline); _handle_keyref(ref); _set_indentation(startindent); // keep the child state on RVAL addrem_flags(RVAL, RKCL|QMRK); } _maybe_skip_whitespace_tokens(); } else if(first == '&') { csubstr anchor = _scan_anchor(); _c4dbgpf("mapblck[QMRK]: key anchor! {}", prs_(anchor)); _add_annotation(&m_pending_anchors, anchor, startindent, startline); } else if(first == '!') { csubstr tag = _scan_tag(); _c4dbgpf("mapblck[QMRK]: key tag! {}", prs_(tag)); _add_annotation(&m_pending_tags, tag, startindent, startline); } else if(first == '-') { _c4dbgp("mapblck[QMRK]: maybe seq or doc?"); if(_is_blck_seq_token_maybe(m_evt_handler->m_curr->line_contents.rem)) { _c4dbgp("mapblck[QMRK]: start child seqblck (!)"); addrem_flags(RKCL, QMRK); _handle_annotations_before_blck_key_scalar(); m_evt_handler->begin_seq_key_block(); addrem_flags(RVAL|RSEQ, RMAP|RKCL); _set_indentation(startindent); _line_progressed(1); } else { _c4dbgp("mapblck[QMRK]: end+start doc"); _c4assert(_is_doc_begin_token(m_evt_handler->m_curr->line_contents.rem)); _start_doc_suddenly(); _line_progressed(3); } _maybe_skip_whitespace_tokens(); return false; // finish mapblck } else if(first == '[') { _c4dbgp("mapblck[QMRK]: start child seqflow (!)"); addrem_flags(RKCL, QMRK); _handle_annotations_before_blck_key_scalar(); m_evt_handler->begin_seq_key_flow(); addrem_flags(RVAL|RSEQ|RFLOW, RMAP|RKCL|RBLCK); _set_indentation(m_evt_handler->m_parent->indref + 1); _line_progressed(1); return false; // finish mapblck } else if(first == '{') { _c4dbgp("mapblck[QMRK]: start child mapflow (!)"); addrem_flags(RKCL, QMRK); _handle_annotations_before_blck_key_scalar(); m_evt_handler->begin_map_key_flow(); addrem_flags(RKEY|RFLOW, RVAL|RKCL|RBLCK); _set_indentation(m_evt_handler->m_parent->indref + 1); _line_progressed(1); return false; // finish mapblck } else if(first == '?') { _c4dbgpf("mapblck[QMRK]: another QMRK '?'. ind={} indref={}", startindent, m_evt_handler->m_curr->indref); RYML_ASSERT_PARSE_CB_(callbacks(), startindent > m_evt_handler->m_curr->indref, m_evt_handler->m_curr->pos); _c4dbgp("mapblck[QMRK]: ? indent gt - start child mapblck (!)"); addrem_flags(RKCL, QMRK); _handle_annotations_before_blck_key_scalar(); m_evt_handler->begin_map_key_block(); addrem_flags(QMRK, RKCL); _set_indentation(startindent); // indentation_lt() should be handled elsewhere _line_progressed(1); _maybe_skipchars(' '); if(_is_blck_seq_token_maybe(m_evt_handler->m_curr->line_contents.rem)) { _c4dbgp("mapblck[RVAL]: seqblck starts after ?"); addrem_flags(RKCL, QMRK); m_evt_handler->begin_seq_key_block(); addrem_flags(RSEQ|RVAL, RMAP|RKCL); _save_indentation(); _line_progressed(1); _maybe_skipchars(' '); return false; } } else { _c4err("parse error"); } return true; // continue in mapblck } //----------------------------------------------------------------------------- // return true if we should remain in map_block template bool ParseEngine::_handle_map_block_rkcl() { // // handle indentation // if(m_evt_handler->m_curr->at_line_beginning()) { if(m_evt_handler->m_curr->indentation_eq()) { _c4dbgpf("mapblck[RKCL]: skip {} from indref", m_evt_handler->m_curr->indref); _line_progressed(m_evt_handler->m_curr->indref); if(!m_evt_handler->m_curr->line_contents.rem.len) return true; // continue in mapblck } else if C4_UNLIKELY(m_evt_handler->m_curr->indentation_lt()) { _c4err("invalid indentation"); } } const char first = m_evt_handler->m_curr->line_contents.rem.str[0]; _c4dbgpf("mapblck[RKCL]: '{}'", first); if(first == ':') { _c4dbgp("mapblck[RKCL]: found the colon"); _line_progressed(1); _maybe_skipchars(' '); #if defined(__GNUC__) && ( \ ((__GNUC__ >= 12) && ((C4_WORDSIZE == 4) || defined(C4_CPU_S390_X) || defined(C4_CPU_PPC64))) \ || \ (__GNUC__ == 16 && defined(C4_CPU_X86_64))) C4_DONT_OPTIMIZE(m_evt_handler->m_curr->line_contents.rem); #endif // sequence is valid after the RKCL ':' if(!_is_blck_seq_token_maybe(m_evt_handler->m_curr->line_contents.rem)) { addrem_flags(RVAL, RKCL); return true; // continue in mapblck } else { _c4dbgp("mapblck[RKCL]: start val seqblck"); addrem_flags(RNXT, RKCL); m_evt_handler->begin_seq_val_block(); addrem_flags(RSEQ|RVAL, RMAP|RNXT); _save_indentation(); _line_progressed(1); _maybe_skipchars(' '); return false; // finish mapblck } } else if(first == '?') { _c4dbgp("mapblck[RKCL]: got '?'. val was empty"); m_evt_handler->set_val_scalar_plain_empty(); m_evt_handler->add_sibling(); addrem_flags(QMRK, RKCL); _line_progressed(1); _maybe_skipchars(' '); if(_is_blck_seq_token_maybe(m_evt_handler->m_curr->line_contents.rem)) { _c4dbgp("mapblck[RKCL]: seqblck starts after ?"); addrem_flags(RKCL, QMRK); m_evt_handler->begin_seq_key_block(); addrem_flags(RSEQ|RVAL, RMAP|QMRK); _save_indentation(); _line_progressed(1); _maybe_skipchars(' '); return false; } } else if(first == '-') { if(m_evt_handler->m_curr->indref == 0 || m_evt_handler->m_curr->line_contents.indentation == 0 || _is_doc_begin_token(m_evt_handler->m_curr->line_contents.rem)) { _c4dbgp("mapblck[RKCL]: end+start doc"); RYML_CHECK_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, _is_doc_begin_token(m_evt_handler->m_curr->line_contents.rem), m_evt_handler->m_curr->pos); _start_doc_suddenly(); _line_progressed(3); _maybe_skip_whitespace_tokens(); return false; // finish mapblck } else { _c4err("parse error"); // LCOV_EXCL_LINE } } else if(first == '.') { _c4dbgp("mapblck[RKCL]: maybe end doc?"); csubstr rs = m_evt_handler->m_curr->line_contents.rem.sub(1); if(rs == ".." || rs.begins_with(".. ")) { _c4dbgp("mapblck[RKCL]: end+start doc"); _end_doc_suddenly(); _line_progressed(3); _maybe_skip_whitespace_tokens(); _check_doc_end_tokens(); return false; // finish mapblck } else { _c4err("parse error"); // LCOV_EXCL_LINE } } else/* if(m_was_inside_qmrk) */ { _c4dbgp("mapblck[RKCL]: missing :"); if C4_UNLIKELY(!m_evt_handler->m_curr->indentation_eq()) _c4err("parse error"); // LCOV_EXCL_LINE m_evt_handler->set_val_scalar_plain_empty(); m_evt_handler->add_sibling(); addrem_flags(RKEY, RKCL); } return true; } //----------------------------------------------------------------------------- template void ParseEngine::_handle_unk_json() { _c4dbgpf("handle_unk_json indref={} target={}", m_evt_handler->m_curr->indref, m_evt_handler->m_curr->node_id); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RNXT|RSEQ|RMAP), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_all(RTOP), m_evt_handler->m_curr->pos); _maybe_skip_comment(); csubstr rem = m_evt_handler->m_curr->line_contents.rem; if(!rem.len) return; size_t pos = rem.first_not_of(" \t"); if(pos) { pos = pos != npos ? pos : rem.len; _c4dbgpf("skipping indentation of {}", pos); _line_progressed(pos); rem = m_evt_handler->m_curr->line_contents.rem; if(!rem.len) return; _c4dbgpf("rem is now {}", prs_(rem)); } if(rem.begins_with('[')) { _c4dbgp("it's a seq"); _check_trailing_doc_token(); _maybe_begin_doc(); m_evt_handler->begin_seq_val_flow(); addrem_flags(RSEQ|RFLOW|RVAL, RUNK|RTOP|RDOC); _set_indentation(m_evt_handler->m_curr->line_contents.current_col(rem)); m_doc_empty = false; _line_progressed(1); } else if(rem.begins_with('{')) { _c4dbgp("it's a map"); _check_trailing_doc_token(); _maybe_begin_doc(); m_evt_handler->begin_map_val_flow(); addrem_flags(RMAP|RFLOW|RKEY, RVAL|RTOP|RUNK|RDOC); m_doc_empty = false; _set_indentation(m_evt_handler->m_curr->line_contents.current_col(rem)); _line_progressed(1); } else if(_handle_bom()) { _c4dbgp("byte order mark"); } else { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, ! has_any(SSCL), m_evt_handler->m_curr->pos); _maybe_skip_whitespace_tokens(); csubstr s = m_evt_handler->m_curr->line_contents.rem; if(!s.len) return; const size_t startindent = m_evt_handler->m_curr->line_contents.indentation; // save const char first = s.str[0]; ScannedScalar sc; if(first == '"') { _c4dbgp("runk_json: scanning double-quoted scalar"); _check_trailing_doc_token(); _maybe_begin_doc(); add_flags(RDOC); m_doc_empty = false; sc = _scan_scalar_dquot(); csubstr maybe_filtered = _maybe_filter_val_scalar_dquot(sc); if(!_maybe_scan_following_colon()) { _c4dbgp("runk_json: set as val"); _handle_annotations_before_blck_val_scalar(); m_evt_handler->set_val_scalar_dquoted(maybe_filtered); } else { _c4err("parse error"); } } else if(_scan_scalar_plain_unk(&sc)) { _c4dbgp("runk_json: got a plain scalar"); _check_trailing_doc_token(); _maybe_begin_doc(); add_flags(RDOC); m_doc_empty = false; if(!_maybe_scan_following_colon()) { _c4dbgp("runk_json: set as val"); _handle_annotations_before_blck_val_scalar(); csubstr maybe_filtered = _maybe_filter_val_scalar_plain(sc, startindent); m_evt_handler->set_val_scalar_plain(maybe_filtered); } else { _c4err("parse error"); // LCOV_EXCL_LINE } } else { _c4err("parse error"); // LCOV_EXCL_LINE } } } //----------------------------------------------------------------------------- template void ParseEngine::_handle_unk() { _c4dbgpf("handle_unk indref={} target={}", m_evt_handler->m_curr->indref, m_evt_handler->m_curr->node_id); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RNXT|RSEQ|RMAP), m_evt_handler->m_curr->pos); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_all(RTOP), m_evt_handler->m_curr->pos); _maybe_skipchars(' '); _maybe_skip_comment(); if(!m_evt_handler->m_curr->line_contents.rem.len) return; _c4dbgpf("runk: rem is now {}", prs_(m_evt_handler->m_curr->line_contents.rem)); if(m_evt_handler->m_curr->line_contents.indentation == 0u && (m_evt_handler->m_curr->at_line_beginning() || (m_bom_len && (m_evt_handler->m_curr->pos.line == m_bom_line)))) { _c4dbgpf("runk: rtop: zero indent + at line begin. offset={}", m_evt_handler->m_curr->pos.offset); _c4dbgp("runk: check BOM"); if(_handle_bom()) { m_bom_line = m_evt_handler->m_curr->pos.line; _c4dbgpf("runk: byte order mark! line={} offset={}", m_bom_line, m_evt_handler->m_curr->pos.offset); return; } const char first = m_evt_handler->m_curr->line_contents.rem.str[0]; _c4dbgpf("runk: rtop: first={}", _c4prc(first)); if(first == '-') { _c4dbgp("runk: rtop: suspecting doc"); if(_is_doc_begin_token(m_evt_handler->m_curr->line_contents.rem)) { _c4dbgp("runk: rtop: begin doc"); _maybe_end_doc(); _begin2_doc_expl(); _set_indentation(0); addrem_flags(RDOC|RUNK, NDOC); _line_progressed(3u); _maybe_skip_whitespace_tokens(); return; } } else if(first == '.') { _c4dbgp("runk: rtop: suspecting doc end"); if(_is_doc_end_token(m_evt_handler->m_curr->line_contents.rem)) { _c4dbgp("runk: rtop: end doc"); if(has_any(RDOC)) { _end2_doc_expl(); } else { _c4dbgp("runk: rtop: ignore end doc"); } addrem_flags(NDOC|RUNK, RDOC); _line_progressed(3u); _maybe_skip_whitespace_tokens(); _check_doc_end_tokens(); return; } } else if(first == '%') { _c4dbgpf("directive: {}", m_evt_handler->m_curr->line_contents.rem); if C4_UNLIKELY(has_any(RDOC) || (!m_doc_empty && has_none(NDOC))) _c4err("need document footer before directives"); _handle_directive(m_evt_handler->m_curr->line_contents.rem); return; } } /* no else-if! */ size_t startindent = m_evt_handler->m_curr->line_contents.indentation; size_t remindent = m_evt_handler->m_curr->line_contents.current_col(m_evt_handler->m_curr->line_contents.rem); if(m_bom_len) { _c4dbgpf("runk: prev BOMlen={}", m_bom_len); if(m_evt_handler->m_curr->pos.line == m_bom_line) { _c4dbgpf("runk: BOM remindent={} offset={}", remindent, m_evt_handler->m_curr->pos.offset); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, remindent >= m_bom_len, m_evt_handler->m_curr->pos); remindent -= m_bom_len; } else { m_bom_len = 0; } } size_t startcol = _handle_block_skip_leading_whitespace(); const char first = m_evt_handler->m_curr->line_contents.rem.str[0]; if(first == '[') { _c4dbgp("runk: flow seq?"); _handle_unk_begin_doc(); if C4_LIKELY( ! _annotations_require_key_container()) { _c4dbgp("runk: it's a seq, flow"); _handle_annotations_before_blck_val_scalar(); m_evt_handler->begin_seq_val_flow(); addrem_flags(RSEQ|RFLOW|RVAL, RUNK|RTOP|RDOC); _set_indentation(0); } else { _c4dbgp("runk: start new block map, set flow seq as key (!)"); _handle_annotations_before_start_mapblck(m_evt_handler->m_curr->pos.line); m_evt_handler->begin_map_val_block(); addrem_flags(RMAP|RBLCK|RKEY, RUNK|RTOP|RDOC); _handle_annotations_and_indentation_after_start_mapblck(remindent, m_evt_handler->m_curr->pos.line); m_evt_handler->begin_seq_key_flow(); addrem_flags(RSEQ|RFLOW|RVAL, RMAP|RBLCK|RKEY); _set_indentation(0); } _line_progressed(1); } else if(first == '{') { _c4dbgp("runk: flow map?"); _handle_unk_begin_doc(); if C4_LIKELY( ! _annotations_require_key_container()) { _c4dbgp("runk: it's a map, flow"); _handle_annotations_before_blck_val_scalar(); m_evt_handler->begin_map_val_flow(); addrem_flags(RMAP|RFLOW|RKEY, RVAL|RTOP|RUNK|RDOC); _set_indentation(0); } else { _c4dbgp("runk: start new block map, set flow map as key (!)"); _handle_annotations_before_start_mapblck(m_evt_handler->m_curr->pos.line); m_evt_handler->begin_map_val_block(); addrem_flags(RMAP|RBLCK|RKEY, RUNK|RTOP|RDOC); _handle_annotations_and_indentation_after_start_mapblck(remindent, m_evt_handler->m_curr->pos.line); m_evt_handler->begin_map_key_flow(); addrem_flags(RMAP|RFLOW, RBLCK); _set_indentation(0); } _line_progressed(1); } else if(first == '-' && _is_blck_token(m_evt_handler->m_curr->line_contents.rem)) { _c4dbgp("runk: it's a seq, block"); if C4_UNLIKELY(!m_evt_handler->m_curr->at_first_token()) startindent = _handle_unk_check_left_tokens(startindent, m_evt_handler->m_curr->pos.col, /*skip_annotations*/false); _handle_unk_begin_doc(); _handle_annotations_before_blck_val_scalar(); m_evt_handler->begin_seq_val_block(); addrem_flags(RSEQ|RBLCK|RVAL, RNXT|RTOP|RUNK|RDOC); _set_indentation(startindent); _line_progressed(1); _maybe_skipchars(' '); } else if(first == '?' && _is_blck_token(m_evt_handler->m_curr->line_contents.rem)) { _c4dbgp("runk: it's a map + this key is complex"); if C4_UNLIKELY(!m_evt_handler->m_curr->at_first_token()) startindent = _handle_unk_check_left_tokens(startindent, m_evt_handler->m_curr->pos.col, /*skip_annotations*/false); _handle_block_check_leading_tabs(startcol); _handle_unk_begin_doc(); _handle_annotations_before_blck_val_scalar(); m_evt_handler->begin_map_val_block(); addrem_flags(RMAP|RBLCK|QMRK, RKEY|RVAL|RTOP|RUNK|RDOC); _set_indentation(startindent); _line_progressed(1); _maybe_skipchars(' '); if(_is_blck_seq_token_maybe(m_evt_handler->m_curr->line_contents.rem)) { _c4dbgp("runk: seqblck key starts after ?"); addrem_flags(RKCL, QMRK); m_evt_handler->begin_seq_key_block(); addrem_flags(RSEQ|RVAL, RMAP|RKCL); _save_indentation(); _line_progressed(1); _maybe_skipchars(' '); } } else if(first == ':' && _is_blck_token(m_evt_handler->m_curr->line_contents.rem)) { if(m_doc_empty || (m_pending_anchors.num_entries | m_pending_tags.num_entries)) { _c4dbgp("runk: it's a map with an empty key"); if C4_UNLIKELY(!m_evt_handler->m_curr->at_first_token()) startindent = _handle_unk_check_left_tokens(startindent, m_evt_handler->m_curr->pos.col); _handle_block_check_leading_tabs(startcol); const size_t startline = m_evt_handler->m_curr->pos.line; // save _handle_unk_begin_doc(); _handle_annotations_before_start_mapblck(startline); _handle_colon(); m_evt_handler->begin_map_val_block(); _handle_annotations_and_indentation_after_start_mapblck(startindent, startline); m_evt_handler->set_key_scalar_plain_empty(); _set_indentation(startindent); } else { _c4err("block colon cannot occur on a new line unless ? is used"); } addrem_flags(RMAP|RBLCK|RVAL, RTOP|RUNK|RDOC); _line_progressed(1); _maybe_skip_whitespace_tokens(); } else if(first == '&') { csubstr anchor = _scan_anchor(); _c4dbgpf("anchor! {}", prs_(anchor)); const size_t line = m_evt_handler->m_curr->pos.line; _handle_unk_begin_doc(); _add_annotation(&m_pending_anchors, anchor, remindent, line); _set_indentation(0); } else if(first == '*') { csubstr ref = _scan_ref_map(); _c4dbgpf("runk: ref! {}", prs_(ref)); _handle_unk_begin_doc(); if(!_maybe_scan_following_colon()) { _c4dbgp("runk: set val ref"); _handle_valref(ref); } else { _c4dbgp("runk: start new block map, set ref as key"); _handle_block_check_leading_tabs(startcol); const size_t startline = m_evt_handler->m_curr->pos.line; // save _handle_annotations_before_start_mapblck(startline); m_evt_handler->begin_map_val_block(); _handle_keyref(ref); _maybe_skip_whitespace_tokens(); _set_indentation(0); addrem_flags(RMAP|RBLCK|RVAL, RTOP|RUNK|RDOC); } } else if(first == '!') { csubstr tag_orig; csubstr tag = _scan_tag(&tag_orig); _c4dbgpf("runk: val tag! {}", prs_(tag)); // we need to buffer the tags, as there may be two // consecutive tags in here const size_t indentation = m_evt_handler->m_curr->line_contents.current_col(m_evt_handler->m_curr->line_contents.rem); const size_t line = m_evt_handler->m_curr->pos.line; _add_annotation(&m_pending_tags, tag, indentation, line, tag_orig); } else { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, ! has_any(SSCL), m_evt_handler->m_curr->pos); const size_t startscalar = _handle_block_get_whitespace_mark(); const size_t startline = m_evt_handler->m_curr->pos.line; // save auto beginmap = [&](size_t startindent_){ if C4_UNLIKELY(m_evt_handler->m_curr->pos.line > startline) _c4err("multiline scalars cannot be used as implicit keys"); _handle_block_check_leading_tabs(startcol, startscalar); _handle_annotations_before_start_mapblck(startline); _handle_colon(); m_evt_handler->begin_map_val_block(); _handle_annotations_and_indentation_after_start_mapblck(startindent_, startline); }; auto after_beginmap = [&](size_t startindent_){ _maybe_skip_whitespace_tokens(); _set_indentation(startindent_); addrem_flags(RMAP|RBLCK|RVAL, RTOP|RUNK|RDOC); }; if(first == '|') { _c4dbgp("runk: block-literal scalar"); _handle_unk_begin_doc(); ScannedBlock sb; _scan_block(&sb, startindent); _handle_annotations_before_blck_val_scalar(); csubstr maybe_filtered = _maybe_filter_val_scalar_literal(sb); m_evt_handler->set_val_scalar_literal(maybe_filtered); } else if(first == '>') { _c4dbgp("runk: block-folded scalar"); _handle_unk_begin_doc(); ScannedBlock sb; _scan_block(&sb, startindent); _handle_annotations_before_blck_val_scalar(); csubstr maybe_filtered = _maybe_filter_val_scalar_folded(sb); m_evt_handler->set_val_scalar_folded(maybe_filtered); } else if(first == '\'') { _c4dbgp("runk: single-quoted scalar"); _handle_unk_begin_doc(); bool firsttoken = m_evt_handler->m_curr->at_first_token(); size_t col = m_evt_handler->m_curr->pos.col; ScannedScalar sc = _scan_scalar_squot(); if(!_maybe_scan_following_colon()) { _c4dbgp("runk: set as val"); _handle_annotations_before_blck_val_scalar(); csubstr maybe_filtered = _maybe_filter_val_scalar_squot(sc); m_evt_handler->set_val_scalar_squoted(maybe_filtered); } else { _c4dbgp("runk: start new block map, set single-quoted scalar as key"); if C4_UNLIKELY(m_evt_handler->m_curr->pos.line > startline) _c4err("multiline key"); if(!firsttoken) startindent = _handle_unk_check_left_tokens(startindent, col); beginmap(startindent); csubstr maybe_filtered = _maybe_filter_val_scalar_squot(sc); m_evt_handler->set_key_scalar_squoted(maybe_filtered); after_beginmap(startindent); } } else if(first == '"') { _c4dbgp("runk: double-quoted scalar"); _handle_unk_begin_doc(); bool firsttoken = m_evt_handler->m_curr->at_first_token(); size_t col = m_evt_handler->m_curr->pos.col; ScannedScalar sc = _scan_scalar_dquot(); if(!_maybe_scan_following_colon()) { _c4dbgp("runk: set as val"); _handle_annotations_before_blck_val_scalar(); csubstr maybe_filtered = _maybe_filter_val_scalar_dquot(sc); m_evt_handler->set_val_scalar_dquoted(maybe_filtered); } else { _c4dbgp("runk: start new block map, set double-quoted scalar as key"); if C4_UNLIKELY(m_evt_handler->m_curr->pos.line > startline) _c4err("multiline key"); if(!firsttoken) startindent = _handle_unk_check_left_tokens(startindent, col); beginmap(startindent); csubstr maybe_filtered = _maybe_filter_val_scalar_dquot(sc); m_evt_handler->set_key_scalar_dquoted(maybe_filtered); after_beginmap(startindent); } } else { bool firsttoken = m_evt_handler->m_curr->at_first_token(); size_t col = m_evt_handler->m_curr->pos.col; ScannedScalar sc; if(_scan_scalar_plain_unk(&sc)) { _c4dbgp("runk: plain scalar"); _handle_unk_begin_doc(); if(!_maybe_scan_following_colon()) { _c4dbgp("runk: set as val"); _handle_annotations_before_blck_val_scalar(); csubstr maybe_filtered = _maybe_filter_val_scalar_plain(sc, startindent); m_evt_handler->set_val_scalar_plain(maybe_filtered); } else { _c4dbgp("runk: start new block map, set plain scalar as key"); // there is already a check to multiline inside // _scan_scalar_plain_unk(), so we don't need to // throw an error here. but let's be safe by // asserting the assumption: _c4assert(m_evt_handler->m_curr->pos.line == startline); if(!firsttoken) startindent = _handle_unk_check_left_tokens(startindent, col); beginmap(startindent); csubstr maybe_filtered = _maybe_filter_val_scalar_plain(sc, startindent); m_evt_handler->set_key_scalar_plain(maybe_filtered); after_beginmap(startindent); } } else { _c4err("parse error"); // LCOV_EXCL_LINE } } } if(m_bom_len && has_none(RUNK)) { _c4dbgpf("runk: BOMlen={} BOMline={} now={} at_end={}", m_bom_len, m_bom_line, m_evt_handler->m_curr->pos.line, !m_evt_handler->m_curr->line_contents.rem.len); if(m_evt_handler->m_curr->pos.line != m_bom_line || !m_evt_handler->m_curr->line_contents.rem.len) { _c4dbgp("runk: clear BOMlen"); m_bom_len = 0; } } } template void ParseEngine::_handle_unk_begin_doc() { _c4dbgp("runk: begin doc"); _check_trailing_doc_token(); _maybe_begin_doc(); add_flags(RDOC); m_doc_empty = false; } template size_t ParseEngine::_handle_unk_check_left_tokens(size_t realindent, size_t col, bool skip_annotations) { _c4assert(col >= 1); col -= 1; _c4assert(col >= m_bom_len); csubstr s = m_evt_handler->m_curr->line_contents.full.range(m_bom_len, col); size_t pos = 0; _c4dbgpf("runk: check left tokens: s={}", prs_(s, /*escape*/true)); if(skip_annotations) { _handle_unk_get_first_non_pending_token_pos(s, &realindent, &pos); _c4dbgpf("runk: skip annotations: realindent={} pos={}", realindent, pos); } size_t firstns = s.first_not_of(' ', pos); if(firstns == npos) firstns = s.len; _c4dbgpf("runk: check left tokens:\n" " tokens={} skipped={}\n" " bomlen={} first={} col={}\n" " (bomlen+first)={} vs {}=col\n" " startindent={} lineindent={}" , prs_(s, /*escape*/true), prs_(s.sub(firstns), /*escape*/true) , m_bom_len, firstns, col , m_bom_len+firstns, col, realindent, m_evt_handler->m_curr->line_contents.indentation); if(m_bom_len + firstns != col) _c4err("parse error"); if(!skip_annotations) realindent = firstns; _c4dbgpf("runk: pos={} firstns={} -> realindent={}", pos, firstns, realindent); return realindent; } /** skip annotations which are pending on the same line */ template void ParseEngine::_handle_unk_get_first_non_pending_token_pos(csubstr s, size_t *indent, size_t *first_non_token_pos) { csubstr first, second; uint32_t total = _get_annotations_same_line(s, &first, &second); _c4dbgpf("runk: before skip: {}", prs_(s, true)); size_t pos = s.first_not_of(" \t"); if(pos == npos) pos = s.len; if(!total) { *indent = *first_non_token_pos = pos; return; } _c4assert(!s.sub(pos).begins_with_any(" \t")); _c4dbgpf("runk: after skip leading {} whitespace: {}", pos, prs_(s.sub(pos), true)); _c4dbgpf("runk: first annotation: {}", first); _c4assert(first.len); _c4assert(first.is_sub(s)); _c4assert(first.is_sub(s.sub(pos))); _c4assert(s.sub(pos).begins_with(first)); *indent = pos; pos += first.len; _c4dbgpf("runk: after skip first annotation: pos={} {}", pos, prs_(s.sub(pos), true)); if(total > 1) { _c4dbgpf("runk: second annotation: {}", second); _c4assert(total == 2); _c4assert(second.len); _c4assert(second.is_sub(s)); _c4assert(second.is_sub(s.sub(pos))); csubstr spos = s.sub(pos); size_t more = spos.first_not_of(" \t"); _c4assert(more != npos); // because the annotations are on the same line _c4dbgpf("runk: next nonspace: {}", pos + more); pos += more; _c4dbgpf("runk: after skip annotation whitespace: pos={} {}", pos, prs_(s.sub(pos), true)); _c4assert(s.sub(pos).begins_with(second)); pos += second.len; _c4dbgpf("runk: after skip annotation 2: pos={} {}", pos, prs_(s.sub(pos), true)); } *first_non_token_pos = pos; } template uint32_t ParseEngine::_get_annotations_same_line(csubstr token_soup, csubstr *first_, csubstr *second_) const { _c4assert(!m_evt_handler->m_curr->at_first_token()); (void)token_soup; using EntryPtr = typename Annotation::Entry const* C4_RESTRICT; EntryPtr first = nullptr; EntryPtr second = nullptr; uint32_t total = (uint32_t)(m_pending_anchors.num_entries + m_pending_tags.num_entries); if(total) { _c4dbgpf("there are {} pending annotations: {} anchors + {} tags", total, m_pending_anchors.num_entries, m_pending_tags.num_entries); auto valid_if_same_line = [this](EntryPtr entry){ _c4dbgpf("pending: {} indent={} line={} vs currline={}", maybe_null_str_(entry->str), entry->indentation, entry->line, m_evt_handler->m_curr->pos.line); return (entry->line == m_evt_handler->m_curr->pos.line) ? entry : nullptr; }; // now select annotations only on the same line total = 0; for(size_t i = 0; i < m_pending_anchors.num_entries; ++i) total += !!valid_if_same_line(&m_pending_anchors.annotations[i]); for(size_t i = 0; i < m_pending_tags.num_entries; ++i) total += !!valid_if_same_line(&m_pending_tags.annotations[i]); _c4dbgpf("{} annotations on same line", total); _c4assert(total > 0); // because this function is only called // while not at the first token. That // means we must have same-line // annotations. auto get_first_on_same_line = [this](EntryPtr not_this_one){ for(size_t i = 0; i < m_pending_anchors.num_entries; ++i) if(&m_pending_anchors.annotations[i] != not_this_one && m_pending_anchors.annotations[i].line == m_evt_handler->m_curr->pos.line) return &m_pending_anchors.annotations[i]; for(size_t i = 0; i < m_pending_tags.num_entries; ++i) if(&m_pending_tags.annotations[i] != not_this_one && m_pending_tags.annotations[i].line == m_evt_handler->m_curr->pos.line) return &m_pending_tags.annotations[i]; C4_UNREACHABLE(); // LCOV_EXCL_LINE return (EntryPtr)nullptr; // LCOV_EXCL_LINE }; _c4assert(total >= 1); // assign to first first = get_first_on_same_line(nullptr); _c4assert(first); _c4dbgpf("first annotation: {} indent={} line={}", maybe_null_str_(first->str), first->indentation, first->line); if(total > 1) { _c4assert(total == 2); // assign to second second = get_first_on_same_line(first); _c4assert(second); _c4dbgpf("second annotation: {} indent={} line={}", maybe_null_str_(second->str), second->indentation, second->line); } auto extract_string = [&](EntryPtr e){ // tags can be null when the arena ran out of space if(!e->str.str || e->str.begins_with_any("!<")) { csubstr tag = e->orig; _c4assert(tag.str); _c4assert(tag.len); _c4assert(tag.is_sub(token_soup)); _c4dbgpf("tag: {} -> {}", maybe_null_str_(e->str), tag); return tag; } csubstr anchor = e->str; _c4assert(anchor.len); _c4assert(anchor.str); _c4assert(anchor.is_sub(token_soup)); _c4assert(!anchor.begins_with('&')); _c4assert(anchor.str - token_soup.str > 0); // add back the anchor's & --anchor.str; ++anchor.len; _c4assert(anchor.begins_with('&')); _c4dbgpf("anchor: {} -> {}", e->str, anchor); return anchor; }; *first_ = first ? extract_string(first) : nullptr; *second_ = second ? extract_string(second) : nullptr; if(total > 1 && (first_->str > second_->str)) { csubstr tmp = *first_; *first_ = *second_; *second_ = tmp; _c4dbgpf("swap first and second: {} -> {}", *first_, *second_); } } return total; } //----------------------------------------------------------------------------- template C4_COLD void ParseEngine::_handle_usty() { _c4dbgpf("handle_usty target={}", m_evt_handler->m_curr->indref, m_evt_handler->m_curr->node_id); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_none(RBLCK|RFLOW), m_evt_handler->m_curr->pos); #ifdef RYML_NO_COVERAGE__TO_BE_DELETED if(has_any(RNXT)) { _c4dbgp("usty[RNXT]: finishing!"); _end_stream(); } #endif _maybe_skip_comment(); csubstr rem = m_evt_handler->m_curr->line_contents.rem; if(!rem.len) return; size_t pos = rem.first_not_of(" \t"); if(pos) { pos = pos != npos ? pos : rem.len; _c4dbgpf("skipping indentation of {}", pos); _line_progressed(pos); rem = m_evt_handler->m_curr->line_contents.rem; if(!rem.len) return; _c4dbgpf("rem is now {}", prs_(rem)); } RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, rem.len > 0, m_evt_handler->m_curr->pos); size_t startindent = m_evt_handler->m_curr->line_contents.indentation; // save char first = rem.str[0]; if(has_any(RSEQ)) // destination is a sequence { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, ! has_any(RMAP), m_evt_handler->m_curr->pos); _c4dbgpf("usty[RSEQ]: first='{}'", _c4prc(first)); if(first == '[') { _c4dbgp("usty[RSEQ]: it's a flow seq. merging it"); add_flags(RNXT); m_evt_handler->_push(); addrem_flags(RFLOW|RVAL, RNXT|USTY); _set_indentation(startindent); _line_progressed(1); _maybe_skip_whitespace_tokens(); } else if(first == '-' && _is_blck_token(rem)) { _c4dbgp("usty[RSEQ]: it's a block seq. merging it"); add_flags(RNXT); m_evt_handler->_push(); addrem_flags(RBLCK|RVAL, RNXT|USTY); _set_indentation(startindent); _line_progressed(1); _maybe_skip_whitespace_tokens(); } else { _c4err("can only parse a seq into an existing seq"); } } else if(has_any(RMAP)) // destination is a map { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, ! has_any(RSEQ), m_evt_handler->m_curr->pos); _c4dbgpf("usty[RMAP]: first='{}'", _c4prc(first)); if(first == '{') { _c4dbgp("usty[RMAP]: it's a flow map. merging it"); add_flags(RNXT); _handle_annotations_before_blck_val_scalar(); m_evt_handler->_push(); addrem_flags(RMAP|RFLOW|RKEY, RNXT|USTY); _set_indentation(startindent); _line_progressed(1); _maybe_skip_whitespace_tokens(); } else if(first == '?' && _is_blck_token(rem)) { _c4dbgp("usty[RMAP]: it's a block map + this key is complex"); add_flags(RNXT); _handle_annotations_before_blck_val_scalar(); m_evt_handler->_push(); addrem_flags(RMAP|RBLCK|QMRK, RNXT|USTY); _save_indentation(); _line_progressed(1); _maybe_skip_whitespace_tokens(); } else if(first == ':' && _is_blck_token(rem)) { _c4dbgp("usty[RMAP]: it's a map with an empty key"); add_flags(RNXT); _handle_annotations_before_blck_val_scalar(); m_evt_handler->_push(); m_evt_handler->set_key_scalar_plain_empty(); addrem_flags(RMAP|RBLCK|RVAL, RNXT|USTY); _save_indentation(); _line_progressed(1); _maybe_skip_whitespace_tokens(); } else if(rem.begins_with('&')) { csubstr anchor = _scan_anchor(); _c4dbgpf("usty[RMAP]: anchor! {}", prs_(anchor)); const size_t indentation = m_evt_handler->m_curr->line_contents.current_col(rem); const size_t line = m_evt_handler->m_curr->pos.line; _add_annotation(&m_pending_anchors, anchor, indentation, line); _set_indentation(m_evt_handler->m_curr->line_contents.current_col(rem)); } else if(first == '*') { csubstr ref = _scan_ref_map(); _c4dbgpf("usty[RMAP]: ref! {}", prs_(ref)); if(!_maybe_scan_following_colon()) { _c4err("cannot read a VAL to a map"); } else { _c4dbgp("usty[RMAP]: start new block map, set ref as key"); const size_t startline = m_evt_handler->m_curr->pos.line; // save add_flags(RNXT); _handle_annotations_before_start_mapblck(startline); m_evt_handler->_push(); _handle_keyref(ref); _maybe_skip_whitespace_tokens(); _set_indentation(startindent); addrem_flags(RMAP|RBLCK|RVAL, RNXT|USTY); } } else if(first == '!') { csubstr tag = _scan_tag(); _c4dbgpf("usty[RMAP]: val tag! {}", prs_(tag)); // we need to buffer the tags, as there may be two // consecutive tags in here const size_t indentation = m_evt_handler->m_curr->line_contents.current_col(rem); const size_t line = m_evt_handler->m_curr->pos.line; _add_annotation(&m_pending_tags, tag, indentation, line); } else if(first == '[' || (first == '-' && _is_blck_token(rem))) { _c4err("cannot parse a seq into an existing map"); } else { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, ! has_any(SSCL), m_evt_handler->m_curr->pos); startindent = m_evt_handler->m_curr->line_contents.indentation; // save const size_t startline = m_evt_handler->m_curr->pos.line; // save ScannedScalar sc; _c4dbgpf("usty[RMAP]: maybe scalar. first='{}'", _c4prc(first)); if(first == '\'') { _c4dbgp("usty[RMAP]: scanning single-quoted scalar"); sc = _scan_scalar_squot(); if(!_maybe_scan_following_colon()) { _c4err("cannot read a VAL to a map"); } else { _c4dbgp("usty[RMAP]: start new block map, set scalar as key"); add_flags(RNXT); _handle_annotations_before_start_mapblck(startline); m_evt_handler->_push(); _handle_annotations_and_indentation_after_start_mapblck(startindent, startline); csubstr maybe_filtered = _maybe_filter_key_scalar_squot(sc); m_evt_handler->set_key_scalar_squoted(maybe_filtered); _set_indentation(startindent); addrem_flags(RMAP|RBLCK|RVAL, RNXT|USTY); _maybe_skip_whitespace_tokens(); } } else if(first == '"') { _c4dbgp("usty[RMAP]: scanning double-quoted scalar"); sc = _scan_scalar_dquot(); if(!_maybe_scan_following_colon()) { _c4err("cannot read a VAL to a map"); } else { _c4dbgp("usty[RMAP]: start new block map, set double-quoted scalar as key"); add_flags(RNXT); _handle_annotations_before_start_mapblck(startline); m_evt_handler->_push(); _handle_annotations_and_indentation_after_start_mapblck(startindent, startline); csubstr maybe_filtered = _maybe_filter_key_scalar_dquot(sc); m_evt_handler->set_key_scalar_dquoted(maybe_filtered); _set_indentation(startindent); addrem_flags(RMAP|RBLCK|RVAL, RNXT|USTY); _maybe_skip_whitespace_tokens(); } } else if(first == '|') { _c4err("block literal keys must be enclosed in '?'"); } else if(first == '>') { _c4err("block literal keys must be enclosed in '?'"); } else if(_scan_scalar_plain_unk(&sc)) { _c4dbgp("usty[RMAP]: got a plain scalar"); if(!_maybe_scan_following_colon()) { _c4err("cannot read a VAL to a map"); } else { _c4dbgp("usty[RMAP]: start new block map, set scalar as key"); add_flags(RNXT); _handle_annotations_before_start_mapblck(startline); m_evt_handler->_push(); _handle_annotations_and_indentation_after_start_mapblck(startindent, startline); csubstr maybe_filtered = _maybe_filter_key_scalar_plain(sc, startindent); m_evt_handler->set_key_scalar_plain(maybe_filtered); _set_indentation(startindent); addrem_flags(RMAP|RBLCK|RVAL, RNXT|USTY); _maybe_skip_whitespace_tokens(); } } else { _c4err("parse error"); // LCOV_EXCL_LINE } } } else // destination is unknown { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, ! has_any(RSEQ), m_evt_handler->m_curr->pos); _c4dbgpf("usty[UNK]: first='{}'", _c4prc(first)); if(first == '[') { _c4dbgp("usty[UNK]: it's a flow seq"); add_flags(RNXT); _handle_annotations_before_blck_val_scalar(); m_evt_handler->begin_seq_val_flow(); addrem_flags(RSEQ|RFLOW|RVAL, RNXT|USTY); _set_indentation(startindent); _line_progressed(1); _maybe_skip_whitespace_tokens(); } else if(first == '-' && _is_blck_token(rem)) { _c4dbgp("usty[UNK]: it's a block seq"); add_flags(RNXT); _handle_annotations_before_blck_val_scalar(); m_evt_handler->begin_seq_val_block(); addrem_flags(RSEQ|RBLCK|RVAL, RNXT|USTY); _set_indentation(startindent); _line_progressed(1); _maybe_skip_whitespace_tokens(); } else if(first == '{') { _c4dbgp("usty[UNK]: it's a flow map"); add_flags(RNXT); _handle_annotations_before_blck_val_scalar(); m_evt_handler->begin_map_val_flow(); addrem_flags(RMAP|RFLOW|RKEY, RNXT|USTY); _set_indentation(startindent); _line_progressed(1); _maybe_skip_whitespace_tokens(); } else if(first == '?' && _is_blck_token(rem)) { _c4dbgp("usty[UNK]: it's a map + this key is complex"); add_flags(RNXT); _handle_annotations_before_blck_val_scalar(); m_evt_handler->begin_map_val_block(); addrem_flags(RMAP|RBLCK|QMRK, RNXT|USTY); _save_indentation(); _line_progressed(1); _maybe_skip_whitespace_tokens(); } else if(first == ':' && _is_blck_token(rem)) { _c4dbgp("usty[UNK]: it's a map with an empty key"); add_flags(RNXT); _handle_annotations_before_blck_val_scalar(); m_evt_handler->begin_map_val_block(); m_evt_handler->set_key_scalar_plain_empty(); addrem_flags(RMAP|RBLCK|RVAL, RNXT|USTY); _save_indentation(); _line_progressed(1); _maybe_skip_whitespace_tokens(); } else if(first == '&') { csubstr anchor = _scan_anchor(); _c4dbgpf("usty[UNK]: anchor! {}", prs_(anchor)); const size_t indentation = m_evt_handler->m_curr->line_contents.current_col(rem); const size_t line = m_evt_handler->m_curr->pos.line; _add_annotation(&m_pending_anchors, anchor, indentation, line); _set_indentation(m_evt_handler->m_curr->line_contents.current_col(rem)); } else if(first == '*') { csubstr ref = _scan_ref_map(); _c4dbgpf("usty[UNK]: ref! {}", prs_(ref)); if(!_maybe_scan_following_colon()) { _c4dbgp("usty[UNK]: set val ref"); _handle_valref(ref); } else { _c4dbgp("usty[UNK]: start new block map, set ref as key"); const size_t startline = m_evt_handler->m_curr->pos.line; // save add_flags(RNXT); _handle_annotations_before_start_mapblck(startline); m_evt_handler->begin_map_val_block(); _handle_keyref(ref); _maybe_skip_whitespace_tokens(); _set_indentation(startindent); addrem_flags(RMAP|RBLCK|RVAL, RNXT|USTY); } } else if(first == '!') { csubstr tag = _scan_tag(); _c4dbgpf("usty[UNK]: val tag! {}", prs_(tag)); // we need to buffer the tags, as there may be two // consecutive tags in here const size_t indentation = m_evt_handler->m_curr->line_contents.current_col(rem); const size_t line = m_evt_handler->m_curr->pos.line; _add_annotation(&m_pending_tags, tag, indentation, line); } else { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, ! has_any(SSCL), m_evt_handler->m_curr->pos); startindent = m_evt_handler->m_curr->line_contents.indentation; // save const size_t startline = m_evt_handler->m_curr->pos.line; // save first = rem.str[0]; ScannedScalar sc; _c4dbgpf("usty[UNK]: maybe scalar. first='{}'", _c4prc(first)); if(first == '\'') { _c4dbgp("usty[UNK]: scanning single-quoted scalar"); sc = _scan_scalar_squot(); if(!_maybe_scan_following_colon()) { _c4dbgp("usty[UNK]: set as val"); _handle_annotations_before_blck_val_scalar(); csubstr maybe_filtered = _maybe_filter_val_scalar_squot(sc); m_evt_handler->set_val_scalar_squoted(maybe_filtered); _end_stream(); } else { _c4dbgp("usty[UNK]: start new block map, set scalar as key"); add_flags(RNXT); _handle_annotations_before_start_mapblck(startline); m_evt_handler->begin_map_val_block(); _handle_annotations_and_indentation_after_start_mapblck(startindent, startline); csubstr maybe_filtered = _maybe_filter_key_scalar_squot(sc); m_evt_handler->set_key_scalar_squoted(maybe_filtered); _set_indentation(startindent); addrem_flags(RMAP|RBLCK|RVAL, RNXT|USTY); _maybe_skip_whitespace_tokens(); } } else if(first == '"') { _c4dbgp("usty[UNK]: scanning double-quoted scalar"); sc = _scan_scalar_dquot(); if(!_maybe_scan_following_colon()) { _c4dbgp("usty[UNK]: set as val"); _handle_annotations_before_blck_val_scalar(); csubstr maybe_filtered = _maybe_filter_val_scalar_dquot(sc); m_evt_handler->set_val_scalar_dquoted(maybe_filtered); _end_stream(); } else { _c4dbgp("usty[UNK]: start new block map, set double-quoted scalar as key"); add_flags(RNXT); _handle_annotations_before_start_mapblck(startline); m_evt_handler->begin_map_val_block(); _handle_annotations_and_indentation_after_start_mapblck(startindent, startline); csubstr maybe_filtered = _maybe_filter_key_scalar_dquot(sc); m_evt_handler->set_key_scalar_dquoted(maybe_filtered); _set_indentation(startindent); addrem_flags(RMAP|RBLCK|RVAL, RNXT|USTY); _maybe_skip_whitespace_tokens(); } } else if(first == '|') { _c4dbgp("usty[UNK]: scanning block-literal scalar"); ScannedBlock sb; _scan_block(&sb, startindent); _c4dbgp("usty[UNK]: set as val"); _handle_annotations_before_blck_val_scalar(); csubstr maybe_filtered = _maybe_filter_val_scalar_literal(sb); m_evt_handler->set_val_scalar_literal(maybe_filtered); _end_stream(); } else if(first == '>') { _c4dbgp("usty[UNK]: scanning block-folded scalar"); ScannedBlock sb; _scan_block(&sb, startindent); _c4dbgp("usty[UNK]: set as val"); _handle_annotations_before_blck_val_scalar(); csubstr maybe_filtered = _maybe_filter_val_scalar_folded(sb); m_evt_handler->set_val_scalar_folded(maybe_filtered); _end_stream(); } else if(_scan_scalar_plain_unk(&sc)) { _c4dbgp("usty[UNK]: got a plain scalar"); if(!_maybe_scan_following_colon()) { _c4dbgp("usty[UNK]: set as val"); _handle_annotations_before_blck_val_scalar(); csubstr maybe_filtered = _maybe_filter_val_scalar_plain(sc, startindent); m_evt_handler->set_val_scalar_plain(maybe_filtered); _end_stream(); } else { _c4dbgp("usty[UNK]: start new block map, set scalar as key"); add_flags(RNXT); _handle_annotations_before_start_mapblck(startline); m_evt_handler->begin_map_val_block(); _handle_annotations_and_indentation_after_start_mapblck(startindent, startline); csubstr maybe_filtered = _maybe_filter_key_scalar_plain(sc, startindent); m_evt_handler->set_key_scalar_plain(maybe_filtered); _set_indentation(startindent); addrem_flags(RMAP|RBLCK|RVAL, RNXT|USTY); _maybe_skip_whitespace_tokens(); } } else { _c4err("parse error"); // LCOV_EXCL_LINE } } } } //----------------------------------------------------------------------------- template void ParseEngine::parse_json_in_place_ev(csubstr filename, substr src) { RYML_ASSERT_BASIC_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_stack.size() >= 1); RYML_SAVE_TEST_JSON_(filename, src); m_evt_handler->start_parse(filename.str, src); m_evt_handler->begin_stream(); _reset(); while( ! _finished_file()) { _scan_line(); while( ! _finished_line()) { _c4dbgnextline(); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, ! m_evt_handler->m_curr->line_contents.rem.empty(), m_evt_handler->m_curr->pos); if(has_any(RSEQ)) { _handle_seq_json(); } else if(has_any(RMAP)) { _handle_map_json(); } else if(has_any(RUNK)) { _handle_unk_json(); } else { _c4err("internal error"); // LCOV_EXCL_LINE } } if(_finished_file()) break; // it may have finished because of multiline blocks _line_ended(); } _end_stream(); m_evt_handler->finish_parse(); } //----------------------------------------------------------------------------- template void ParseEngine::parse_in_place_ev(csubstr filename, substr src) { RYML_ASSERT_BASIC_CB_(m_evt_handler->m_stack.m_callbacks, m_evt_handler->m_stack.size() >= 1); RYML_SAVE_TEST_YAML_(filename, src); m_evt_handler->start_parse(filename.str, src); m_evt_handler->begin_stream(); _reset(); while( ! _finished_file()) { _scan_line(); while( ! _finished_line()) { _c4dbgnextline(); RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, ! m_evt_handler->m_curr->line_contents.rem.empty(), m_evt_handler->m_curr->pos); if(has_any(RFLOW)) { if(has_none(RSEQIMAP)) { if(has_any(RSEQ)) { _handle_seq_flow(); } else { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_all(RMAP), m_evt_handler->m_curr->pos); _handle_map_flow(); } } else { _handle_seq_imap(); } } else if(has_any(RBLCK)) { if(has_any(RSEQ)) { _handle_seq_block(); } else { RYML_ASSERT_PARSE_CB_(m_evt_handler->m_stack.m_callbacks, has_all(RMAP), m_evt_handler->m_curr->pos); _handle_map_block(); } } else if(has_any(RUNK)) { _handle_unk(); } else if(has_any(USTY)) { _handle_usty(); } else { _c4err("internal error"); // LCOV_EXCL_LINE } } if(_finished_file()) break; // it may have finished because of multiline blocks _line_ended(); } _end_stream(); m_evt_handler->finish_parse(); } /** @endcond */ } // namespace yml } // namespace c4 // NOLINTEND(hicpp-signed-bitwise,cppcoreguidelines-avoid-goto,hicpp-avoid-goto,hicpp-multiway-paths-covered,modernize-avoid-c-style-cast) #undef _c4dbgnextline #undef _c4assert #undef _c4err C4_SUPPRESS_WARNING_MSVC_POP C4_SUPPRESS_WARNING_GCC_CLANG_POP #endif // C4_YML_PARSE_ENGINE_DEF_HPP_ // (end src/c4/yml/parse_engine.def.hpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/tree.cpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifdef RYML_SINGLE_HDR_DEFINE_NOW #ifndef C4_YML_TREE_HPP_ //#include "c4/yml/tree.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/tree.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_DETAIL_DBGPRINT_HPP_ //#include "c4/yml/detail/dbgprint.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/detail/dbgprint.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_NODE_HPP_ //#include "c4/yml/node.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/node.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_REFERENCE_RESOLVERS_HPP_ #ifndef C4_YML_REFERENCE_RESOLVER_HPP_ //#include "c4/yml/reference_resolver.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/reference_resolver.hpp must have been amalgamated before this point" #endif /* C4_YML_REFERENCE_RESOLVER_HPP_ */ #endif C4_SUPPRESS_WARNING_MSVC_WITH_PUSH(4296/*expression is always 'boolean_value'*/) C4_SUPPRESS_WARNING_MSVC(4702/*unreachable code*/) C4_SUPPRESS_WARNING_GCC_CLANG_WITH_PUSH("-Wold-style-cast") C4_SUPPRESS_WARNING_GCC("-Wtype-limits") C4_SUPPRESS_WARNING_GCC("-Wuseless-cast") // NOLINTBEGIN(modernize-avoid-c-style-cast) namespace c4 { namespace yml { csubstr serialize_to_arena_str(Tree * tree, csubstr scalar) { if(scalar.len > 0) { return serialize_to_arena_scalar(tree, scalar); } else { if(scalar.str == nullptr) { return csubstr{}; } else if(tree->m_arena.str == nullptr) { // Arena is empty and we want to store a non-null // zero-length string. // Even though the string has zero length, we need // some "memory" to store a non-nullptr string tree->_grow_arena(1); } return tree->_request_span(0); } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- NodeRef Tree::rootref() { return NodeRef(this, root_id()); } ConstNodeRef Tree::rootref() const { return ConstNodeRef(this, root_id()); } ConstNodeRef Tree::crootref() const { return ConstNodeRef(this, root_id()); } NodeRef Tree::ref(id_type id) { RYML_ASSERT_VISIT_CB_(m_callbacks, id != NONE && id >= 0 && id < m_cap, this, id); return NodeRef(this, id); } ConstNodeRef Tree::ref(id_type id) const { RYML_ASSERT_VISIT_CB_(m_callbacks, id != NONE && id >= 0 && id < m_cap, this, id); return ConstNodeRef(this, id); } ConstNodeRef Tree::cref(id_type id) const { RYML_ASSERT_VISIT_CB_(m_callbacks, id != NONE && id >= 0 && id < m_cap, this, id); return ConstNodeRef(this, id); } NodeRef Tree::operator[] (csubstr key) { return rootref()[key]; } ConstNodeRef Tree::operator[] (csubstr key) const { return crootref()[key]; } NodeRef Tree::operator[] (id_type i) { return rootref()[i]; } ConstNodeRef Tree::operator[] (id_type i) const { return crootref()[i]; } NodeRef Tree::docref(id_type i) { return ref(doc(i)); } ConstNodeRef Tree::docref(id_type i) const { return ConstNodeRef(this, doc(i)); } ConstNodeRef Tree::cdocref(id_type i) const { return ConstNodeRef(this, doc(i)); } //----------------------------------------------------------------------------- Tree::Tree(Callbacks const& cb) : Tree(RYML_DEFAULT_TREE_CAPACITY, RYML_DEFAULT_TREE_ARENA_CAPACITY, cb) { } Tree::Tree(id_type node_capacity, size_t arena_capacity, Callbacks const& cb) : m_buf(nullptr) , m_cap(0) , m_size(0) , m_free_head(NONE) , m_free_tail(NONE) , m_arena() , m_arena_pos(0) , m_callbacks(cb) , m_tag_directives() { if(node_capacity) reserve(node_capacity); if(arena_capacity) reserve_arena(arena_capacity); } Tree::~Tree() noexcept { _free(); } Tree::Tree(Tree const& that) : m_callbacks(that.m_callbacks) { _clear(); _copy(that); } Tree::Tree(Tree && that) noexcept : m_callbacks(that.m_callbacks) { _clear(); _move(that); } Tree& Tree::operator= (Tree const& that) { if(&that != this) { _free(); m_callbacks = that.m_callbacks; _copy(that); } return *this; } Tree& Tree::operator= (Tree && that) noexcept { if(&that != this) { _free(); m_callbacks = that.m_callbacks; _move(that); } return *this; } void Tree::_free() { if(m_buf) { RYML_ASSERT_VISIT_CB_(m_callbacks, m_cap > 0, this, NONE); RYML_CB_FREE_(m_callbacks, m_buf, NodeData, (size_t)m_cap); } if(m_arena.str) { RYML_ASSERT_VISIT_CB_(m_callbacks, m_arena.len > 0, this, NONE); RYML_CB_FREE_(m_callbacks, m_arena.str, char, m_arena.len); } _clear(); } C4_SUPPRESS_WARNING_GCC_PUSH #if defined(__GNUC__) && __GNUC__>= 8 C4_SUPPRESS_WARNING_GCC_WITH_PUSH("-Wclass-memaccess") // error: ‘void* memset(void*, int, size_t)’ clearing an object of type ‘class c4::yml::Tree’ with no trivial copy-assignment; use assignment or value-initialization instead #endif void Tree::_clear() { m_buf = nullptr; m_cap = 0; m_size = 0; m_free_head = 0; m_free_tail = 0; m_arena = {}; m_arena_pos = 0; m_tag_directives.clear(); } void Tree::_copy(Tree const& that) { RYML_ASSERT_VISIT_CB_(m_callbacks, m_buf == nullptr, this, NONE); RYML_ASSERT_VISIT_CB_(m_callbacks, m_arena.str == nullptr, this, NONE); RYML_ASSERT_VISIT_CB_(m_callbacks, m_arena.len == 0, this, NONE); if(that.m_cap) { m_buf = RYML_CB_ALLOC_HINT_(m_callbacks, NodeData, (size_t)that.m_cap, that.m_buf); memcpy(m_buf, that.m_buf, (size_t)that.m_cap * sizeof(NodeData)); } m_cap = that.m_cap; m_size = that.m_size; m_free_head = that.m_free_head; m_free_tail = that.m_free_tail; m_arena_pos = that.m_arena_pos; m_arena = that.m_arena; m_tag_directives = that.m_tag_directives; if(that.m_arena.str) { RYML_ASSERT_VISIT_CB_(m_callbacks, that.m_arena.len > 0, this, NONE); substr arena; arena.str = RYML_CB_ALLOC_HINT_(m_callbacks, char, that.m_arena.len, that.m_arena.str); arena.len = that.m_arena.len; _relocate(arena); // does a memcpy of the arena and updates nodes using the old arena m_arena = arena; } } void Tree::_move(Tree & that) noexcept { RYML_ASSERT_VISIT_CB_(m_callbacks, m_buf == nullptr, this, NONE); RYML_ASSERT_VISIT_CB_(m_callbacks, m_arena.str == nullptr, this, NONE); RYML_ASSERT_VISIT_CB_(m_callbacks, m_arena.len == 0, this, NONE); m_buf = that.m_buf; m_cap = that.m_cap; m_size = that.m_size; m_free_head = that.m_free_head; m_free_tail = that.m_free_tail; m_arena = that.m_arena; m_arena_pos = that.m_arena_pos; m_tag_directives = that.m_tag_directives; that._clear(); } void Tree::_relocate(substr next_arena) { RYML_ASSERT_VISIT_CB_(m_callbacks, next_arena.not_empty(), this, NONE); RYML_ASSERT_VISIT_CB_(m_callbacks, next_arena.len >= m_arena.len, this, NONE); if(m_arena_pos) { memcpy(next_arena.str, m_arena.str, m_arena_pos); } for(NodeData *C4_RESTRICT n = m_buf, *e = m_buf + m_cap; n != e; ++n) { if(in_arena(n->m_key.scalar)) n->m_key.scalar = _relocated(n->m_key.scalar, next_arena); if(in_arena(n->m_key.tag)) n->m_key.tag = _relocated(n->m_key.tag, next_arena); if(in_arena(n->m_key.anchor)) n->m_key.anchor = _relocated(n->m_key.anchor, next_arena); if(in_arena(n->m_val.scalar)) n->m_val.scalar = _relocated(n->m_val.scalar, next_arena); if(in_arena(n->m_val.tag)) n->m_val.tag = _relocated(n->m_val.tag, next_arena); if(in_arena(n->m_val.anchor)) n->m_val.anchor = _relocated(n->m_val.anchor, next_arena); } for(TagDirective &C4_RESTRICT td : m_tag_directives) { if(in_arena(td.prefix)) td.prefix = _relocated(td.prefix, next_arena); if(in_arena(td.handle)) td.handle = _relocated(td.handle, next_arena); } } //----------------------------------------------------------------------------- void Tree::reserve(id_type cap) { if(cap > m_cap) { NodeData *buf = RYML_CB_ALLOC_HINT_(m_callbacks, NodeData, (size_t)cap, m_buf); if(m_buf) { memcpy(buf, m_buf, (size_t)m_cap * sizeof(NodeData)); RYML_CB_FREE_(m_callbacks, m_buf, NodeData, (size_t)m_cap); } id_type first = m_cap, del = cap - m_cap; m_cap = cap; m_buf = buf; _clear_range(first, del); if(m_free_head != NONE) { RYML_ASSERT_VISIT_CB_(m_callbacks, m_buf != nullptr, this, NONE); RYML_ASSERT_VISIT_CB_(m_callbacks, m_free_tail != NONE, this, NONE); m_buf[m_free_tail].m_next_sibling = first; m_buf[first].m_prev_sibling = m_free_tail; m_free_tail = cap-1; } else { RYML_ASSERT_VISIT_CB_(m_callbacks, m_free_tail == NONE, this, NONE); m_free_head = first; m_free_tail = cap-1; } RYML_ASSERT_VISIT_CB_(m_callbacks, m_free_head == NONE || (m_free_head >= 0 && m_free_head < cap), this, NONE); RYML_ASSERT_VISIT_CB_(m_callbacks, m_free_tail == NONE || (m_free_tail >= 0 && m_free_tail < cap), this, NONE); if( ! m_size) _claim_root(); } } //----------------------------------------------------------------------------- void Tree::clear() { _clear_range(0, m_cap); m_size = 0; if(m_buf) { RYML_ASSERT_VISIT_CB_(m_callbacks, m_cap >= 0, this, NONE); m_free_head = 0; m_free_tail = m_cap-1; _claim_root(); } else { m_free_head = NONE; m_free_tail = NONE; } m_tag_directives.clear(); } void Tree::_claim_root() { id_type r = _claim(); RYML_ASSERT_VISIT_CB_(m_callbacks, r == 0, this, r); _set_hierarchy(r, NONE, NONE); } //----------------------------------------------------------------------------- void Tree::_clear_range(id_type first, id_type num) { if(num == 0) return; // prevent overflow when subtracting RYML_ASSERT_VISIT_CB_(m_callbacks, first >= 0 && first + num <= m_cap, this, first); memset(m_buf + first, 0, (size_t)num * sizeof(NodeData)); // TODO we should not need this for(id_type i = first, e = first + num; i < e; ++i) { _clear(i); NodeData *n = m_buf + i; n->m_prev_sibling = i - 1; n->m_next_sibling = i + 1; } m_buf[first + num - 1].m_next_sibling = NONE; } C4_SUPPRESS_WARNING_GCC_POP //----------------------------------------------------------------------------- void Tree::_release(id_type i) { RYML_ASSERT_VISIT_CB_(m_callbacks, i >= 0 && i < m_cap, this, i); _rem_hierarchy(i); _free_list_add(i); _clear(i); --m_size; } //----------------------------------------------------------------------------- // add to the front of the free list void Tree::_free_list_add(id_type i) { RYML_ASSERT_VISIT_CB_(m_callbacks, i >= 0 && i < m_cap, this, i); NodeData &C4_RESTRICT w = m_buf[i]; w.m_parent = NONE; w.m_next_sibling = m_free_head; w.m_prev_sibling = NONE; if(m_free_head != NONE) m_buf[m_free_head].m_prev_sibling = i; m_free_head = i; if(m_free_tail == NONE) m_free_tail = m_free_head; } void Tree::_free_list_rem(id_type i) { if(m_free_head == i) m_free_head = _p(i)->m_next_sibling; _rem_hierarchy(i); } //----------------------------------------------------------------------------- id_type Tree::_claim() { if(m_free_head == NONE || m_buf == nullptr) { id_type sz = 2 * m_cap; sz = sz ? sz : 16; reserve(sz); RYML_ASSERT_VISIT_CB_(m_callbacks, m_free_head != NONE, this, NONE); } RYML_ASSERT_VISIT_CB_(m_callbacks, m_size < m_cap, this, NONE); RYML_ASSERT_VISIT_CB_(m_callbacks, m_free_head >= 0 && m_free_head < m_cap, this, NONE); id_type ichild = m_free_head; NodeData *child = m_buf + ichild; ++m_size; m_free_head = child->m_next_sibling; if(m_free_head == NONE) { m_free_tail = NONE; RYML_ASSERT_VISIT_CB_(m_callbacks, m_size == m_cap, this, NONE); } _clear(ichild); return ichild; } //----------------------------------------------------------------------------- void Tree::_set_hierarchy(id_type ichild, id_type iparent, id_type iprev_sibling) { C4_SUPPRESS_WARNING_PUSH C4_SUPPRESS_WARNING_CLANG("-Wnull-dereference") #if defined(__GNUC__) #if (__GNUC__ >= 6) C4_SUPPRESS_WARNING_GCC("-Wnull-dereference") #endif #if (__GNUC__ > 9) C4_SUPPRESS_WARNING_GCC("-Wanalyzer-fd-leak") #endif #endif RYML_ASSERT_VISIT_CB_(m_callbacks, ichild >= 0 && ichild < m_cap, this, ichild); RYML_ASSERT_VISIT_CB_(m_callbacks, iparent == NONE || (iparent >= 0 && iparent < m_cap), this, iparent); RYML_ASSERT_VISIT_CB_(m_callbacks, iprev_sibling == NONE || (iprev_sibling >= 0 && iprev_sibling < m_cap), this, iprev_sibling); NodeData *C4_RESTRICT child = _p(ichild); child->m_parent = iparent; child->m_prev_sibling = NONE; child->m_next_sibling = NONE; if(iparent == NONE) { RYML_ASSERT_VISIT_CB_(m_callbacks, ichild == 0, this, ichild); RYML_ASSERT_VISIT_CB_(m_callbacks, iprev_sibling == NONE, this, iprev_sibling); } if(iparent == NONE) return; id_type inext_sibling = iprev_sibling != NONE ? next_sibling(iprev_sibling) : first_child(iparent); NodeData *C4_RESTRICT parent = get(iparent); NodeData *C4_RESTRICT psib = get(iprev_sibling); NodeData *C4_RESTRICT nsib = get(inext_sibling); if(psib) { RYML_ASSERT_VISIT_CB_(m_callbacks, next_sibling(iprev_sibling) == id(nsib), this, iprev_sibling); child->m_prev_sibling = id(psib); psib->m_next_sibling = id(child); RYML_ASSERT_VISIT_CB_(m_callbacks, psib->m_prev_sibling != psib->m_next_sibling || psib->m_prev_sibling == NONE, this, iprev_sibling); } if(nsib) { RYML_ASSERT_VISIT_CB_(m_callbacks, prev_sibling(inext_sibling) == id(psib), this, inext_sibling); child->m_next_sibling = id(nsib); nsib->m_prev_sibling = id(child); RYML_ASSERT_VISIT_CB_(m_callbacks, nsib->m_prev_sibling != nsib->m_next_sibling || nsib->m_prev_sibling == NONE, this, inext_sibling); } if(parent->m_first_child == NONE) { RYML_ASSERT_VISIT_CB_(m_callbacks, parent->m_last_child == NONE, this, parent->m_last_child); parent->m_first_child = id(child); parent->m_last_child = id(child); } else { if(child->m_next_sibling == parent->m_first_child) parent->m_first_child = id(child); if(child->m_prev_sibling == parent->m_last_child) parent->m_last_child = id(child); } C4_SUPPRESS_WARNING_POP } //----------------------------------------------------------------------------- void Tree::_rem_hierarchy(id_type i) { RYML_ASSERT_VISIT_CB_(m_callbacks, i >= 0 && i < m_cap, this, i); NodeData &C4_RESTRICT w = m_buf[i]; // remove from the parent if(w.m_parent != NONE) { NodeData &C4_RESTRICT p = m_buf[w.m_parent]; if(p.m_first_child == i) { p.m_first_child = w.m_next_sibling; } if(p.m_last_child == i) { p.m_last_child = w.m_prev_sibling; } } // remove from the used list if(w.m_prev_sibling != NONE) { NodeData *C4_RESTRICT prev = get(w.m_prev_sibling); prev->m_next_sibling = w.m_next_sibling; } if(w.m_next_sibling != NONE) { NodeData *C4_RESTRICT next = get(w.m_next_sibling); next->m_prev_sibling = w.m_prev_sibling; } } //----------------------------------------------------------------------------- /** @cond dev */ id_type Tree::_do_reorder(id_type *node, id_type count) { // swap this node if it's not in place if(*node != count) { _swap(*node, count); *node = count; } ++count; // bump the count from this node // now descend in the hierarchy for(id_type i = first_child(*node); i != NONE; i = next_sibling(i)) { // this child may have been relocated to a different index, // so get an updated version count = _do_reorder(&i, count); } return count; } /** @endcond */ void Tree::reorder() { id_type r = root_id(); _do_reorder(&r, 0); } //----------------------------------------------------------------------------- /** @cond dev */ void Tree::_swap(id_type n_, id_type m_) { RYML_ASSERT_VISIT_CB_(m_callbacks, (parent(n_) != NONE) || type(n_) == NOTYPE, this, n_); RYML_ASSERT_VISIT_CB_(m_callbacks, (parent(m_) != NONE) || type(m_) == NOTYPE, this, m_); NodeType tn = type(n_); NodeType tm = type(m_); if(tn != NOTYPE && tm != NOTYPE) { _swap_props(n_, m_); _swap_hierarchy(n_, m_); } else if(tn == NOTYPE && tm != NOTYPE) { _copy_props(n_, m_); _free_list_rem(n_); _copy_hierarchy(n_, m_); _clear(m_); _free_list_add(m_); } else if(tn != NOTYPE && tm == NOTYPE) { _copy_props(m_, n_); _free_list_rem(m_); _copy_hierarchy(m_, n_); _clear(n_); _free_list_add(n_); } else { C4_NEVER_REACH(); } } //----------------------------------------------------------------------------- void Tree::_swap_hierarchy(id_type ia, id_type ib) { if(ia == ib) return; for(id_type i = first_child(ia); i != NONE; i = next_sibling(i)) { if(i == ib || i == ia) continue; _p(i)->m_parent = ib; } for(id_type i = first_child(ib); i != NONE; i = next_sibling(i)) { if(i == ib || i == ia) continue; _p(i)->m_parent = ia; } auto & C4_RESTRICT a = *_p(ia); auto & C4_RESTRICT b = *_p(ib); auto & C4_RESTRICT pa = *_p(a.m_parent); auto & C4_RESTRICT pb = *_p(b.m_parent); if(&pa == &pb) { if((pa.m_first_child == ib && pa.m_last_child == ia) || (pa.m_first_child == ia && pa.m_last_child == ib)) { std::swap(pa.m_first_child, pa.m_last_child); } else { bool changed = false; if(pa.m_first_child == ia) { pa.m_first_child = ib; changed = true; } if(pa.m_last_child == ia) { pa.m_last_child = ib; changed = true; } if(pb.m_first_child == ib && !changed) { pb.m_first_child = ia; } if(pb.m_last_child == ib && !changed) { pb.m_last_child = ia; } } } else { if(pa.m_first_child == ia) pa.m_first_child = ib; if(pa.m_last_child == ia) pa.m_last_child = ib; if(pb.m_first_child == ib) pb.m_first_child = ia; if(pb.m_last_child == ib) pb.m_last_child = ia; } std::swap(a.m_first_child , b.m_first_child); std::swap(a.m_last_child , b.m_last_child); if(a.m_prev_sibling != ib && b.m_prev_sibling != ia && a.m_next_sibling != ib && b.m_next_sibling != ia) { if(a.m_prev_sibling != NONE && a.m_prev_sibling != ib) _p(a.m_prev_sibling)->m_next_sibling = ib; if(a.m_next_sibling != NONE && a.m_next_sibling != ib) _p(a.m_next_sibling)->m_prev_sibling = ib; if(b.m_prev_sibling != NONE && b.m_prev_sibling != ia) _p(b.m_prev_sibling)->m_next_sibling = ia; if(b.m_next_sibling != NONE && b.m_next_sibling != ia) _p(b.m_next_sibling)->m_prev_sibling = ia; std::swap(a.m_prev_sibling, b.m_prev_sibling); std::swap(a.m_next_sibling, b.m_next_sibling); } else { if(a.m_next_sibling == ib) // n will go after m { RYML_ASSERT_VISIT_CB_(m_callbacks, b.m_prev_sibling == ia, this, ia); if(a.m_prev_sibling != NONE) { RYML_ASSERT_VISIT_CB_(m_callbacks, a.m_prev_sibling != ib, this, ib); _p(a.m_prev_sibling)->m_next_sibling = ib; } if(b.m_next_sibling != NONE) { RYML_ASSERT_VISIT_CB_(m_callbacks, b.m_next_sibling != ia, this, ia); _p(b.m_next_sibling)->m_prev_sibling = ia; } id_type ns = b.m_next_sibling; b.m_prev_sibling = a.m_prev_sibling; b.m_next_sibling = ia; a.m_prev_sibling = ib; a.m_next_sibling = ns; } else if(a.m_prev_sibling == ib) // m will go after n { RYML_ASSERT_VISIT_CB_(m_callbacks, b.m_next_sibling == ia, this, ia); if(b.m_prev_sibling != NONE) { RYML_ASSERT_VISIT_CB_(m_callbacks, b.m_prev_sibling != ia, this, ia); _p(b.m_prev_sibling)->m_next_sibling = ia; } if(a.m_next_sibling != NONE) { RYML_ASSERT_VISIT_CB_(m_callbacks, a.m_next_sibling != ib, this, ib); _p(a.m_next_sibling)->m_prev_sibling = ib; } id_type ns = b.m_prev_sibling; a.m_prev_sibling = b.m_prev_sibling; a.m_next_sibling = ib; b.m_prev_sibling = ia; b.m_next_sibling = ns; } else { C4_NEVER_REACH(); } } RYML_ASSERT_VISIT_CB_(m_callbacks, a.m_next_sibling != ia, this, ia); RYML_ASSERT_VISIT_CB_(m_callbacks, a.m_prev_sibling != ia, this, ia); RYML_ASSERT_VISIT_CB_(m_callbacks, b.m_next_sibling != ib, this, ib); RYML_ASSERT_VISIT_CB_(m_callbacks, b.m_prev_sibling != ib, this, ib); if(a.m_parent != ib && b.m_parent != ia) { std::swap(a.m_parent, b.m_parent); } else { if(a.m_parent == ib && b.m_parent != ia) { a.m_parent = b.m_parent; b.m_parent = ia; } else if(a.m_parent != ib && b.m_parent == ia) { b.m_parent = a.m_parent; a.m_parent = ib; } else { C4_NEVER_REACH(); } } } //----------------------------------------------------------------------------- void Tree::_copy_hierarchy(id_type dst_, id_type src_) { auto const& C4_RESTRICT src = *_p(src_); auto & C4_RESTRICT dst = *_p(dst_); auto & C4_RESTRICT prt = *_p(src.m_parent); for(id_type i = src.m_first_child; i != NONE; i = next_sibling(i)) { _p(i)->m_parent = dst_; } if(src.m_prev_sibling != NONE) { _p(src.m_prev_sibling)->m_next_sibling = dst_; } if(src.m_next_sibling != NONE) { _p(src.m_next_sibling)->m_prev_sibling = dst_; } if(prt.m_first_child == src_) { prt.m_first_child = dst_; } if(prt.m_last_child == src_) { prt.m_last_child = dst_; } dst.m_parent = src.m_parent; dst.m_first_child = src.m_first_child; dst.m_last_child = src.m_last_child; dst.m_prev_sibling = src.m_prev_sibling; dst.m_next_sibling = src.m_next_sibling; } //----------------------------------------------------------------------------- void Tree::_swap_props(id_type n_, id_type m_) { NodeData &C4_RESTRICT n = *_p(n_); NodeData &C4_RESTRICT m = *_p(m_); std::swap(n.m_type, m.m_type); std::swap(n.m_key, m.m_key); std::swap(n.m_val, m.m_val); } /** @endcond */ //----------------------------------------------------------------------------- void Tree::move(id_type node, id_type after) { RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE, this, node); RYML_ASSERT_VISIT_CB_(m_callbacks, node != after, this, node); RYML_ASSERT_VISIT_CB_(m_callbacks, ! is_root(node), this, node); RYML_ASSERT_VISIT_CB_(m_callbacks, (after == NONE) || (has_sibling(node, after) && has_sibling(after, node)), this, node); _rem_hierarchy(node); _set_hierarchy(node, parent(node), after); } //----------------------------------------------------------------------------- void Tree::move(id_type node, id_type new_parent, id_type after) { RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE, this, node); RYML_ASSERT_VISIT_CB_(m_callbacks, node != after, this, node); RYML_ASSERT_VISIT_CB_(m_callbacks, new_parent != NONE, this, new_parent); RYML_ASSERT_VISIT_CB_(m_callbacks, new_parent != node, this, new_parent); RYML_ASSERT_VISIT_CB_(m_callbacks, new_parent != after, this, new_parent); RYML_ASSERT_VISIT_CB_(m_callbacks, ! is_root(node), this, node); _rem_hierarchy(node); _set_hierarchy(node, new_parent, after); } id_type Tree::move(Tree *src, id_type node, id_type new_parent, id_type after) { RYML_ASSERT_VISIT_CB_(m_callbacks, src != nullptr, this, new_parent); RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE, this, new_parent); RYML_ASSERT_VISIT_CB_(m_callbacks, new_parent != NONE, this, new_parent); RYML_ASSERT_VISIT_CB_(m_callbacks, new_parent != after, this, new_parent); id_type dup = duplicate(src, node, new_parent, after); src->remove(node); return dup; } void Tree::set_root_as_stream() { id_type root = root_id(); NodeType ty = type(root); if(ty.is_stream()) return; _c4dbgpf("set_root_as_stream. rootty={}", type(root).m_bits); bool empty_root = ((type(root) & (SEQ|MAP|VAL)) == 0); for(TagDirective &C4_RESTRICT td : m_tag_directives) { if(td.doc_id >= m_cap || _p(td.doc_id)->m_parent == NONE) { _c4dbgpf("tagd[{}]: id={}->NONE", &td-m_tag_directives.m_directives, td.doc_id); td.doc_id = NONE; } } // don't use _add_flags() because it's checked and will fail id_type next_doc; if(!has_children(root)) { if(ty.is_container()) { next_doc = append_child(root); _copy_props_wo_key(next_doc, root); _p(next_doc)->m_type.add(DOC); } else { _p(root)->m_type.add(SEQ); next_doc = append_child(root); _copy_props_wo_key(next_doc, root); _p(next_doc)->m_type.add(DOC); _p(next_doc)->m_type.rem(SEQ); } } else { RYML_ASSERT_VISIT_CB_(m_callbacks, !ty.has_key(), this, root); next_doc = append_child(root); _copy_props_wo_key(next_doc, root); _add_flags(next_doc, DOC); for(id_type prev = NONE, ch = first_child(root), next = next_sibling(ch); ch != NONE; ) { if(ch == next_doc) break; move(ch, next_doc, prev); prev = ch; ch = next; next = next_sibling(next); } } _p(root)->m_type = STREAM; for(TagDirective &C4_RESTRICT td : m_tag_directives) { id_type id = (td.doc_id != NONE) ? next_doc : (empty_root ? first_child(root) : m_free_head); _c4dbgpf("tagd[{}]: id={}->{}", &td-m_tag_directives.m_directives, td.doc_id, id); td.doc_id = id; } } //----------------------------------------------------------------------------- void Tree::remove_children(id_type node) { RYML_ASSERT_VISIT_CB_(m_callbacks, get(node) != nullptr, this, node); C4_SUPPRESS_WARNING_GCC_PUSH #if defined(__GNUC__) && __GNUC__ >= 6 C4_SUPPRESS_WARNING_GCC("-Wnull-dereference") #endif id_type ich = get(node)->m_first_child; while(ich != NONE) { remove_children(ich); RYML_ASSERT_VISIT_CB_(m_callbacks, get(ich) != nullptr, this, node); id_type next = get(ich)->m_next_sibling; _release(ich); if(ich == get(node)->m_last_child) break; ich = next; } C4_SUPPRESS_WARNING_GCC_POP } //----------------------------------------------------------------------------- bool Tree::change_type(id_type node, NodeType next) { NodeType curr = this->type(node); RYML_ASSERT_VISIT_CB_(m_callbacks, next.is_val() || next.is_map() || next.is_seq(), this, node); RYML_ASSERT_VISIT_CB_(m_callbacks, next.is_val() + next.is_map() + next.is_seq() == 1, this, node); RYML_ASSERT_VISIT_CB_(m_callbacks, next.has_key() == curr.has_key() || (curr.has_key() && !next.has_key()), this, node); NodeData *d = _p(node); if(next.is_map() && curr.is_map()) return false; else if(next.is_seq() && curr.is_seq()) return false; else if(next.is_val() && curr.is_val()) return false; d->m_type.m_bits = (d->m_type.m_bits & (~(MAP|SEQ|VAL|CONTAINER_STYLE|KEY_STYLE|VAL_STYLE))) | next; remove_children(node); return true; } //----------------------------------------------------------------------------- id_type Tree::duplicate(id_type node, id_type parent, id_type after) { return duplicate(this, node, parent, after); } id_type Tree::duplicate(Tree const* src, id_type node, id_type parent, id_type after) { RYML_ASSERT_VISIT_CB_(m_callbacks, src != nullptr, src, node); RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE, src, node); RYML_ASSERT_VISIT_CB_(m_callbacks, parent != NONE, this, parent); RYML_ASSERT_VISIT_CB_(m_callbacks, ! src->is_root(node), src, node); id_type copy = _claim(); _copy_props(copy, src, node); _set_hierarchy(copy, parent, after); duplicate_children(src, node, copy, NONE); return copy; } //----------------------------------------------------------------------------- id_type Tree::duplicate_children(id_type node, id_type parent, id_type after) { return duplicate_children(this, node, parent, after); } id_type Tree::duplicate_children(Tree const* src, id_type node, id_type parent, id_type after) { RYML_ASSERT_VISIT_CB_(m_callbacks, src != nullptr, src, node); RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE, src, node); RYML_ASSERT_VISIT_CB_(m_callbacks, parent != NONE, this, parent); RYML_ASSERT_VISIT_CB_(m_callbacks, after == NONE || has_child(parent, after), this, parent); id_type prev = after; for(id_type i = src->first_child(node); i != NONE; i = src->next_sibling(i)) { prev = duplicate(src, i, parent, prev); } return prev; } //----------------------------------------------------------------------------- void Tree::duplicate_contents(id_type node, id_type where) { duplicate_contents(this, node, where); } void Tree::duplicate_contents(Tree const *src, id_type node, id_type where) { RYML_ASSERT_VISIT_CB_(m_callbacks, src != nullptr, src, node); RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE, src, node); RYML_ASSERT_VISIT_CB_(m_callbacks, where != NONE, this, where); _copy_props_wo_key(where, src, node); duplicate_children(src, node, where, last_child(where)); } //----------------------------------------------------------------------------- id_type Tree::duplicate_children_no_rep(id_type node, id_type parent, id_type after) { return duplicate_children_no_rep(this, node, parent, after); } id_type Tree::duplicate_children_no_rep(Tree const *src, id_type node, id_type parent, id_type after) { RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE, src, node); RYML_ASSERT_VISIT_CB_(m_callbacks, parent != NONE, this, parent); RYML_ASSERT_VISIT_CB_(m_callbacks, after == NONE || has_child(parent, after), this, parent); // don't loop using pointers as there may be a relocation // find the position where "after" is id_type after_pos = NONE; if(after != NONE) { for(id_type i = first_child(parent), icount = 0; i != NONE; ++icount, i = next_sibling(i)) { if(i == after) { after_pos = icount; break; } } RYML_ASSERT_VISIT_CB_(m_callbacks, after_pos != NONE, this, node); } // for each child to be duplicated... id_type prev = after; NodeType pty = type(parent); for(id_type i = src->first_child(node); i != NONE; i = src->next_sibling(i)) { _c4dbgpf("duplicate_no_rep: {} -> {}/{}", i, parent, prev); RYML_CHECK_VISIT_CB_(m_callbacks, this != src || (parent != i && !is_ancestor(parent, i)), this, parent); if(pty.is_seq()) { _c4dbgpf("duplicate_no_rep: {} is seq", parent); prev = duplicate(src, i, parent, prev); } else { _c4dbgpf("duplicate_no_rep: {} is map", parent); RYML_ASSERT_VISIT_CB_(m_callbacks, pty.is_map(), this, parent); // does the parent already have a node with key equal to that of the current duplicate? id_type dstnode_dup = NONE, dstnode_dup_pos = NONE; { csubstr srckey = src->key(i); for(id_type j = first_child(parent), jcount = 0; j != NONE; ++jcount, j = next_sibling(j)) { if(key(j) == srckey) { _c4dbgpf("duplicate_no_rep: found matching key '{}' src={}/{} dst={}/{}", srckey, node, i, parent, j); dstnode_dup = j; dstnode_dup_pos = jcount; break; } } } _c4dbgpf("duplicate_no_rep: dstnode_dup={} dstnode_dup_pos={} after_pos={}", dstnode_dup, dstnode_dup_pos, after_pos); if(dstnode_dup == NONE) // there is no repetition; just duplicate { _c4dbgpf("duplicate_no_rep: no repetition, just duplicate i={} parent={} prev={}", i, parent, prev); prev = duplicate(src, i, parent, prev); } else // yes, there is a repetition { if(after_pos != NONE && dstnode_dup_pos <= after_pos) { // the dst duplicate is located before the node which will be inserted, // and will be overridden by the duplicate. So replace it. _c4dbgpf("duplicate_no_dstnode_dup: replace {}/{} with {}/{}", parent, dstnode_dup, node, i); if(prev == dstnode_dup) prev = prev_sibling(dstnode_dup); remove(dstnode_dup); prev = duplicate(src, i, parent, prev); } else if(prev == NONE) { _c4dbgpf("duplicate_no_dstnode_dup: {}=prev <- {}", prev, dstnode_dup); // first iteration with prev = after = NONE and dstnode_dupetition prev = dstnode_dup; } else if(dstnode_dup != prev) { // dstnode_dup is located after the node which will be inserted // and overrides it. So move the dstnode_dup into this node's place. _c4dbgpf("duplicate_no_dstnode_dup: move({}, {})", dstnode_dup, prev); move(dstnode_dup, prev); prev = dstnode_dup; } } // there's a dstnode_dupetition } } return prev; } //----------------------------------------------------------------------------- void Tree::merge_with(Tree const *src, id_type src_node, id_type dst_node) { RYML_ASSERT_VISIT_CB_(m_callbacks, src != nullptr, src, src_node); if(src_node == NONE) src_node = src->root_id(); if(dst_node == NONE) dst_node = root_id(); NodeType srcty = src->type(src_node); NodeType dstty = type(dst_node); RYML_ASSERT_VISIT_CB_(m_callbacks, srcty.has_val() || srcty.is_seq() || srcty.is_map(), src, src_node); if(srcty.has_val()) { type_bits mask_src = ~STYLE; // keep the existing style if it is already a val if( ! dstty.has_val()) { if(has_children(dst_node)) remove_children(dst_node); mask_src |= VAL_STYLE; // copy the src style } if(srcty.is_keyval()) { _copy_props(dst_node, src, src_node, mask_src); } else { RYML_ASSERT_VISIT_CB_(m_callbacks, srcty.is_val(), src, src_node); _copy_props_wo_key(dst_node, src, src_node, mask_src); } } else if(srcty.is_seq()) { if( ! dstty.is_seq()) { if(has_children(dst_node)) remove_children(dst_node); _clear_type(dst_node); if(src->has_key(src_node)) set_key(dst_node, src->key(src_node)); set_seq(dst_node); _p(dst_node)->m_type = src->_p(src_node)->m_type; } for(id_type sch = src->first_child(src_node); sch != NONE; sch = src->next_sibling(sch)) { id_type dch = append_child(dst_node); _copy_props_wo_key(dch, src, sch); merge_with(src, sch, dch); } } else { RYML_ASSERT_VISIT_CB_(m_callbacks, srcty.is_map(), src, src_node); if( ! dstty.is_map()) { if(has_children(dst_node)) remove_children(dst_node); _clear_type(dst_node); if(src->has_key(src_node)) set_key(dst_node, src->key(src_node)); set_map(dst_node); _p(dst_node)->m_type = src->_p(src_node)->m_type; } for(id_type sch = src->first_child(src_node); sch != NONE; sch = src->next_sibling(sch)) { id_type dch = find_child(dst_node, src->key(sch)); if(dch == NONE) { dch = append_child(dst_node); _copy_props(dch, src, sch); } merge_with(src, sch, dch); } } } //----------------------------------------------------------------------------- void Tree::resolve(bool clear_anchors) { if(m_size == 0) return; ReferenceResolver rr; resolve(&rr, clear_anchors); } void Tree::resolve(ReferenceResolver *C4_RESTRICT rr, bool clear_anchors) { if(m_size == 0) return; rr->resolve(this, clear_anchors); } //----------------------------------------------------------------------------- id_type Tree::num_children(id_type node) const { id_type count = 0; for(id_type i = first_child(node); i != NONE; i = next_sibling(i)) ++count; return count; } id_type Tree::child_pos(id_type node, id_type ch) const { RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE, this, node); id_type count = 0; for(id_type i = first_child(node); i != NONE; i = next_sibling(i)) { if(i == ch) return count; ++count; } return NONE; } id_type Tree::child(id_type node, id_type pos) const { RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE, this, node); id_type count = 0; for(id_type i = first_child(node); i != NONE; i = next_sibling(i)) { if(count++ == pos) return i; } return NONE; } id_type Tree::find_child(id_type node, csubstr const& name) const { C4_SUPPRESS_WARNING_PUSH #if defined(__clang__) #elif defined(__GNUC__) # if __GNUC__ >= 6 C4_SUPPRESS_WARNING_GCC("-Wnull-dereference") # endif # if __GNUC__ > 9 C4_SUPPRESS_WARNING_GCC("-Wanalyzer-null-dereference") # endif #endif RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE, this, node); RYML_ASSERT_VISIT_CB_(m_callbacks, _p(node)->m_type.m_bits & MAP, this, node); for(id_type i = first_child(node); i != NONE; i = next_sibling(i)) { if(_p(i)->m_key.scalar == name) return i; } return NONE; C4_SUPPRESS_WARNING_POP } namespace { id_type depth_desc_(Tree const& C4_RESTRICT t, id_type id, id_type currdepth=0, id_type maxdepth=0) { maxdepth = currdepth > maxdepth ? currdepth : maxdepth; for(id_type child = t.first_child(id); child != NONE; child = t.next_sibling(child)) { const id_type d = depth_desc_(t, child, currdepth+1, maxdepth); maxdepth = d > maxdepth ? d : maxdepth; } return maxdepth; } } id_type Tree::depth_desc(id_type node) const { RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE, this, node); return depth_desc_(*this, node); } id_type Tree::depth_asc(id_type node) const { RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE, this, node); id_type depth = 0; while(!is_root(node)) { ++depth; node = parent(node); } return depth; } bool Tree::is_ancestor(id_type node, id_type ancestor) const { RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE, this, node); id_type p = parent(node); while(p != NONE) { if(p == ancestor) return true; p = parent(p); } return false; } //----------------------------------------------------------------------------- /** @cond dev */ // LCOV_EXCL_START void Tree::to_val(id_type node, csubstr val, type_bits more_flags) { RYML_ASSERT_VISIT_CB_(m_callbacks, ! has_children(node), this, node); RYML_ASSERT_VISIT_CB_(m_callbacks, parent(node) == NONE || ! parent_is_map(node), this, node); RYML_ASSERT_VISIT_CB_(m_callbacks, !is_seq(node) && !is_map(node), this, node); NodeData* C4_RESTRICT nd = _p(node); nd->m_type = VAL|more_flags; nd->m_key.clear(); nd->m_val = val; } void Tree::to_keyval(id_type node, csubstr key, csubstr val, type_bits more_flags) { RYML_ASSERT_VISIT_CB_(m_callbacks, ! has_children(node), this, node); RYML_ASSERT_VISIT_CB_(m_callbacks, parent(node) == NONE || parent_is_map(node), this, node); RYML_ASSERT_VISIT_CB_(m_callbacks, !is_seq(node) && !is_map(node), this, node); NodeData* C4_RESTRICT nd = _p(node); nd->m_type = KEYVAL|more_flags; nd->m_key = key; nd->m_val = val; } void Tree::to_map(id_type node, type_bits more_flags) { RYML_ASSERT_VISIT_CB_(m_callbacks, ! has_children(node), this, node); NodeData* C4_RESTRICT nd = _p(node); nd->m_type = MAP|more_flags; nd->m_key.clear(); nd->m_val.clear(); } void Tree::to_map(id_type node, csubstr key, type_bits more_flags) { RYML_ASSERT_VISIT_CB_(m_callbacks, ! has_children(node), this, node); RYML_ASSERT_VISIT_CB_(m_callbacks, parent(node) == NONE || parent_is_map(node), this, node); NodeData* C4_RESTRICT nd = _p(node); nd->m_type = KEY|MAP|more_flags; nd->m_key = key; nd->m_val.clear(); } void Tree::to_seq(id_type node, type_bits more_flags) { RYML_ASSERT_VISIT_CB_(m_callbacks, ! has_children(node), this, node); RYML_ASSERT_VISIT_CB_(m_callbacks, parent(node) == NONE || parent_is_seq(node), this, node); NodeData* C4_RESTRICT nd = _p(node); nd->m_type = SEQ|more_flags; nd->m_key.clear(); nd->m_val.clear(); } void Tree::to_seq(id_type node, csubstr key, type_bits more_flags) { RYML_ASSERT_VISIT_CB_(m_callbacks, ! has_children(node), this, node); RYML_ASSERT_VISIT_CB_(m_callbacks, parent(node) == NONE || parent_is_map(node), this, node); NodeData* C4_RESTRICT nd = _p(node); nd->m_type = KEY|SEQ|more_flags; nd->m_key = key; nd->m_val.clear(); } void Tree::to_doc(id_type node, type_bits more_flags) { RYML_ASSERT_VISIT_CB_(m_callbacks, ! has_children(node), this, node); NodeData* C4_RESTRICT nd = _p(node); nd->m_type = DOC|more_flags; nd->m_key.clear(); nd->m_val.clear(); } void Tree::to_stream(id_type node, type_bits more_flags) { RYML_ASSERT_VISIT_CB_(m_callbacks, ! has_children(node), this, node); NodeData* C4_RESTRICT nd = _p(node); nd->m_type = STREAM|more_flags; nd->m_key.clear(); nd->m_val.clear(); } /** @endcond */ // LCOV_EXCL_STOP //----------------------------------------------------------------------------- void Tree::clear_style(id_type node, bool recurse) { NodeData *C4_RESTRICT d = _p(node); d->m_type.clear_style(); if(!recurse) return; for(id_type child = d->m_first_child; child != NONE; child = next_sibling(child)) clear_style(child, recurse); } void Tree::set_style_conditionally(id_type node, NodeType type_mask, NodeType rem_style_flags, NodeType add_style_flags, bool recurse) { NodeData *C4_RESTRICT d = _p(node); if((d->m_type & type_mask) == type_mask) { d->m_type &= ~(NodeType)rem_style_flags; d->m_type |= (NodeType)add_style_flags; } if(!recurse) return; for(id_type child = d->m_first_child; child != NONE; child = next_sibling(child)) set_style_conditionally(child, type_mask, rem_style_flags, add_style_flags, recurse); } //----------------------------------------------------------------------------- id_type Tree::num_tag_directives() const { return m_tag_directives.size(); } void Tree::clear_tag_directives() { m_tag_directives.clear(); } void Tree::add_tag_directive(csubstr handle, csubstr prefix, id_type id) { RYML_CHECK_BASIC_CB_(m_callbacks, !handle.empty() && !prefix.empty() && is_valid_tag_handle(handle) && m_tag_directives.add(handle, prefix, id)); } size_t Tree::resolve_tag(substr output, csubstr tag, id_type node_id) const { size_t reqsz = 0; m_tag_directives.resolve(output, &reqsz, tag, node_id, Location{}, callbacks()); return reqsz; } namespace { // return the extra size needed for the arena to accomodate the resolved tag size_t _transform_tag(Tree *t, id_type node_id, id_type doc_id, TagCache &cache, csubstr tag, csubstr *resolved) { _c4dbgpf("tag: doc={} node={} resolving tag ~~~{}~~~", doc_id, node_id, tag); (void)node_id; size_t reqsize = 0; if(tag.begins_with('<')) { *resolved = tag; } else { RYML_ASSERT_VISIT_CB_(t->callbacks(), !tag.begins_with("!<"), t, node_id); // this should have been handled elsewhere TagCache::LookupResult ret = cache.find(tag, doc_id); if(ret) { _c4dbgpf("tag: doc={} node={} resolving tag: found in cache[{}]: {}", doc_id, node_id, ret.pos, prs_(ret.resolved)); *resolved = ret.resolved; } else { _c4dbgpf("tag: doc={} node={} tag not in cache ~~~{}~~~", doc_id, node_id, tag); substr buf = t->m_arena.sub(t->m_arena_pos); reqsize = t->resolve_tag(buf, tag, doc_id); if(!reqsize) { *resolved = tag; } else if(reqsize <= buf.len) { t->m_arena_pos += reqsize; *resolved = buf.first(reqsize); cache.add(tag, *resolved, doc_id, ret.pos); reqsize = 0; } else { _c4dbgpf("tag: doc={} node={} extra size needed: {}", doc_id, node_id, reqsize); } _c4dbgpf("tag: doc={} node={} resolved tag: ~~~{}~~~", doc_id, node_id, *resolved); } } return reqsize; } size_t _resolve_tags(Tree *t, id_type node, id_type doc_id, TagCache &cache, bool all=true) { NodeData *C4_RESTRICT d = t->_p(node); size_t extra_size = 0; if((d->m_type & KEYTAG) && (all || is_custom_tag(d->m_key.tag))) extra_size += _transform_tag(t, node, doc_id, cache, d->m_key.tag, &d->m_key.tag); if((d->m_type & VALTAG) && (all || is_custom_tag(d->m_val.tag))) extra_size += _transform_tag(t, node, doc_id, cache, d->m_val.tag, &d->m_val.tag); for(id_type child = t->first_child(node); child != NONE; child = t->next_sibling(child)) extra_size += _resolve_tags(t, child, doc_id, cache); return extra_size; } size_t _resolve_tags(Tree *t, TagCache &cache, bool all) { id_type r = t->root_id(); size_t extra_size = 0; if(!t->is_stream(r)) extra_size += _resolve_tags(t, r, r, cache, all); else for(id_type doc_id = t->first_child(r); doc_id != NONE; doc_id = t->next_sibling(doc_id)) extra_size += _resolve_tags(t, doc_id, doc_id, cache, all); return extra_size; } void _normalize_tags(Tree *t, id_type node) { NodeData *C4_RESTRICT d = t->_p(node); if(d->m_type & KEYTAG) d->m_key.tag = normalize_tag(d->m_key.tag); if(d->m_type & VALTAG) d->m_val.tag = normalize_tag(d->m_val.tag); for(id_type child = t->first_child(node); child != NONE; child = t->next_sibling(child)) _normalize_tags(t, child); } void _normalize_tags_long(Tree *t, id_type node) { NodeData *C4_RESTRICT d = t->_p(node); if(d->m_type & KEYTAG) d->m_key.tag = normalize_tag_long(d->m_key.tag); if(d->m_type & VALTAG) d->m_val.tag = normalize_tag_long(d->m_val.tag); for(id_type child = t->first_child(node); child != NONE; child = t->next_sibling(child)) _normalize_tags_long(t, child); } } // namespace void Tree::resolve_tags(TagCache &cache, bool all) { if(empty()) return; // try to resolve. While doing so, get the extra size needed for // the arena, if the arena is currently too small. size_t extra_size = _resolve_tags(this, cache, all); // if the arena requires extra size, grow it and then resolve the // missing entries if(extra_size) { _c4dbgpf("tag: extrasize={} -- retry! {}->{}", extra_size, m_arena.len, m_arena.len + extra_size); _grow_arena(extra_size); extra_size = _resolve_tags(this, cache, all); RYML_ASSERT_BASIC_CB_(callbacks(), extra_size == 0); } } void Tree::normalize_tags() { if(empty()) return; _normalize_tags(this, root_id()); } void Tree::normalize_tags_long() { if(empty()) return; _normalize_tags_long(this, root_id()); } //----------------------------------------------------------------------------- csubstr Tree::lookup_result::resolved() const { csubstr p = path.first(path_pos); if(p.ends_with('.')) p = p.first(p.len-1); return p; } csubstr Tree::lookup_result::unresolved() const { return path.sub(path_pos); } void Tree::_advance(lookup_result *r, size_t more) { r->path_pos += more; if(r->path.sub(r->path_pos).begins_with('.')) ++r->path_pos; } Tree::lookup_result Tree::lookup_path(csubstr path, id_type start) const { if(start == NONE) start = root_id(); lookup_result r(path, start); if(path.empty()) return r; _lookup_path(&r); if(r.target == NONE && r.closest == start) r.closest = NONE; return r; } id_type Tree::lookup_path_or_modify(csubstr default_value, csubstr path, id_type start) { id_type target = _lookup_path_or_create(path, start); set_val(target, default_value); return target; } id_type Tree::lookup_path_or_modify(Tree const *src, id_type src_node, csubstr path, id_type start) { id_type target = _lookup_path_or_create(path, start); merge_with(src, src_node, target); return target; } id_type Tree::_lookup_path_or_create(csubstr path, id_type start) { if(start == NONE) start = root_id(); lookup_result r(path, start); _lookup_path(&r); if(r.target != NONE) { C4_ASSERT(r.unresolved().empty()); return r.target; } _lookup_path_modify(&r); return r.target; } void Tree::_lookup_path(lookup_result *r) const { C4_ASSERT( ! r->unresolved().empty()); _lookup_path_token parent{"", type(r->closest)}; id_type node; do { node = _next_node(r, &parent); if(node != NONE) r->closest = node; if(r->unresolved().empty()) { r->target = node; return; } } while(node != NONE); } void Tree::_lookup_path_modify(lookup_result *r) { C4_ASSERT( ! r->unresolved().empty()); _lookup_path_token parent{"", type(r->closest)}; id_type node; do { node = _next_node_modify(r, &parent); if(node != NONE) r->closest = node; if(r->unresolved().empty()) { r->target = node; return; } } while(node != NONE); } id_type Tree::_next_node(lookup_result * r, _lookup_path_token *parent) const { _lookup_path_token token = _next_token(r, *parent); if( ! token) return NONE; id_type node = NONE; csubstr prev = token.value; if(token.type == MAP || token.type == SEQ) { RYML_ASSERT_VISIT_CB_(m_callbacks, !token.value.begins_with('['), this, r->closest); //RYML_ASSERT_VISIT_CB_(m_callbacks, is_container(r->closest) || r->closest == NONE); RYML_ASSERT_VISIT_CB_(m_callbacks, is_map(r->closest), this, r->closest); node = find_child(r->closest, token.value); } else if(token.type == KEYVAL) { RYML_ASSERT_VISIT_CB_(m_callbacks, r->unresolved().empty(), this, r->closest); if(is_map(r->closest)) node = find_child(r->closest, token.value); } else if(token.type == KEY) { RYML_ASSERT_VISIT_CB_(m_callbacks, token.value.begins_with('[') && token.value.ends_with(']'), this, r->closest); token.value = token.value.offs(1, 1).trim(' '); id_type idx = 0; RYML_CHECK_BASIC_CB_(m_callbacks, from_chars(token.value, &idx)); node = child(r->closest, idx); } else { C4_NEVER_REACH(); } if(node != NONE) { *parent = token; } else { csubstr p = r->path.sub(r->path_pos > 0 ? r->path_pos - 1 : r->path_pos); r->path_pos -= prev.len; if(p.begins_with('.')) r->path_pos -= 1u; } return node; } id_type Tree::_next_node_modify(lookup_result * r, _lookup_path_token *parent) { _lookup_path_token token = _next_token(r, *parent); if( ! token) return NONE; id_type node = NONE; NodeType ty = type(r->closest); if(token.type == MAP || token.type == SEQ) { RYML_ASSERT_VISIT_CB_(m_callbacks, !token.value.begins_with('['), this, r->closest); //RYML_ASSERT_VISIT_CB_(m_callbacks, is_container(r->closest) || r->closest == NONE); if( ! ty.is_container()) { set_map(r->closest); } else { if(ty.is_map()) { node = find_child(r->closest, token.value); } else { id_type pos = NONE; RYML_CHECK_BASIC_CB_(m_callbacks, c4::atox(token.value, &pos)); RYML_ASSERT_VISIT_CB_(m_callbacks, pos != NONE, this, r->closest); node = child(r->closest, pos); } } if(node == NONE) { RYML_ASSERT_VISIT_CB_(m_callbacks, is_map(r->closest), this, r->closest); node = append_child(r->closest); NodeData *n = _p(node); n->m_key.scalar = token.value; n->m_type.add(KEY); } } else if(token.type == KEYVAL) { RYML_ASSERT_VISIT_CB_(m_callbacks, r->unresolved().empty(), this, r->closest); if(ty.is_map()) { node = find_child(r->closest, token.value); if(node == NONE) node = append_child(r->closest); } else { RYML_ASSERT_VISIT_CB_(m_callbacks, !ty.is_seq(), this, r->closest); _add_flags(r->closest, MAP); node = append_child(r->closest); } NodeData *n = _p(node); n->m_key.scalar = token.value; n->m_val.scalar = ""; n->m_type.add(KEYVAL); } else if(token.type == KEY) { RYML_ASSERT_VISIT_CB_(m_callbacks, token.value.begins_with('[') && token.value.ends_with(']'), this, r->closest); token.value = token.value.offs(1, 1).trim(' '); id_type idx; if( ! from_chars(token.value, &idx)) { return NONE; } if( ! is_container(r->closest)) { set_seq(r->closest); } RYML_ASSERT_VISIT_CB_(m_callbacks, is_container(r->closest), this, r->closest); node = child(r->closest, idx); if(node == NONE) { RYML_ASSERT_VISIT_CB_(m_callbacks, num_children(r->closest) <= idx, this, r->closest); for(id_type i = num_children(r->closest); i <= idx; ++i) { node = append_child(r->closest); if(i < idx) { if(is_map(r->closest)) { _clear_type(node); set_key(node, {}); set_val(node, {}); } else { RYML_ASSERT_VISIT_CB_(m_callbacks, is_seq(r->closest), this, r->closest); _clear_type(node); set_val(node, {}); } } } } } else { C4_NEVER_REACH(); } RYML_ASSERT_VISIT_CB_(m_callbacks, node != NONE, this, r->closest); *parent = token; return node; } /* types of tokens: * - seeing "map." ---> "map"/MAP * - finishing "scalar" ---> "scalar"/KEYVAL * - seeing "seq[n]" ---> "seq"/SEQ (--> "[n]"/KEY) * - seeing "[n]" ---> "[n]"/KEY */ Tree::_lookup_path_token Tree::_next_token(lookup_result *r, _lookup_path_token const& parent) const { csubstr unres = r->unresolved(); if(unres.empty()) return {}; // LCOV_EXCL_LINE // is it an indexation like [0], [1], etc? if(unres.begins_with('[')) { size_t pos = unres.find(']'); if(pos == csubstr::npos) return {}; // LCOV_EXCL_LINE csubstr idx = unres.first(pos + 1); _advance(r, pos + 1); return {idx, KEY}; } // no. so it must be a name size_t pos = unres.first_of(".["); if(pos == csubstr::npos) { _advance(r, unres.len); NodeType t; if(( ! parent) || parent.type.is_seq()) return {unres, VAL}; return {unres, KEYVAL}; } // it's either a map or a seq RYML_ASSERT_VISIT_CB_(m_callbacks, unres[pos] == '.' || unres[pos] == '[', this, r->closest); if(unres[pos] == '.') { RYML_ASSERT_VISIT_CB_(m_callbacks, pos != 0, this, r->closest); _advance(r, pos + 1); return {unres.first(pos), MAP}; } RYML_ASSERT_VISIT_CB_(m_callbacks, unres[pos] == '[', this, r->closest); _advance(r, pos); return {unres.first(pos), SEQ}; } } // namespace yml } // namespace c4 //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- #ifndef C4_YML_EVENT_HANDLER_TREE_HPP_ //#include "c4/yml/event_handler_tree.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/event_handler_tree.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_PARSE_ENGINE_DEF_HPP_ //#include "c4/yml/parse_engine.def.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/parse_engine.def.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_PARSE_HPP_ //#include "c4/yml/parse.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/parse.hpp must have been amalgamated before this point" #endif namespace c4 { namespace yml { Location Tree::location(Parser const& parser, id_type node) const { // try hard to avoid getting the location from a null string. Location loc; if(_location_from_node(parser, node, &loc, 0)) return loc; return parser.val_location(parser.source().str); } bool Tree::_location_from_node(Parser const& parser, id_type node, Location *C4_RESTRICT loc, id_type level) const { NodeType ty = type(node); if(ty.has_key()) { csubstr k = key(node); if C4_LIKELY(k.str != nullptr) { RYML_ASSERT_BASIC_CB_(m_callbacks, k.is_sub(parser.source())); RYML_ASSERT_BASIC_CB_(m_callbacks, parser.source().is_super(k)); *loc = parser.val_location(k.str); return true; } } if(ty.has_val()) { csubstr v = val(node); if C4_LIKELY(v.str != nullptr) { RYML_ASSERT_BASIC_CB_(m_callbacks, v.is_sub(parser.source())); RYML_ASSERT_BASIC_CB_(m_callbacks, parser.source().is_super(v)); *loc = parser.val_location(v.str); return true; } } if(ty.is_container()) { if(_location_from_cont(parser, node, loc)) return true; } if(type(node) != NOTYPE && level == 0) { // try the prev sibling { const id_type prev = prev_sibling(node); if(prev != NONE) { if(_location_from_node(parser, prev, loc, level+1)) return true; } } // try the next sibling { const id_type next = next_sibling(node); if(next != NONE) { if(_location_from_node(parser, next, loc, level+1)) return true; } } // try the parent { const id_type parent = this->parent(node); if(parent != NONE) { if(_location_from_node(parser, parent, loc, level+1)) return true; } } } return false; } bool Tree::_location_from_cont(Parser const& parser, id_type node, Location *C4_RESTRICT loc) const { RYML_ASSERT_BASIC_CB_(m_callbacks, type(node).is_container()); if(!type(node).is_stream()) { const char *node_start = _p(node)->m_val.scalar.str; // this was stored in the container if(has_children(node)) { id_type child = first_child(node); if(type(child).has_key()) { // when a map starts, the container was set after the key csubstr k = key(child); if(k.str && node_start > k.str) node_start = k.str; } } *loc = parser.val_location(node_start); return true; } else // it's a stream { *loc = parser.val_location(parser.source().str); // just return the front of the buffer } return true; } } // namespace yml } // namespace c4 // NOLINTEND(modernize-avoid-c-style-cast) C4_SUPPRESS_WARNING_GCC_CLANG_POP C4_SUPPRESS_WARNING_MSVC_POP #endif /* RYML_SINGLE_HDR_DEFINE_NOW */ // (end src/c4/yml/tree.cpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/reference_resolver.cpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifdef RYML_SINGLE_HDR_DEFINE_NOW #ifndef C4_YML_REFERENCE_RESOLVER_HPP_ //#include "c4/yml/reference_resolver.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/reference_resolver.hpp must have been amalgamated before this point" #endif /* C4_YML_REFERENCE_RESOLVER_HPP_ */ #ifndef C4_YML_COMMON_HPP_ //#include "c4/yml/common.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/common.hpp must have been amalgamated before this point" #endif /* C4_YML_COMMON_HPP_ */ #ifndef C4_YML_DETAIL_DBGPRINT_HPP_ //#include "c4/yml/detail/dbgprint.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/detail/dbgprint.hpp must have been amalgamated before this point" #endif /* C4_YML_DETAIL_DBGPRINT_HPP_ */ #ifdef RYML_DBG #ifndef C4_YML_DETAIL_PRINT_HPP_ //#include "c4/yml/detail/print.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/detail/print.hpp must have been amalgamated before this point" #endif /* C4_YML_DETAIL_PRINT_HPP_ */ #else #define _c4dbg_tree(...) #define _c4dbg_node(...) #endif namespace c4 { namespace yml { /** @cond dev */ id_type ReferenceResolver::count_anchors_and_refs_(id_type n) { id_type c = 0; NodeType ty = m_tree->type(n); c += ty.has_key_anchor(); c += ty.has_val_anchor(); c += ty.is_key_ref(); c += ty.is_val_ref(); c += ty.has_key() && m_tree->key(n) == "<<"; for(id_type ch = m_tree->first_child(n); ch != NONE; ch = m_tree->next_sibling(ch)) c += count_anchors_and_refs_(ch); return c; } void ReferenceResolver::gather_anchors_and_refs_(id_type n) { NodeType ty = m_tree->type(n); // insert key refs BEFORE inserting val refs if(ty.has_key()) { if(!ty.is_key_quoted() && m_tree->key(n) == "<<") { _c4dbgpf("node[{}]: key is <<", n); if(ty.has_val()) { if(ty.is_val_ref()) { _c4dbgpf("node[{}]: instance[{}]: val ref, inheriting! '{}'", n, m_refs.size(), m_tree->val_ref(n)); m_refs.push({VALREF, n, NONE, NONE, NONE, NONE}); //m_refs.push({KEYREF, n, NONE, NONE, NONE, NONE}); } else { _c4dbgpf("node[{}]: not ref!", n); } } else if(ty.is_seq()) { // for merging multiple inheritance targets // <<: [ *CENTER, *BIG ] _c4dbgpf("node[{}]: is seq!", n); for(id_type ich = m_tree->first_child(n); ich != NONE; ich = m_tree->next_sibling(ich)) { _c4dbgpf("node[{}]: instance [{}]: val ref, inheriting multiple: {} '{}'", n, m_refs.size(), ich, m_tree->val_ref(ich)); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, !m_tree->is_container(ich), m_tree, ich); m_refs.push({VALREF, ich, NONE, NONE, n, m_tree->next_sibling(n)}); } return; // don't descend into the seq } else { RYML_ERR_VISIT_CB_(m_tree->m_callbacks, m_tree, n, "refs for << must be either val or seq"); } } else if(ty.is_key_ref()) { _c4dbgpf("node[{}]: instance[{}]: key ref: '{}', key='{}'", n, m_refs.size(), m_tree->key_ref(n), m_tree->has_key(n) ? m_tree->key(n) : csubstr{"-"}); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, m_tree->key(n) != "<<", m_tree, n); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, m_tree->key(n).ends_with(m_tree->key_ref(n)), m_tree, n); m_refs.push({KEYREF, n, NONE, NONE, NONE, NONE}); } } // val ref if(ty.is_val_ref() && (!ty.has_key() || m_tree->key(n) != "<<")) { _c4dbgpf("node[{}]: instance[{}]: val ref: '{}'", n, m_refs.size(), m_tree->val_ref(n)); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, (!ty.has_val()) || m_tree->val(n).ends_with(m_tree->val_ref(n)), m_tree, n); m_refs.push({VALREF, n, NONE, NONE, NONE, NONE}); } // anchors if(ty.has_key_anchor()) { _c4dbgpf("node[{}]: instance[{}]: key anchor: '{}'", n, m_refs.size(), m_tree->key_anchor(n)); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, ty.has_key(), m_tree, n); m_refs.push({KEYANCH, n, NONE, NONE, NONE, NONE}); } if(ty.has_val_anchor()) { _c4dbgpf("node[{}]: instance[{}]: val anchor: '{}'", n, m_refs.size(), m_tree->val_anchor(n)); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, ty.has_val() || ty.is_container(), m_tree, n); m_refs.push({VALANCH, n, NONE, NONE, NONE, NONE}); } // recurse for(id_type ch = m_tree->first_child(n); ch != NONE; ch = m_tree->next_sibling(ch)) gather_anchors_and_refs_(ch); } void ReferenceResolver::gather_anchors_and_refs_() { _c4dbgp("gathering anchors and refs..."); // minimize (re-)allocations by counting first id_type num_anchors_and_refs = count_anchors_and_refs_(m_tree->root_id()); if(!num_anchors_and_refs) return; m_refs.reserve(num_anchors_and_refs); m_refs.clear(); // now descend through the hierarchy gather_anchors_and_refs_(m_tree->root_id()); _c4dbgpf("found {} anchors/refs", m_refs.size()); // finally connect the reference list id_type prev_anchor = NONE; id_type count = 0; for(auto &rd : m_refs) { rd.prev_anchor = prev_anchor; if(rd.type.has_anchor()) prev_anchor = count; ++count; } _c4dbgp("gathering anchors and refs: finished"); } id_type ReferenceResolver::lookup_(RefData const* C4_RESTRICT ra) { #ifdef RYML_DBG id_type instance = static_cast(ra-m_refs.m_stack); id_type node = ra->node; #endif RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, ra->type.is_key_ref() || ra->type.is_val_ref(), m_tree, ra->node); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, ra->type.is_key_ref() != ra->type.is_val_ref(), m_tree, ra->node); csubstr refname; _c4dbgpf("instance[{}:node{}]: lookup from node={}...", instance, node, ra->node); if(ra->type.is_val_ref()) { refname = m_tree->val_ref(ra->node); _c4dbgpf("instance[{}:node{}]: valref: '{}'", instance, node, refname); } else { RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, ra->type.is_key_ref(), m_tree, ra->node); refname = m_tree->key_ref(ra->node); _c4dbgpf("instance[{}:node{}]: keyref: '{}'", instance, node, refname); } while(ra->prev_anchor != NONE) { ra = &m_refs[ra->prev_anchor]; _c4dbgpf("instance[{}:node{}]: lookup '{}' at [{}:node{}]: keyref='{}' valref='{}'", instance, node, refname, ra-m_refs.m_stack, ra->node, (m_tree->has_key_anchor(ra->node) ? m_tree->key_anchor(ra->node) : csubstr("~")), (m_tree->has_val_anchor(ra->node) ? m_tree->val_anchor(ra->node) : csubstr("~"))); if(m_tree->has_anchor(ra->node, refname)) { _c4dbgpf("instance[{}:node{}]: got it at [{}:node{}]!", instance, node, ra-m_refs.m_stack, ra->node); return ra->node; } } RYML_ERR_VISIT_CB_(m_tree->m_callbacks, m_tree, ra->node, "anchor not found: '{}'", refname); C4_UNREACHABLE_AFTER_ERR(); } void ReferenceResolver::reset_(Tree *t_) { if(t_->callbacks() != m_refs.m_callbacks) { m_refs.m_callbacks = t_->callbacks(); } m_tree = t_; m_refs.clear(); } void ReferenceResolver::resolve_() { /* from the specs: "an alias node refers to the most recent * node in the serialization having the specified anchor". So * we need to start looking upward from ref nodes. * * @see http://yaml.org/spec/1.2/spec.html#id2765878 */ _c4dbgp("matching anchors/refs..."); for(id_type i = 0, e = m_refs.size(); i < e; ++i) { RefData &C4_RESTRICT refdata = m_refs.top(i); if( ! refdata.type.is_ref()) continue; refdata.target = lookup_(&refdata); } _c4dbgp("matching anchors/refs: finished"); // insert the resolved references _c4dbgp("modifying tree..."); id_type prev_parent_ref = NONE; id_type prev_parent_ref_after = NONE; for(id_type i = 0, e = m_refs.size(); i < e; ++i) { RefData const& C4_RESTRICT refdata = m_refs[i]; _c4dbgpf("instance[{}:node{}]: {}/{}...", i, refdata.node, i+1, e); if( ! refdata.type.is_ref()) continue; _c4dbgpf("instance[{}:node{}]: is reference!", i, refdata.node); NodeType nty = m_tree->type(refdata.node); if(refdata.parent_ref != NONE) { _c4dbgpf("instance[{}:node{}] has parent: {}", i, refdata.node, refdata.parent_ref); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, m_tree->is_seq(refdata.parent_ref), m_tree, refdata.node); const id_type p = m_tree->parent(refdata.parent_ref); const id_type after = (prev_parent_ref != refdata.parent_ref) ? refdata.parent_ref//prev_sibling(rd.parent_ref_sibling) : prev_parent_ref_after; prev_parent_ref = refdata.parent_ref; prev_parent_ref_after = m_tree->duplicate_children_no_rep(refdata.target, p, after); m_tree->remove(refdata.node); } else { _c4dbgpf("instance[{}:node{}] has no parent", i, refdata.node, refdata.parent_ref); if(nty.has_key() && m_tree->key(refdata.node) == "<<") { _c4dbgpf("instance[{}:node{}] is inheriting", i, refdata.node); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, nty.is_keyval(), m_tree, refdata.node); const id_type p = m_tree->parent(refdata.node); const id_type after = m_tree->prev_sibling(refdata.node); _c4dbgpf("instance[{}:node{}] p={} after={}", i, refdata.node, p, after); m_tree->duplicate_children_no_rep(refdata.target, p, after); m_tree->remove(refdata.node); } else if(refdata.type.is_key_ref()) { _c4dbgpf("instance[{}:node{}] is key ref", i, refdata.node); NodeType tty = m_tree->type(refdata.target); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, nty.is_key_ref(), m_tree, refdata.node); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, tty.has_key_anchor() || tty.has_val_anchor(), m_tree, refdata.node); if(tty.has_val_anchor() && m_tree->val_anchor(refdata.target) == m_tree->key_ref(refdata.node)) { _c4dbgpf("instance[{}:node{}] target.anchor==val.anchor=={}", i, refdata.node, m_tree->val_anchor(refdata.target)); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, !m_tree->is_container(refdata.target), m_tree, refdata.target); RYML_CHECK_VISIT_CB_(m_tree->m_callbacks, m_tree->has_val(refdata.target), m_tree, refdata.target); const type_bits existing_style_flags = VAL_STYLE & m_tree->_p(refdata.target)->m_type.m_bits; static_assert((VAL_STYLE >> 1u) == (KEY_STYLE), "bad flags"); m_tree->_p(refdata.node)->m_key.scalar = m_tree->val(refdata.target); m_tree->_add_flags(refdata.node, KEY | (existing_style_flags >> 1u)); } else { _c4dbgpf("instance[{}:node{}] don't inherit container flags", i, refdata.node); RYML_CHECK_BASIC_CB_(m_tree->m_callbacks, m_tree->key_anchor(refdata.target) == m_tree->key_ref(refdata.node)); m_tree->_p(refdata.node)->m_key.scalar = m_tree->key(refdata.target); // keys cannot be containers, so don't inherit container flags const type_bits existing_style_flags = KEY_STYLE & m_tree->_p(refdata.target)->m_type.m_bits; m_tree->_add_flags(refdata.node, KEY | existing_style_flags); } } else // val ref { _c4dbgpf("instance[{}:node{}] is val ref", i, refdata.node); NodeType tty = m_tree->type(refdata.target); RYML_ASSERT_VISIT_CB_(m_tree->m_callbacks, refdata.type.is_val_ref(), m_tree, refdata.node); if(tty.has_key_anchor() && m_tree->key_anchor(refdata.target) == m_tree->val_ref(refdata.node)) { _c4dbgpf("instance[{}:node{}] target.anchor==key.anchor=={}", i, refdata.node, m_tree->key_anchor(refdata.target)); RYML_CHECK_BASIC_CB_(m_tree->m_callbacks, !tty.is_container()); RYML_CHECK_BASIC_CB_(m_tree->m_callbacks, tty.has_val()); // keys cannot be containers, so don't inherit container flags const type_bits existing_style_flags = (KEY_STYLE) & m_tree->_p(refdata.target)->m_type.m_bits; static_assert((KEY_STYLE << 1u) == (VAL_STYLE), "bad flags"); m_tree->_p(refdata.node)->m_val.scalar = m_tree->key(refdata.target); m_tree->_add_flags(refdata.node, VAL | (existing_style_flags << 1u)); } else { _c4dbgpf("instance[{}:node{}] duplicate contents", i, refdata.node); m_tree->duplicate_contents(refdata.target, refdata.node); } } } _c4dbg_tree("after insertion", *m_tree); } } void ReferenceResolver::resolve(Tree *t_, bool clear_anchors) { _c4dbgp("resolving references..."); reset_(t_); _c4dbg_tree("unresolved tree", *m_tree); gather_anchors_and_refs_(); if(m_refs.empty()) return; resolve_(); _c4dbg_tree("resolved tree", *m_tree); // clear anchors and refs if(clear_anchors) { _c4dbgp("clearing anchors/refs"); auto clear_ = [this]{ for(auto const& C4_RESTRICT ar : m_refs) { m_tree->rem_anchor_ref(ar.node); if(ar.parent_ref != NONE) if(m_tree->type(ar.parent_ref) != NOTYPE) m_tree->remove(ar.parent_ref); } }; clear_(); // some of the elements injected during the resolution may // have nested anchors; these anchors will have been newly // injected during the resolution; collect again, and clear // again, to ensure those are also cleared: gather_anchors_and_refs_(); clear_(); _c4dbgp("clearing anchors/refs: finished"); } _c4dbg_tree("final resolved tree", *m_tree); m_tree = nullptr; _c4dbgp("resolving references: finished"); } /** @endcond */ } // namespace ryml } // namespace c4 #endif /* RYML_SINGLE_HDR_DEFINE_NOW */ // (end src/c4/yml/reference_resolver.cpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/parse.cpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifdef RYML_SINGLE_HDR_DEFINE_NOW #ifndef C4_YML_PARSE_HPP_ //#include "c4/yml/parse.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/parse.hpp must have been amalgamated before this point" #endif /* C4_YML_PARSE_HPP_ */ #ifndef C4_YML_NODE_HPP_ //#include "c4/yml/node.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/node.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_PARSE_ENGINE_HPP_ //#include "c4/yml/parse_engine.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/parse_engine.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_PARSE_ENGINE_DEF_HPP_ //#include "c4/yml/parse_engine.def.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/parse_engine.def.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_EVENT_HANDLER_TREE_HPP_ //#include "c4/yml/event_handler_tree.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/event_handler_tree.hpp must have been amalgamated before this point" #endif //----------------------------------------------------------------------------- namespace c4 { namespace yml { // instantiate the parser class template class RYML_EXPORT ParseEngine; namespace { // so many things can go wrong... void check_(Tree *tree) { if C4_UNLIKELY(!tree) RYML_ERR_BASIC_("null tree"); if C4_UNLIKELY(tree->empty()) tree->reserve(); } void check_(NodeRef &node) { check_(node.tree()); if C4_UNLIKELY(node.id() == NONE) RYML_ERR_VISIT_CB_(node.tree()->m_callbacks, node.tree(), node.id(), "invalid node"); node.create(); } void check_(Parser *parser) { if C4_UNLIKELY(!parser) RYML_ERR_BASIC_("null parser"); if C4_UNLIKELY(!parser->m_evt_handler) // the parser callbacks are from the handler. do not use parser->callbacks() RYML_ERR_BASIC_("null handler"); } void check_(Parser *parser, Tree *tree) { if C4_UNLIKELY(!parser && !tree) { RYML_ERR_BASIC_("null parser and tree"); } else if C4_UNLIKELY(!parser) { RYML_ERR_BASIC_CB_(tree->callbacks(), "null parser"); } else if C4_UNLIKELY(!tree) { if C4_UNLIKELY(!parser->m_evt_handler) RYML_ERR_BASIC_("null tree and handler"); else RYML_ERR_BASIC_CB_(parser->callbacks(), "null tree"); } if C4_UNLIKELY(!parser->m_evt_handler) { RYML_ERR_BASIC_("null handler"); } if C4_UNLIKELY(tree->empty()) { tree->reserve(); } } void check_(Parser *parser, NodeRef &node) { check_(parser, node.tree()); check_(node); } void checksrc_(Tree *tree, csubstr src) { if C4_UNLIKELY(src.len && !src.str) RYML_ERR_BASIC_CB_(tree->callbacks(), "null source buffer"); } substr cpsrc_(Tree *tree, csubstr src) { checksrc_(tree, src); return tree->copy_to_arena(src); } // helpers: check and copy to arena substr checkcp_(Tree *tree, csubstr src) { check_(tree); return cpsrc_(tree, src); } substr checkcp_(NodeRef &node, csubstr src) { check_(node); return cpsrc_(node.tree(), src); } substr checkcp_(Parser *parser, Tree *tree, csubstr src) { check_(parser, tree); return cpsrc_(tree, src); } substr checkcp_(Parser *parser, NodeRef &node, csubstr src) { check_(parser, node); return cpsrc_(node.tree(), src); } using Handler = Parser::handler_type; struct TmpParser { Handler handler; Parser parser; // assumes checks above were done prior to instantiation TmpParser(ParserOptions const& opts={}) : handler(get_callbacks()) , parser(&handler, opts) { } TmpParser(Tree* tree, ParserOptions const& opts={}) : handler(tree->callbacks()) , parser(&handler, opts) { } TmpParser(NodeRef &node, ParserOptions const& opts={}) : handler(node.tree()->callbacks()) , parser(&handler, opts) { } }; // assumes checks above were done prior to calling C4_ALWAYS_INLINE void reset_handler_(Parser *parser, Tree *tree, id_type node_id) { RYML_ASSERT_BASIC_(parser); // LCOV_EXCL_LINE lcov weirdly fails here RYML_ASSERT_BASIC_(parser->m_evt_handler); RYML_ASSERT_BASIC_(tree); if C4_UNLIKELY(node_id == NONE || node_id >= tree->capacity()) RYML_ERR_VISIT_CB_(tree->m_callbacks, tree, node_id, "invalid node"); parser->m_evt_handler->reset(tree, node_id); RYML_ASSERT_BASIC_(parser->m_evt_handler->m_tree == tree); } // assumes checks above were done prior to calling void parse_yaml_(Parser *parser, csubstr filename, substr yaml, Tree *tree, id_type node_id) { reset_handler_(parser, tree, node_id); checksrc_(tree, yaml); parser->parse_in_place_ev(filename, yaml); } // assumes checks above were done prior to calling void parse_json_(Parser *parser, csubstr filename, substr json, Tree *tree, id_type node_id) { reset_handler_(parser, tree, node_id); checksrc_(tree, json); parser->parse_json_in_place_ev(filename, json); } } // namespace // this is vertically aligned to highlight the parameter differences. void parse_in_place(Parser *parser, csubstr filename, substr yaml, Tree *tree, id_type node_id) { check_(parser, tree); parse_yaml_(parser, filename, yaml, tree, node_id); } void parse_in_place(Parser *parser, substr yaml, Tree *tree, id_type node_id) { check_(parser, tree); parse_yaml_(parser, {} , yaml, tree, node_id); } void parse_in_place(Parser *parser, csubstr filename, substr yaml, Tree *tree ) { check_(parser, tree); parse_yaml_(parser, filename, yaml, tree, tree->root_id()); } void parse_in_place(Parser *parser, substr yaml, Tree *tree ) { check_(parser, tree); parse_yaml_(parser, {} , yaml, tree, tree->root_id()); } void parse_in_place(Parser *parser, csubstr filename, substr yaml, NodeRef node ) { check_(parser, node); parse_yaml_(parser, filename, yaml, node.tree(), node.id()); } void parse_in_place(Parser *parser, substr yaml, NodeRef node ) { check_(parser, node); parse_yaml_(parser, {} , yaml, node.tree(), node.id()); } Tree parse_in_place(Parser *parser, csubstr filename, substr yaml ) { check_(parser); Tree tree(parser->callbacks()); parse_yaml_(parser, filename, yaml, &tree, tree.root_id()); return tree; } Tree parse_in_place(Parser *parser, substr yaml ) { check_(parser); Tree tree(parser->callbacks()); parse_yaml_(parser, {} , yaml, &tree, tree.root_id()); return tree; } // this is vertically aligned to highlight the parameter differences. void parse_in_place(csubstr filename, substr yaml, Tree *tree, id_type node_id, ParserOptions const& opts) { check_(tree); TmpParser tmp(tree, opts); parse_yaml_(&tmp.parser, filename, yaml, tree, node_id); } void parse_in_place( substr yaml, Tree *tree, id_type node_id, ParserOptions const& opts) { check_(tree); TmpParser tmp(tree, opts); parse_yaml_(&tmp.parser, {} , yaml, tree, node_id); } void parse_in_place(csubstr filename, substr yaml, Tree *tree , ParserOptions const& opts) { check_(tree); TmpParser tmp(tree, opts); parse_yaml_(&tmp.parser, filename, yaml, tree, tree->root_id()); } void parse_in_place( substr yaml, Tree *tree , ParserOptions const& opts) { check_(tree); TmpParser tmp(tree, opts); parse_yaml_(&tmp.parser, {} , yaml, tree, tree->root_id()); } void parse_in_place(csubstr filename, substr yaml, NodeRef node , ParserOptions const& opts) { check_(node); TmpParser tmp(node, opts); parse_yaml_(&tmp.parser, filename, yaml, node.tree(), node.id()); } void parse_in_place( substr yaml, NodeRef node , ParserOptions const& opts) { check_(node); TmpParser tmp(node, opts); parse_yaml_(&tmp.parser, {} , yaml, node.tree(), node.id()); } Tree parse_in_place(csubstr filename, substr yaml , ParserOptions const& opts) { TmpParser tmp(opts); Tree tree; parse_yaml_(&tmp.parser, filename, yaml, &tree, tree.root_id()); return tree; } Tree parse_in_place( substr yaml , ParserOptions const& opts) { TmpParser tmp(opts); Tree tree; parse_yaml_(&tmp.parser, {} , yaml, &tree, tree.root_id()); return tree; } // this is vertically aligned to highlight the parameter differences. void parse_json_in_place(Parser *parser, csubstr filename, substr json, Tree *tree, id_type node_id) { check_(parser, tree); parse_json_(parser, filename, json, tree, node_id); } void parse_json_in_place(Parser *parser, substr json, Tree *tree, id_type node_id) { check_(parser, tree); parse_json_(parser, {} , json, tree, node_id); } void parse_json_in_place(Parser *parser, csubstr filename, substr json, Tree *tree ) { check_(parser, tree); parse_json_(parser, filename, json, tree, tree->root_id()); } void parse_json_in_place(Parser *parser, substr json, Tree *tree ) { check_(parser, tree); parse_json_(parser, {} , json, tree, tree->root_id()); } void parse_json_in_place(Parser *parser, csubstr filename, substr json, NodeRef node ) { check_(parser, node); parse_json_(parser, filename, json, node.tree(), node.id()); } void parse_json_in_place(Parser *parser, substr json, NodeRef node ) { check_(parser, node); parse_json_(parser, {} , json, node.tree(), node.id()); } Tree parse_json_in_place(Parser *parser, csubstr filename, substr json ) { check_(parser); Tree tree(parser->callbacks()); parse_json_(parser, filename, json, &tree, tree.root_id()); return tree; } Tree parse_json_in_place(Parser *parser, substr json ) { check_(parser); Tree tree(parser->callbacks()); parse_json_(parser, {} , json, &tree, tree.root_id()); return tree; } // this is vertically aligned to highlight the parameter differences. void parse_json_in_place(csubstr filename, substr json, Tree *tree, id_type node_id, ParserOptions const& opts) { check_(tree); TmpParser tmp(tree, opts); parse_json_(&tmp.parser, filename, json, tree, node_id); } void parse_json_in_place( substr json, Tree *tree, id_type node_id, ParserOptions const& opts) { check_(tree); TmpParser tmp(tree, opts); parse_json_(&tmp.parser, {} , json, tree, node_id); } void parse_json_in_place(csubstr filename, substr json, Tree *tree , ParserOptions const& opts) { check_(tree); TmpParser tmp(tree, opts); parse_json_(&tmp.parser, filename, json, tree, tree->root_id()); } void parse_json_in_place( substr json, Tree *tree , ParserOptions const& opts) { check_(tree); TmpParser tmp(tree, opts); parse_json_(&tmp.parser, {} , json, tree, tree->root_id()); } void parse_json_in_place(csubstr filename, substr json, NodeRef node , ParserOptions const& opts) { check_(node); TmpParser tmp(node, opts); parse_json_(&tmp.parser, filename, json, node.tree(), node.id()); } void parse_json_in_place( substr json, NodeRef node , ParserOptions const& opts) { check_(node); TmpParser tmp(node, opts); parse_json_(&tmp.parser, {} , json, node.tree(), node.id()); } Tree parse_json_in_place(csubstr filename, substr json , ParserOptions const& opts) { TmpParser tmp(opts); Tree tree; parse_json_(&tmp.parser, filename, json, &tree, tree.root_id()); return tree; } Tree parse_json_in_place( substr json , ParserOptions const& opts) { TmpParser tmp(opts); Tree tree; parse_json_(&tmp.parser, {} , json, &tree, tree.root_id()); return tree; } // this is vertically aligned to highlight the parameter differences. void parse_in_arena(Parser *parser, csubstr filename, csubstr yaml, Tree *tree, id_type node_id) { substr src = checkcp_(parser, tree, yaml); parse_yaml_(parser, filename, src, tree, node_id); } void parse_in_arena(Parser *parser, csubstr yaml, Tree *tree, id_type node_id) { substr src = checkcp_(parser, tree, yaml); parse_yaml_(parser, {} , src, tree, node_id); } void parse_in_arena(Parser *parser, csubstr filename, csubstr yaml, Tree *tree ) { substr src = checkcp_(parser, tree, yaml); parse_yaml_(parser, filename, src, tree, tree->root_id()); } void parse_in_arena(Parser *parser, csubstr yaml, Tree *tree ) { substr src = checkcp_(parser, tree, yaml); parse_yaml_(parser, {} , src, tree, tree->root_id()); } void parse_in_arena(Parser *parser, csubstr filename, csubstr yaml, NodeRef node ) { substr src = checkcp_(parser, node, yaml); parse_yaml_(parser, filename, src, node.tree(), node.id()); } void parse_in_arena(Parser *parser, csubstr yaml, NodeRef node ) { substr src = checkcp_(parser, node, yaml); parse_yaml_(parser, {} , src, node.tree(), node.id()); } Tree parse_in_arena(Parser *parser, csubstr filename, csubstr yaml ) { check_(parser); Tree tree(parser->callbacks()); substr src = cpsrc_(&tree, yaml); parse_yaml_(parser, filename, src, &tree, tree.root_id()); return tree; } Tree parse_in_arena(Parser *parser, csubstr yaml ) { check_(parser); Tree tree(parser->callbacks()); substr src = cpsrc_(&tree, yaml); parse_yaml_(parser, {} , src, &tree, tree.root_id()); return tree; } // this is vertically aligned to highlight the parameter differences. void parse_in_arena(csubstr filename, csubstr yaml, Tree *tree, id_type node_id, ParserOptions const& opts) { substr src = checkcp_(tree, yaml); TmpParser tmp(tree, opts); parse_yaml_(&tmp.parser, filename, src, tree, node_id); } void parse_in_arena( csubstr yaml, Tree *tree, id_type node_id, ParserOptions const& opts) { substr src = checkcp_(tree, yaml); TmpParser tmp(tree, opts); parse_yaml_(&tmp.parser, {} , src, tree, node_id); } void parse_in_arena(csubstr filename, csubstr yaml, Tree *tree , ParserOptions const& opts) { substr src = checkcp_(tree, yaml); TmpParser tmp(tree, opts); parse_yaml_(&tmp.parser, filename, src, tree, tree->root_id()); } void parse_in_arena( csubstr yaml, Tree *tree , ParserOptions const& opts) { substr src = checkcp_(tree, yaml); TmpParser tmp(tree, opts); parse_yaml_(&tmp.parser, {} , src, tree, tree->root_id()); } void parse_in_arena(csubstr filename, csubstr yaml, NodeRef node , ParserOptions const& opts) { substr src = checkcp_(node, yaml); TmpParser tmp(node, opts); parse_yaml_(&tmp.parser, filename, src, node.tree(), node.id()); } void parse_in_arena( csubstr yaml, NodeRef node , ParserOptions const& opts) { substr src = checkcp_(node, yaml); TmpParser tmp(node, opts); parse_yaml_(&tmp.parser, {} , src, node.tree(), node.id()); } Tree parse_in_arena(csubstr filename, csubstr yaml , ParserOptions const& opts) { TmpParser tmp(opts); Tree tree; substr src = cpsrc_(&tree, yaml); parse_yaml_(&tmp.parser, filename, src, &tree, tree.root_id()); return tree; } Tree parse_in_arena( csubstr yaml , ParserOptions const& opts) { TmpParser tmp(opts); Tree tree; substr src = cpsrc_(&tree, yaml); parse_yaml_(&tmp.parser, {} , src, &tree, tree.root_id()); return tree; } // this is vertically aligned to highlight the parameter differences. void parse_json_in_arena(Parser *parser, csubstr filename, csubstr json, Tree *tree, id_type node_id) { substr src = checkcp_(parser, tree, json); parse_json_(parser, filename, src, tree, node_id); } void parse_json_in_arena(Parser *parser, csubstr json, Tree *tree, id_type node_id) { substr src = checkcp_(parser, tree, json); parse_json_(parser, {} , src, tree, node_id); } void parse_json_in_arena(Parser *parser, csubstr filename, csubstr json, Tree *tree ) { substr src = checkcp_(parser, tree, json); parse_json_(parser, filename, src, tree, tree->root_id()); } void parse_json_in_arena(Parser *parser, csubstr json, Tree *tree ) { substr src = checkcp_(parser, tree, json); parse_json_(parser, {} , src, tree, tree->root_id()); } void parse_json_in_arena(Parser *parser, csubstr filename, csubstr json, NodeRef node ) { substr src = checkcp_(parser, node, json); parse_json_(parser, filename, src, node.tree(), node.id()); } void parse_json_in_arena(Parser *parser, csubstr json, NodeRef node ) { substr src = checkcp_(parser, node, json); parse_json_(parser, {} , src, node.tree(), node.id()); } Tree parse_json_in_arena(Parser *parser, csubstr filename, csubstr json ) { check_(parser); Tree tree(parser->callbacks()); substr src = cpsrc_(&tree, json); parse_json_(parser, filename, src, &tree, tree.root_id()); return tree; } Tree parse_json_in_arena(Parser *parser, csubstr json ) { check_(parser); Tree tree(parser->callbacks()); substr src = cpsrc_(&tree, json); parse_json_(parser, {} , src, &tree, tree.root_id()); return tree; } // this is vertically aligned to highlight the parameter differences. void parse_json_in_arena(csubstr filename, csubstr json, Tree *tree, id_type node_id, ParserOptions const& opts) { substr src = checkcp_(tree, json); TmpParser tmp(tree, opts); parse_json_(&tmp.parser, filename, src, tree, node_id); } void parse_json_in_arena( csubstr json, Tree *tree, id_type node_id, ParserOptions const& opts) { substr src = checkcp_(tree, json); TmpParser tmp(tree, opts); parse_json_(&tmp.parser, {} , src, tree, node_id); } void parse_json_in_arena(csubstr filename, csubstr json, Tree *tree , ParserOptions const& opts) { substr src = checkcp_(tree, json); TmpParser tmp(tree, opts); parse_json_(&tmp.parser, filename, src, tree, tree->root_id()); } void parse_json_in_arena( csubstr json, Tree *tree , ParserOptions const& opts) { substr src = checkcp_(tree, json); TmpParser tmp(tree, opts); parse_json_(&tmp.parser, {} , src, tree, tree->root_id()); } void parse_json_in_arena(csubstr filename, csubstr json, NodeRef node , ParserOptions const& opts) { substr src = checkcp_(node, json); TmpParser tmp(node, opts); parse_json_(&tmp.parser, filename, src, node.tree(), node.id()); } void parse_json_in_arena( csubstr json, NodeRef node , ParserOptions const& opts) { substr src = checkcp_(node, json); TmpParser tmp(node, opts); parse_json_(&tmp.parser, {} , src, node.tree(), node.id()); } Tree parse_json_in_arena(csubstr filename, csubstr json , ParserOptions const& opts) { TmpParser tmp(opts); Tree tree; substr src = cpsrc_(&tree, json); parse_json_(&tmp.parser, filename, src, &tree, tree.root_id()); return tree; } Tree parse_json_in_arena( csubstr json , ParserOptions const& opts) { TmpParser tmp(opts); Tree tree; substr src = cpsrc_(&tree, json); parse_json_(&tmp.parser, {} , src, &tree, tree.root_id()); return tree; } //----------------------------------------------------------------------------- RYML_EXPORT id_type estimate_tree_capacity(csubstr src) { id_type num_nodes = 1; // root for(size_t i = 0; i < src.len; ++i) { const char c = src.str[i]; num_nodes += (c == '\n') || (c == ',') || (c == '[') || (c == '{'); } return num_nodes; } } // namespace yml } // namespace c4 #endif /* RYML_SINGLE_HDR_DEFINE_NOW */ // (end src/c4/yml/parse.cpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/scalar_style.cpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifdef RYML_SINGLE_HDR_DEFINE_NOW #ifndef C4_YML_SCALAR_STYLE_HPP_ //#include "c4/yml/scalar_style.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/scalar_style.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_SCALAR_CHARCONV_HPP_ //#include "c4/yml/scalar_charconv.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/scalar_charconv.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_ERROR_HPP_ //#include "c4/yml/error.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/error.hpp must have been amalgamated before this point" #endif namespace c4 { namespace yml { bool scalar_style_query_squo(csubstr scalar) noexcept { // see https://www.yaml.info/learn/quote.html#noplain // cannot have leading whitespace after a newline for(size_t i = 0; i < scalar.len; ++i) { if(scalar.str[i] == '\n' && i + 1 < scalar.len) { char next = scalar.str[i + 1]; if(next == ' ' || next == '\t') return false; } } return true; } namespace { bool is_wsnl_(char c) noexcept { return c == ' ' || c == '\n' || c == '\t' || c == '\r'; } bool is_valid_bulk_(csubstr s, size_t i) { C4_ASSERT(i >= 1 && i+1 < s.len); C4_ASSERT(s.str[i] == ':' || s.str[i] == '#'); switch(s.str[i]) { case ':': return !is_wsnl_(s.str[i+1]); case '#': return !is_wsnl_(s.str[i-1]); } C4_UNREACHABLE(); // LCOV_EXCL_LINE } } // namespace bool scalar_style_query_plain_flow(csubstr scalar) noexcept { // see https://www.yaml.info/learn/quote.html#noplain if(!scalar.len) return !scalar.str; // first switch(scalar.str[0]) { case ' ': case '\n': case '\t': case '\r': case '!': case '&': case '*': case ',': case '"': case '\'': case '|': case '>': case '{': case '}': case '[': case ']': case '#': case '`': case '%': case '@': return false; case '-': case ':': case '?': if(scalar.len == 1 || (scalar.str[1] == ' ' || scalar.str[1] == '\t')) return false; break; } // bulk for(size_t i = 1; i + 1 < scalar.len; ++i) { switch(scalar.str[i]) { case ',': case '{': case '}': case '[': case ']': return false; case ':': case '#': if(!is_valid_bulk_(scalar, i)) return false; break; } } // last if(scalar.len > 1) { switch(scalar.back()) { case ' ': case '\n': case '\t': case '\r': case ',': case '{': case '}': case '[': case ']': case '#': case ':': return false; } } return true; } bool scalar_style_query_plain_block(csubstr scalar) noexcept { // see https://www.yaml.info/learn/quote.html#noplain if(!scalar.len) return !scalar.str; // first switch(scalar.str[0]) { case ' ': case '\n': case '\t': case '\r': case '!': case '&': case '*': case ',': case '"': case '\'': case '|': case '>': case '{': case '}': case '[': case ']': case '#': case '`': case '%': case '@': return false; case '-': case ':': case '?': if (scalar.len == 1 || (scalar.str[1] == ' ' || scalar.str[1] == '\t')) return false; break; } // bulk for(size_t i = 1; i + 1 < scalar.len; ++i) { switch(scalar.str[i]) { case ':': case '#': if(!is_valid_bulk_(scalar, i)) return false; break; } } // last if(scalar.len > 1) { switch(scalar.back()) { case ' ': case '\n': case '\t': case '\r': case '#': case ':': return false; } } return true; } NodeType scalar_style_choose_block(csubstr scalar) noexcept { if(scalar.len) { if(scalar_style_query_plain_block(scalar)) return SCALAR_PLAIN; RYML_ASSERT_BASIC_(scalar_style_query_squo(scalar) && "if this assertion fires, please submit an issue!"); return SCALAR_SQUO; } return scalar.str ? SCALAR_SQUO : SCALAR_PLAIN; } NodeType scalar_style_choose_json(csubstr scalar) noexcept { // do not quote numbers or special scalars return scalar_is_plain_number_json(scalar) || scalar_is_special_json(scalar) ? SCALAR_PLAIN : SCALAR_DQUO; } } // namespace yml } // namespace c4 #endif /* RYML_SINGLE_HDR_DEFINE_NOW */ // (end src/c4/yml/scalar_style.cpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/emit_buf.cpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifdef RYML_SINGLE_HDR_DEFINE_NOW #ifndef C4_YML_EMIT_BUF_HPP_ //#include "c4/yml/emit_buf.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/emit_buf.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_WRITER_BUF_HPP_ //#include "c4/yml/writer_buf.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/writer_buf.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_TREE_HPP_ //#include "c4/yml/tree.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/tree.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_NODE_HPP_ //#include "c4/yml/node.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/node.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_EMITTER_DEF_HPP_ //#include "c4/yml/emitter.def.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/emitter.def.hpp must have been amalgamated before this point" #endif namespace c4 { namespace yml { // instantiate the template class template class RYML_EXPORT Emitter; // emit from root ------------------------- substr emit_yaml(Tree const& t, EmitOptions const& opts, substr buf, bool error_on_excess) { EmitterBuf em(opts, buf); em.emit_as(EMIT_YAML, &t); return em.get_result(error_on_excess); } substr emit_yaml(Tree const& t, substr buf, bool error_on_excess) { EmitterBuf em(EmitOptions{}, buf); em.emit_as(EMIT_YAML, &t); return em.get_result(error_on_excess); } substr emit_json(Tree const& t, EmitOptions const& opts, substr buf, bool error_on_excess) { EmitterBuf em(opts, buf); em.emit_as(EMIT_JSON, &t); return em.get_result(error_on_excess); } substr emit_json(Tree const& t, substr buf, bool error_on_excess) { EmitterBuf em(EmitOptions{}, buf); em.emit_as(EMIT_JSON, &t); return em.get_result(error_on_excess); } // emit from tree and node id ----------------------- substr emit_yaml(Tree const& t, id_type id, EmitOptions const& opts, substr buf, bool error_on_excess) { EmitterBuf em(opts, buf); em.emit_as(EMIT_YAML, &t, id); return em.get_result(error_on_excess); } substr emit_yaml(Tree const& t, id_type id, substr buf, bool error_on_excess) { EmitterBuf em(EmitOptions{}, buf); em.emit_as(EMIT_YAML, &t, id); return em.get_result(error_on_excess); } substr emit_json(Tree const& t, id_type id, EmitOptions const& opts, substr buf, bool error_on_excess) { EmitterBuf em(opts, buf); em.emit_as(EMIT_JSON, &t, id); return em.get_result(error_on_excess); } substr emit_json(Tree const& t, id_type id, substr buf, bool error_on_excess) { EmitterBuf em(EmitOptions{}, buf); em.emit_as(EMIT_JSON, &t, id); return em.get_result(error_on_excess); } // emit from ConstNodeRef ------------------------ substr emit_yaml(ConstNodeRef const& r, EmitOptions const& opts, substr buf, bool error_on_excess) { EmitterBuf em(opts, buf); em.emit_as(EMIT_YAML, r.tree(), r.id()); return em.get_result(error_on_excess); } substr emit_yaml(ConstNodeRef const& r, substr buf, bool error_on_excess) { EmitterBuf em(EmitOptions{}, buf); em.emit_as(EMIT_YAML, r.tree(), r.id()); return em.get_result(error_on_excess); } substr emit_json(ConstNodeRef const& r, EmitOptions const& opts, substr buf, bool error_on_excess) { EmitterBuf em(opts, buf); em.emit_as(EMIT_JSON, r.tree(), r.id()); return em.get_result(error_on_excess); } substr emit_json(ConstNodeRef const& r, substr buf, bool error_on_excess) { EmitterBuf em(EmitOptions{}, buf); em.emit_as(EMIT_JSON, r.tree(), r.id()); return em.get_result(error_on_excess); } } // namespace yml } // namespace c4 #endif /* RYML_SINGLE_HDR_DEFINE_NOW */ // (end src/c4/yml/emit_buf.cpp) //******************************************************************************** //-------------------------------------------------------------------------------- // src/c4/yml/emit_file.cpp //-------------------------------------------------------------------------------- //******************************************************************************** #ifdef RYML_SINGLE_HDR_DEFINE_NOW #ifndef C4_YML_EMIT_FILE_HPP_ //#include "c4/yml/emit_file.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/emit_file.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_WRITER_FILE_HPP_ //#include "c4/yml/writer_file.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/writer_file.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_TREE_HPP_ //#include "c4/yml/tree.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/tree.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_NODE_HPP_ //#include "c4/yml/node.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/node.hpp must have been amalgamated before this point" #endif #ifndef C4_YML_EMITTER_DEF_HPP_ //#include "c4/yml/emitter.def.hpp" // amalgamate: remove include #error "amalgamate: c4/yml/emitter.def.hpp must have been amalgamated before this point" #endif namespace c4 { namespace yml { // instantiate the template class template class RYML_EXPORT Emitter; // emit from root ------------------------- void emit_yaml(Tree const& t, EmitOptions const& opts, FILE *f) { EmitterFile em(opts, f); em.emit_as(EMIT_YAML, &t); } void emit_yaml(Tree const& t, FILE *f) { EmitterFile em(EmitOptions{}, f); em.emit_as(EMIT_YAML, &t); } void emit_json(Tree const& t, EmitOptions const& opts, FILE *f) { EmitterFile em(opts, f); em.emit_as(EMIT_JSON, &t); } void emit_json(Tree const& t, FILE *f) { EmitterFile em(EmitOptions{}, f); em.emit_as(EMIT_JSON, &t); } // emit from tree and node id ----------------------- void emit_yaml(Tree const& t, id_type id, EmitOptions const& opts, FILE *f) { EmitterFile em(opts, f); em.emit_as(EMIT_YAML, &t, id); } void emit_yaml(Tree const& t, id_type id, FILE *f) { EmitterFile em(EmitOptions{}, f); em.emit_as(EMIT_YAML, &t, id); } void emit_json(Tree const& t, id_type id, EmitOptions const& opts, FILE *f) { EmitterFile em(opts, f); em.emit_as(EMIT_JSON, &t, id); } void emit_json(Tree const& t, id_type id, FILE *f) { EmitterFile em(EmitOptions{}, f); em.emit_as(EMIT_JSON, &t, id); } // emit from ConstNodeRef ------------------------ void emit_yaml(ConstNodeRef const& r, EmitOptions const& opts, FILE *f) { EmitterFile em(opts, f); em.emit_as(EMIT_YAML, r.tree(), r.id()); } void emit_yaml(ConstNodeRef const& r, FILE *f) { EmitterFile em(EmitOptions{}, f); em.emit_as(EMIT_YAML, r.tree(), r.id()); } void emit_json(ConstNodeRef const& r, EmitOptions const& opts, FILE *f) { EmitterFile em(opts, f); em.emit_as(EMIT_JSON, r.tree(), r.id()); } void emit_json(ConstNodeRef const& r, FILE *f) { EmitterFile em(EmitOptions{}, f); em.emit_as(EMIT_JSON, r.tree(), r.id()); } } // namespace yml } // namespace c4 #endif /* RYML_SINGLE_HDR_DEFINE_NOW */ // (end src/c4/yml/emit_file.cpp) #endif /* RYML_SINGLE_HEADER_AMALGAMATED_HPP_ */