apply new format
diff --git a/dev/test/include/catch.hpp b/dev/test/include/catch.hpp index 7e706f9..836e405 100644 --- a/dev/test/include/catch.hpp +++ b/dev/test/include/catch.hpp
@@ -2,8 +2,8 @@ * Catch v2.13.7 * Generated: 2021-07-28 20:29:27.753164 * ---------------------------------------------------------- - * This file has been merged from multiple headers. Please don't edit it directly - * Copyright (c) 2021 Two Blue Cubes Ltd. All rights reserved. + * This file has been merged from multiple headers. Please don't edit it + * directly Copyright (c) 2021 Two Blue Cubes Ltd. All rights reserved. * * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) @@ -12,55 +12,54 @@ #define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED // start catch.hpp - #define CATCH_VERSION_MAJOR 2 #define CATCH_VERSION_MINOR 13 #define CATCH_VERSION_PATCH 7 #ifdef __clang__ -# pragma clang system_header +#pragma clang system_header #elif defined __GNUC__ -# pragma GCC system_header +#pragma GCC system_header #endif // start catch_suppress_warnings.h #ifdef __clang__ -# ifdef __ICC // icpc defines the __clang__ macro -# pragma warning(push) -# pragma warning(disable: 161 1682) -# else // __ICC -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wpadded" -# pragma clang diagnostic ignored "-Wswitch-enum" -# pragma clang diagnostic ignored "-Wcovered-switch-default" -# endif +#ifdef __ICC // icpc defines the __clang__ macro +#pragma warning(push) +#pragma warning(disable : 161 1682) +#else // __ICC +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpadded" +#pragma clang diagnostic ignored "-Wswitch-enum" +#pragma clang diagnostic ignored "-Wcovered-switch-default" +#endif #elif defined __GNUC__ - // Because REQUIREs trigger GCC's -Wparentheses, and because still - // supported version of g++ have only buggy support for _Pragmas, - // Wparentheses have to be suppressed globally. -# pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details +// Because REQUIREs trigger GCC's -Wparentheses, and because still +// supported version of g++ have only buggy support for _Pragmas, +// Wparentheses have to be suppressed globally. +#pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wunused-variable" -# pragma GCC diagnostic ignored "-Wpadded" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunused-variable" +#pragma GCC diagnostic ignored "-Wpadded" #endif // end catch_suppress_warnings.h #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER) -# define CATCH_IMPL -# define CATCH_CONFIG_ALL_PARTS +#define CATCH_IMPL +#define CATCH_CONFIG_ALL_PARTS #endif // In the impl file, we want to have access to all parts of the headers // Can also be used to sanely support PCHs #if defined(CATCH_CONFIG_ALL_PARTS) -# define CATCH_CONFIG_EXTERNAL_INTERFACES -# if defined(CATCH_CONFIG_DISABLE_MATCHERS) -# undef CATCH_CONFIG_DISABLE_MATCHERS -# endif -# if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER) -# define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER -# endif +#define CATCH_CONFIG_EXTERNAL_INTERFACES +#if defined(CATCH_CONFIG_DISABLE_MATCHERS) +#undef CATCH_CONFIG_DISABLE_MATCHERS +#endif +#if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER) +#define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER +#endif #endif #if !defined(CATCH_CONFIG_IMPL_ONLY) @@ -69,28 +68,29 @@ // See e.g.: // https://opensource.apple.com/source/CarbonHeaders/CarbonHeaders-18.1/TargetConditionals.h.auto.html #ifdef __APPLE__ -# include <TargetConditionals.h> -# if (defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1) || \ - (defined(TARGET_OS_MAC) && TARGET_OS_MAC == 1) -# define CATCH_PLATFORM_MAC -# elif (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1) -# define CATCH_PLATFORM_IPHONE -# endif +#include <TargetConditionals.h> +#if (defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1) || \ + (defined(TARGET_OS_MAC) && TARGET_OS_MAC == 1) +#define CATCH_PLATFORM_MAC +#elif (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1) +#define CATCH_PLATFORM_IPHONE +#endif #elif defined(linux) || defined(__linux) || defined(__linux__) -# define CATCH_PLATFORM_LINUX +#define CATCH_PLATFORM_LINUX -#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__) -# define CATCH_PLATFORM_WINDOWS +#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || \ + defined(_MSC_VER) || defined(__MINGW32__) +#define CATCH_PLATFORM_WINDOWS #endif // end catch_platform.h #ifdef CATCH_IMPL -# ifndef CLARA_CONFIG_MAIN -# define CLARA_CONFIG_MAIN_NOT_DEFINED -# define CLARA_CONFIG_MAIN -# endif +#ifndef CLARA_CONFIG_MAIN +#define CLARA_CONFIG_MAIN_NOT_DEFINED +#define CLARA_CONFIG_MAIN +#endif #endif // start catch_user_interfaces.h @@ -125,30 +125,33 @@ #ifdef __cplusplus -# if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L) -# define CATCH_CPP14_OR_GREATER -# endif +#if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L) +#define CATCH_CPP14_OR_GREATER +#endif -# if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) -# define CATCH_CPP17_OR_GREATER -# endif +#if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) +#define CATCH_CPP17_OR_GREATER +#endif #endif // Only GCC compiler should be used in this block, so other compilers trying to // mask themselves as GCC should be ignored. -#if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__) && !defined(__LCC__) -# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" ) -# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" ) +#if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && \ + !defined(__CUDACC__) && !defined(__LCC__) +#define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma("GCC diagnostic push") +#define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma("GCC diagnostic pop") -# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) +#define CATCH_INTERNAL_IGNORE_BUT_WARN(...) \ + (void)__builtin_constant_p(__VA_ARGS__) #endif #if defined(__clang__) -# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" ) -# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic pop" ) +#define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ + _Pragma("clang diagnostic push") +#define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma("clang diagnostic pop") // As of this writing, IBM XL's implementation of __builtin_constant_p has a bug // which results in calls to destructors being emitted for each temporary, @@ -161,62 +164,66 @@ // ``` // // Therefore, `CATCH_INTERNAL_IGNORE_BUT_WARN` is not implemented. -# if !defined(__ibmxl__) && !defined(__CUDACC__) -# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) /* NOLINT(cppcoreguidelines-pro-type-vararg, hicpp-vararg) */ -# endif +#if !defined(__ibmxl__) && !defined(__CUDACC__) +#define CATCH_INTERNAL_IGNORE_BUT_WARN(...) \ + (void)__builtin_constant_p(__VA_ARGS__) /* NOLINT(cppcoreguidelines-pro-type-vararg, \ + hicpp-vararg) */ +#endif -# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ - _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \ - _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"") +#define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + _Pragma("clang diagnostic ignored \"-Wexit-time-destructors\"") \ + _Pragma("clang diagnostic ignored \"-Wglobal-constructors\"") -# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ - _Pragma( "clang diagnostic ignored \"-Wparentheses\"" ) +#define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ + _Pragma("clang diagnostic ignored \"-Wparentheses\"") -# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ - _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" ) +#define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ + _Pragma("clang diagnostic ignored \"-Wunused-variable\"") -# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ - _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" ) +#define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ + _Pragma("clang diagnostic ignored " \ + "\"-Wgnu-zero-variadic-macro-arguments\"") -# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ - _Pragma( "clang diagnostic ignored \"-Wunused-template\"" ) +#define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ + _Pragma("clang diagnostic ignored \"-Wunused-template\"") #endif // __clang__ //////////////////////////////////////////////////////////////////////////////// // Assume that non-Windows platforms support posix signals by default #if !defined(CATCH_PLATFORM_WINDOWS) - #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS +#define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS #endif //////////////////////////////////////////////////////////////////////////////// // We know some environments not to support full POSIX signals -#if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__) - #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS +#if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || \ + defined(__DJGPP__) +#define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS #endif #ifdef __OS400__ -# define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS -# define CATCH_CONFIG_COLOUR_NONE +#define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS +#define CATCH_CONFIG_COLOUR_NONE #endif //////////////////////////////////////////////////////////////////////////////// // Android somehow still does not support std::to_string #if defined(__ANDROID__) -# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING -# define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE +#define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING +#define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE #endif //////////////////////////////////////////////////////////////////////////////// // Not all Windows environments support SEH properly #if defined(__MINGW32__) -# define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH +#define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH #endif //////////////////////////////////////////////////////////////////////////////// // PS4 #if defined(__ORBIS__) -# define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE +#define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE #endif //////////////////////////////////////////////////////////////////////////////// @@ -224,65 +231,70 @@ #ifdef __CYGWIN__ // Required for some versions of Cygwin to declare gettimeofday -// see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin -# define _BSD_SOURCE -// some versions of cygwin (most) do not support std::to_string. Use the libstd check. -// https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813 -# if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \ - && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF)) +// see: +// http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin +#define _BSD_SOURCE +// some versions of cygwin (most) do not support std::to_string. Use the libstd +// check. +// https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html +// line 2812-2813 +#if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) && \ + !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF)) -# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING +#define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING -# endif +#endif #endif // __CYGWIN__ //////////////////////////////////////////////////////////////////////////////// // Visual C++ #if defined(_MSC_VER) -# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) ) -# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) ) +#define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma(warning(push)) +#define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma(warning(pop)) // Universal Windows platform does not support SEH // Or console colours (or console at all...) -# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) -# define CATCH_CONFIG_COLOUR_NONE -# else -# define CATCH_INTERNAL_CONFIG_WINDOWS_SEH -# endif +#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) +#define CATCH_CONFIG_COLOUR_NONE +#else +#define CATCH_INTERNAL_CONFIG_WINDOWS_SEH +#endif // MSVC traditional preprocessor needs some workaround for __VA_ARGS__ // _MSVC_TRADITIONAL == 0 means new conformant preprocessor // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor -# if !defined(__clang__) // Handle Clang masquerading for msvc -# if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL) -# define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR -# endif // MSVC_TRADITIONAL -# endif // __clang__ +#if !defined(__clang__) // Handle Clang masquerading for msvc +#if !defined(_MSVC_TRADITIONAL) || \ + (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL) +#define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#endif // MSVC_TRADITIONAL +#endif // __clang__ #endif // _MSC_VER #if defined(_REENTRANT) || defined(_MSC_VER) -// Enable async processing, as -pthread is specified or no additional linking is required -# define CATCH_INTERNAL_CONFIG_USE_ASYNC +// Enable async processing, as -pthread is specified or no additional linking is +// required +#define CATCH_INTERNAL_CONFIG_USE_ASYNC #endif // _MSC_VER //////////////////////////////////////////////////////////////////////////////// // Check if we are compiled with -fno-exceptions or equivalent #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND) -# define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED +#define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED #endif //////////////////////////////////////////////////////////////////////////////// // DJGPP #ifdef __DJGPP__ -# define CATCH_INTERNAL_CONFIG_NO_WCHAR +#define CATCH_INTERNAL_CONFIG_NO_WCHAR #endif // __DJGPP__ //////////////////////////////////////////////////////////////////////////////// // Embarcadero C++Build #if defined(__BORLANDC__) - #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN +#define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN #endif //////////////////////////////////////////////////////////////////////////////// @@ -292,8 +304,8 @@ // handled by it. // Otherwise all supported compilers support COUNTER macro, // but user still might want to turn it off -#if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L ) - #define CATCH_INTERNAL_CONFIG_COUNTER +#if (!defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L) +#define CATCH_INTERNAL_CONFIG_COUNTER #endif //////////////////////////////////////////////////////////////////////////////// @@ -302,9 +314,9 @@ // This means that it is detected as Windows, but does not provide // the same set of capabilities as real Windows does. #if defined(UNDER_RTSS) || defined(RTX64_BUILD) - #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH - #define CATCH_INTERNAL_CONFIG_NO_ASYNC - #define CATCH_CONFIG_COLOUR_NONE +#define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH +#define CATCH_INTERNAL_CONFIG_NO_ASYNC +#define CATCH_CONFIG_COLOUR_NONE #endif #if !defined(_GLIBCXX_USE_C99_MATH_TR1) @@ -313,139 +325,173 @@ // Various stdlib support checks that require __has_include #if defined(__has_include) - // Check if string_view is available and usable - #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER) - # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW - #endif +// Check if string_view is available and usable +#if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER) +#define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW +#endif - // Check if optional is available and usable - # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER) - # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL - # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER) +// Check if optional is available and usable +#if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER) +#define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL +#endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER) - // Check if byte is available and usable - # if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER) - # include <cstddef> - # if defined(__cpp_lib_byte) && (__cpp_lib_byte > 0) - # define CATCH_INTERNAL_CONFIG_CPP17_BYTE - # endif - # endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER) +// Check if byte is available and usable +#if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER) +#include <cstddef> +#if defined(__cpp_lib_byte) && (__cpp_lib_byte > 0) +#define CATCH_INTERNAL_CONFIG_CPP17_BYTE +#endif +#endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER) - // Check if variant is available and usable - # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER) - # if defined(__clang__) && (__clang_major__ < 8) - // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852 - // fix should be in clang 8, workaround in libstdc++ 8.2 - # include <ciso646> - # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) - # define CATCH_CONFIG_NO_CPP17_VARIANT - # else - # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT - # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) - # else - # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT - # endif // defined(__clang__) && (__clang_major__ < 8) - # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER) +// Check if variant is available and usable +#if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER) +#if defined(__clang__) && (__clang_major__ < 8) +// work around clang bug with libstdc++ +// https://bugs.llvm.org/show_bug.cgi?id=31852 fix should be in clang 8, +// workaround in libstdc++ 8.2 +#include <ciso646> +#if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) +#define CATCH_CONFIG_NO_CPP17_VARIANT +#else +#define CATCH_INTERNAL_CONFIG_CPP17_VARIANT +#endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE + // < 9) +#else +#define CATCH_INTERNAL_CONFIG_CPP17_VARIANT +#endif // defined(__clang__) && (__clang_major__ < 8) +#endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER) #endif // defined(__has_include) -#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) -# define CATCH_CONFIG_COUNTER +#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && \ + !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) +#define CATCH_CONFIG_COUNTER #endif -#if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH) -# define CATCH_CONFIG_WINDOWS_SEH +#if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && \ + !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && \ + !defined(CATCH_CONFIG_WINDOWS_SEH) && \ + !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH) +#define CATCH_CONFIG_WINDOWS_SEH #endif -// This is set by default, because we assume that unix compilers are posix-signal-compatible by default. -#if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS) -# define CATCH_CONFIG_POSIX_SIGNALS +// This is set by default, because we assume that unix compilers are +// posix-signal-compatible by default. +#if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && \ + !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && \ + !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && \ + !defined(CATCH_CONFIG_POSIX_SIGNALS) +#define CATCH_CONFIG_POSIX_SIGNALS #endif -// This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions. -#if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR) -# define CATCH_CONFIG_WCHAR +// This is set by default, because we assume that compilers with no wchar_t +// support are just rare exceptions. +#if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && \ + !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR) +#define CATCH_CONFIG_WCHAR #endif -#if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING) -# define CATCH_CONFIG_CPP11_TO_STRING +#if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && \ + !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && \ + !defined(CATCH_CONFIG_CPP11_TO_STRING) +#define CATCH_CONFIG_CPP11_TO_STRING #endif -#if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL) -# define CATCH_CONFIG_CPP17_OPTIONAL +#if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && \ + !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && \ + !defined(CATCH_CONFIG_CPP17_OPTIONAL) +#define CATCH_CONFIG_CPP17_OPTIONAL #endif -#if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW) -# define CATCH_CONFIG_CPP17_STRING_VIEW +#if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && \ + !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && \ + !defined(CATCH_CONFIG_CPP17_STRING_VIEW) +#define CATCH_CONFIG_CPP17_STRING_VIEW #endif -#if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT) -# define CATCH_CONFIG_CPP17_VARIANT +#if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && \ + !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && \ + !defined(CATCH_CONFIG_CPP17_VARIANT) +#define CATCH_CONFIG_CPP17_VARIANT #endif -#if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE) -# define CATCH_CONFIG_CPP17_BYTE +#if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && \ + !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE) +#define CATCH_CONFIG_CPP17_BYTE #endif #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT) -# define CATCH_INTERNAL_CONFIG_NEW_CAPTURE +#define CATCH_INTERNAL_CONFIG_NEW_CAPTURE #endif -#if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE) -# define CATCH_CONFIG_NEW_CAPTURE +#if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && \ + !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && \ + !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && \ + !defined(CATCH_CONFIG_NEW_CAPTURE) +#define CATCH_CONFIG_NEW_CAPTURE #endif -#if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) -# define CATCH_CONFIG_DISABLE_EXCEPTIONS +#if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && \ + !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) +#define CATCH_CONFIG_DISABLE_EXCEPTIONS #endif -#if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN) -# define CATCH_CONFIG_POLYFILL_ISNAN +#if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && \ + !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && \ + !defined(CATCH_CONFIG_POLYFILL_ISNAN) +#define CATCH_CONFIG_POLYFILL_ISNAN #endif -#if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC) -# define CATCH_CONFIG_USE_ASYNC +#if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && \ + !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && \ + !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC) +#define CATCH_CONFIG_USE_ASYNC #endif -#if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE) -# define CATCH_CONFIG_ANDROID_LOGWRITE +#if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && \ + !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && \ + !defined(CATCH_CONFIG_ANDROID_LOGWRITE) +#define CATCH_CONFIG_ANDROID_LOGWRITE #endif -#if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) -# define CATCH_CONFIG_GLOBAL_NEXTAFTER +#if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && \ + !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && \ + !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) +#define CATCH_CONFIG_GLOBAL_NEXTAFTER #endif // Even if we do not think the compiler has that warning, we still have // to provide a macro that can be used by the code. #if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION) -# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION +#define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION #endif #if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION) -# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION +#define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION #endif #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) -# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS +#define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS #endif #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS) -# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS +#define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS #endif #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS) -# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS +#define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS #endif #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS) -# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS +#define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS #endif // The goal of this macro is to avoid evaluation of the arguments, but // still have the compiler warn on problems inside... #if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN) -# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) +#define CATCH_INTERNAL_IGNORE_BUT_WARN(...) #endif -#if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10) -# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS +#if defined(__APPLE__) && defined(__apple_build_version__) && \ + (__clang_major__ < 10) +#undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS #elif defined(__clang__) && (__clang_major__ < 5) -# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS +#undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS #endif #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS) -# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS +#define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS #endif #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) @@ -458,39 +504,44 @@ #define CATCH_CATCH_ANON(type) catch (type) #endif -#if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) +#if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && \ + !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && \ + !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #endif // end catch_compiler_capabilities.h -#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line -#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) +#define INTERNAL_CATCH_UNIQUE_NAME_LINE2(name, line) name##line +#define INTERNAL_CATCH_UNIQUE_NAME_LINE(name, line) \ + INTERNAL_CATCH_UNIQUE_NAME_LINE2(name, line) #ifdef CATCH_CONFIG_COUNTER -# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ ) +#define INTERNAL_CATCH_UNIQUE_NAME(name) \ + INTERNAL_CATCH_UNIQUE_NAME_LINE(name, __COUNTER__) #else -# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ ) +#define INTERNAL_CATCH_UNIQUE_NAME(name) \ + INTERNAL_CATCH_UNIQUE_NAME_LINE(name, __LINE__) #endif #include <iosfwd> #include <string> #include <cstdint> -// We need a dummy global operator<< so we can bring it into Catch namespace later +// We need a dummy global operator<< so we can bring it into Catch namespace +// later struct Catch_global_namespace_dummy {}; std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy); namespace Catch { - struct CaseSensitive { enum Choice { - Yes, - No - }; }; + struct CaseSensitive { + enum Choice { Yes, No }; + }; class NonCopyable { - NonCopyable( NonCopyable const& ) = delete; - NonCopyable( NonCopyable && ) = delete; - NonCopyable& operator = ( NonCopyable const& ) = delete; - NonCopyable& operator = ( NonCopyable && ) = delete; + NonCopyable(NonCopyable const&) = delete; + NonCopyable(NonCopyable&&) = delete; + NonCopyable& operator=(NonCopyable const&) = delete; + NonCopyable& operator=(NonCopyable&&) = delete; protected: NonCopyable(); @@ -500,25 +551,23 @@ struct SourceLineInfo { SourceLineInfo() = delete; - SourceLineInfo( char const* _file, std::size_t _line ) noexcept - : file( _file ), - line( _line ) - {} + SourceLineInfo(char const* _file, std::size_t _line) noexcept : + file(_file), line(_line) {} - SourceLineInfo( SourceLineInfo const& other ) = default; - SourceLineInfo& operator = ( SourceLineInfo const& ) = default; - SourceLineInfo( SourceLineInfo&& ) noexcept = default; - SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default; + SourceLineInfo(SourceLineInfo const& other) = default; + SourceLineInfo& operator=(SourceLineInfo const&) = default; + SourceLineInfo(SourceLineInfo&&) noexcept = default; + SourceLineInfo& operator=(SourceLineInfo&&) noexcept = default; bool empty() const noexcept { return file[0] == '\0'; } - bool operator == ( SourceLineInfo const& other ) const noexcept; - bool operator < ( SourceLineInfo const& other ) const noexcept; + bool operator==(SourceLineInfo const& other) const noexcept; + bool operator<(SourceLineInfo const& other) const noexcept; char const* file; std::size_t line; }; - std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ); + std::ostream& operator<<(std::ostream& os, SourceLineInfo const& info); // Bring in operator<< from global namespace into Catch namespace // This is necessary because the overload of operator<< above makes @@ -532,28 +581,32 @@ struct StreamEndStop { std::string operator+() const; }; - template<typename T> - T const& operator + ( T const& value, StreamEndStop ) { + template <typename T> T const& operator+(T const& value, StreamEndStop) { return value; } -} +} // namespace Catch -#define CATCH_INTERNAL_LINEINFO \ - ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) ) +#define CATCH_INTERNAL_LINEINFO \ + ::Catch::SourceLineInfo(__FILE__, static_cast<std::size_t>(__LINE__)) // end catch_common.h namespace Catch { struct RegistrarForTagAliases { - RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); + RegistrarForTagAliases(char const* alias, + char const* tag, + SourceLineInfo const& lineInfo); }; } // end namespace Catch -#define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \ - CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ - CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ - namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \ +#define CATCH_REGISTER_TAG_ALIAS(alias, spec) \ + CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + namespace { \ + Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( \ + AutoRegisterTagAlias)(alias, spec, CATCH_INTERNAL_LINEINFO); \ + } \ CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION // end catch_tag_alias_autoregistrar.h @@ -568,7 +621,7 @@ class TestSpec; struct ITestInvoker { - virtual void invoke () const = 0; + virtual void invoke() const = 0; virtual ~ITestInvoker(); }; @@ -578,15 +631,20 @@ struct ITestCaseRegistry { virtual ~ITestCaseRegistry(); virtual std::vector<TestCase> const& getAllTests() const = 0; - virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0; + virtual std::vector<TestCase> const& + getAllTestsSorted(IConfig const& config) const = 0; }; - bool isThrowSafe( TestCase const& testCase, IConfig const& config ); - bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ); - std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ); - std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ); + bool isThrowSafe(TestCase const& testCase, IConfig const& config); + bool matchTest(TestCase const& testCase, + TestSpec const& testSpec, + IConfig const& config); + std::vector<TestCase> filterTests(std::vector<TestCase> const& testCases, + TestSpec const& testSpec, + IConfig const& config); + std::vector<TestCase> const& getAllTestCasesSorted(IConfig const& config); -} +} // namespace Catch // end catch_interfaces_testcase.h // start catch_stringref.h @@ -615,40 +673,32 @@ public: // construction constexpr StringRef() noexcept = default; - StringRef( char const* rawChars ) noexcept; + StringRef(char const* rawChars) noexcept; - constexpr StringRef( char const* rawChars, size_type size ) noexcept - : m_start( rawChars ), - m_size( size ) - {} + constexpr StringRef(char const* rawChars, size_type size) noexcept : + m_start(rawChars), m_size(size) {} - StringRef( std::string const& stdString ) noexcept - : m_start( stdString.c_str() ), - m_size( stdString.size() ) - {} + StringRef(std::string const& stdString) noexcept : + m_start(stdString.c_str()), m_size(stdString.size()) {} explicit operator std::string() const { return std::string(m_start, m_size); } public: // operators - auto operator == ( StringRef const& other ) const noexcept -> bool; - auto operator != (StringRef const& other) const noexcept -> bool { + auto operator==(StringRef const& other) const noexcept -> bool; + auto operator!=(StringRef const& other) const noexcept -> bool { return !(*this == other); } - auto operator[] ( size_type index ) const noexcept -> char { + auto operator[](size_type index) const noexcept -> char { assert(index < m_size); return m_start[index]; } public: // named queries - constexpr auto empty() const noexcept -> bool { - return m_size == 0; - } - constexpr auto size() const noexcept -> size_type { - return m_size; - } + constexpr auto empty() const noexcept -> bool { return m_size == 0; } + constexpr auto size() const noexcept -> size_type { return m_size; } // Returns the current start pointer. If the StringRef is not // null-terminated, throws std::domain_exception @@ -658,7 +708,8 @@ // Returns a substring of [start, start + length). // If start + length > size(), then the substring is [start, size()). // If start > size(), then the substring is empty. - auto substr( size_type start, size_type length ) const noexcept -> StringRef; + auto substr(size_type start, size_type length) const noexcept + -> StringRef; // Returns the current start pointer. May not be null-terminated. auto data() const noexcept -> char const*; @@ -672,36 +723,51 @@ constexpr const_iterator end() const { return m_start + m_size; } }; - auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&; - auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&; + auto operator+=(std::string& lhs, StringRef const& sr) -> std::string&; + auto operator<<(std::ostream& os, StringRef const& sr) -> std::ostream&; - constexpr auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef { - return StringRef( rawChars, size ); + constexpr auto operator"" _sr(char const* rawChars, + std::size_t size) noexcept -> StringRef { + return StringRef(rawChars, size); } } // namespace Catch -constexpr auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef { - return Catch::StringRef( rawChars, size ); +constexpr auto operator"" _catch_sr(char const* rawChars, + std::size_t size) noexcept + -> Catch::StringRef { + return Catch::StringRef(rawChars, size); } // end catch_stringref.h // start catch_preprocessor.hpp - #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__ -#define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__))) -#define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__))) -#define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__))) -#define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__))) -#define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL1(...) \ + CATCH_RECURSION_LEVEL0( \ + CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL2(...) \ + CATCH_RECURSION_LEVEL1( \ + CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL3(...) \ + CATCH_RECURSION_LEVEL2( \ + CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL4(...) \ + CATCH_RECURSION_LEVEL3( \ + CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL5(...) \ + CATCH_RECURSION_LEVEL4( \ + CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__))) #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__ // MSVC needs more evaluations -#define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__))) -#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__)) +#define CATCH_RECURSION_LEVEL6(...) \ + CATCH_RECURSION_LEVEL5( \ + CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__))) +#define CATCH_RECURSE(...) \ + CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__)) #else -#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__) +#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__) #endif #define CATCH_REC_END(...) @@ -714,627 +780,1356 @@ #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2 #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1 #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT -#define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0) -#define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next) +#define CATCH_REC_NEXT1(test, next) CATCH_DEFER(CATCH_REC_NEXT0)(test, next, 0) +#define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next) -#define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) -#define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ ) -#define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) +#define CATCH_REC_LIST0(f, x, peek, ...) \ + , f(x) CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1))( \ + f, peek, __VA_ARGS__) +#define CATCH_REC_LIST1(f, x, peek, ...) \ + , f(x) CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST0))( \ + f, peek, __VA_ARGS__) +#define CATCH_REC_LIST2(f, x, peek, ...) \ + f(x) CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1))( \ + f, peek, __VA_ARGS__) -#define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) -#define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ ) -#define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) +#define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) \ + , f(userdata, x) CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD))( \ + f, userdata, peek, __VA_ARGS__) +#define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) \ + , f(userdata, x) CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD))( \ + f, userdata, peek, __VA_ARGS__) +#define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) \ + f(userdata, x) CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD))( \ + f, userdata, peek, __VA_ARGS__) -// Applies the function macro `f` to each of the remaining parameters, inserts commas between the results, -// and passes userdata as the first parameter to each invocation, -// e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c) -#define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) +// Applies the function macro `f` to each of the remaining parameters, inserts +// commas between the results, and passes userdata as the first parameter to +// each invocation, e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), +// f(x, b), f(x, c) +#define CATCH_REC_LIST_UD(f, userdata, ...) \ + CATCH_RECURSE(CATCH_REC_LIST2_UD( \ + f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) -#define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) +#define CATCH_REC_LIST(f, ...) \ + CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param) -#define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__ +#define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO##__VA_ARGS__ #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__ #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__) #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__ -#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) +#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) \ + INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) #else -// MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF +// MSVC is adding extra space and needs another indirection to expand +// INTERNAL_CATCH_NOINTERNAL_CATCH_DEF #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__) #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__ -#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1) +#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) \ + (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1) #endif #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__ #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name) -#define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__) +#define INTERNAL_CATCH_REMOVE_PARENS(...) \ + INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__) #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR -#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()) -#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)) +#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) \ + decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()) +#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) \ + INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)) #else -#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())) -#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))) +#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN( \ + __VA_ARGS__)>())) +#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) \ + INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2( \ + INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))) #endif -#define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\ - CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__) +#define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...) \ + CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST, __VA_ARGS__) #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0) -#define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1) -#define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2) -#define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3) -#define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4) -#define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5) -#define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6) -#define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7) -#define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8) -#define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9) -#define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10) +#define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) \ + INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1) +#define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) \ + INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2) +#define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) \ + INTERNAL_CATCH_REMOVE_PARENS(_0), \ + INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3) +#define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) \ + INTERNAL_CATCH_REMOVE_PARENS(_0), \ + INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4) +#define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) \ + INTERNAL_CATCH_REMOVE_PARENS(_0), \ + INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5) +#define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) \ + INTERNAL_CATCH_REMOVE_PARENS(_0), \ + INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6) +#define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) \ + INTERNAL_CATCH_REMOVE_PARENS(_0), \ + INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7) +#define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) \ + INTERNAL_CATCH_REMOVE_PARENS(_0), \ + INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8) +#define INTERNAL_CATCH_REMOVE_PARENS_10_ARG( \ + _0, _1, _2, _3, _4, _5, _6, _7, _8, _9) \ + INTERNAL_CATCH_REMOVE_PARENS(_0), \ + INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9) +#define INTERNAL_CATCH_REMOVE_PARENS_11_ARG( \ + _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) \ + INTERNAL_CATCH_REMOVE_PARENS(_0), \ + INTERNAL_CATCH_REMOVE_PARENS_10_ARG( \ + _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) -#define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N +#define INTERNAL_CATCH_VA_NARGS_IMPL( \ + _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) \ + N -#define INTERNAL_CATCH_TYPE_GEN\ - template<typename...> struct TypeList {};\ - template<typename...Ts>\ - constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\ - template<template<typename...> class...> struct TemplateTypeList{};\ - template<template<typename...> class...Cs>\ - constexpr auto get_wrapper() noexcept -> TemplateTypeList<Cs...> { return {}; }\ - template<typename...>\ - struct append;\ - template<typename...>\ - struct rewrap;\ - template<template<typename...> class, typename...>\ - struct create;\ - template<template<typename...> class, typename>\ - struct convert;\ - \ - template<typename T> \ - struct append<T> { using type = T; };\ - template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\ - struct append<L1<E1...>, L2<E2...>, Rest...> { using type = typename append<L1<E1...,E2...>, Rest...>::type; };\ - template< template<typename...> class L1, typename...E1, typename...Rest>\ - struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { using type = L1<E1...>; };\ - \ - template< template<typename...> class Container, template<typename...> class List, typename...elems>\ - struct rewrap<TemplateTypeList<Container>, List<elems...>> { using type = TypeList<Container<elems...>>; };\ - template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\ - struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { using type = typename append<TypeList<Container<Elems...>>, typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; };\ - \ - template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\ - struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; };\ - template<template <typename...> class Final, template <typename...> class List, typename...Ts>\ - struct convert<Final, List<Ts...>> { using type = typename append<Final<>,TypeList<Ts>...>::type; }; +#define INTERNAL_CATCH_TYPE_GEN \ + template <typename...> struct TypeList {}; \ + template <typename... Ts> \ + constexpr auto get_wrapper() noexcept->TypeList<Ts...> { \ + return {}; \ + } \ + template <template <typename...> class...> struct TemplateTypeList {}; \ + template <template <typename...> class... Cs> \ + constexpr auto get_wrapper() noexcept->TemplateTypeList<Cs...> { \ + return {}; \ + } \ + template <typename...> struct append; \ + template <typename...> struct rewrap; \ + template <template <typename...> class, typename...> struct create; \ + template <template <typename...> class, typename> struct convert; \ + \ + template <typename T> struct append<T> { using type = T; }; \ + template <template <typename...> class L1, \ + typename... E1, \ + template <typename...> \ + class L2, \ + typename... E2, \ + typename... Rest> \ + struct append<L1<E1...>, L2<E2...>, Rest...> { \ + using type = typename append<L1<E1..., E2...>, Rest...>::type; \ + }; \ + template <template <typename...> class L1, \ + typename... E1, \ + typename... Rest> \ + struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { \ + using type = L1<E1...>; \ + }; \ + \ + template <template <typename...> class Container, \ + template <typename...> \ + class List, \ + typename... elems> \ + struct rewrap<TemplateTypeList<Container>, List<elems...>> { \ + using type = TypeList<Container<elems...>>; \ + }; \ + template <template <typename...> class Container, \ + template <typename...> \ + class List, \ + class... Elems, \ + typename... Elements> \ + struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { \ + using type = \ + typename append<TypeList<Container<Elems...>>, \ + typename rewrap<TemplateTypeList<Container>, \ + Elements...>::type>::type; \ + }; \ + \ + template <template <typename...> class Final, \ + template <typename...> \ + class... Containers, \ + typename... Types> \ + struct create<Final, \ + TemplateTypeList<Containers...>, \ + TypeList<Types...>> { \ + using type = \ + typename append<Final<>, \ + typename rewrap<TemplateTypeList<Containers>, \ + Types...>::type...>::type; \ + }; \ + template <template <typename...> class Final, \ + template <typename...> \ + class List, \ + typename... Ts> \ + struct convert<Final, List<Ts...>> { \ + using type = typename append<Final<>, TypeList<Ts>...>::type; \ + }; -#define INTERNAL_CATCH_NTTP_1(signature, ...)\ - template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\ - template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ - constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \ - template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> struct NttpTemplateTypeList{};\ - template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Cs>\ - constexpr auto get_wrapper() noexcept -> NttpTemplateTypeList<Cs...> { return {}; } \ - \ - template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\ - struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { using type = TypeList<Container<__VA_ARGS__>>; };\ - template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\ - struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> { using type = typename append<TypeList<Container<__VA_ARGS__>>, typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; };\ - template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\ - struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; }; +#define INTERNAL_CATCH_NTTP_1(signature, ...) \ + template <INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp {}; \ + template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \ + constexpr auto get_wrapper() noexcept->Nttp<__VA_ARGS__> { \ + return {}; \ + } \ + template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> \ + struct NttpTemplateTypeList {}; \ + template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class... Cs> \ + constexpr auto get_wrapper() noexcept->NttpTemplateTypeList<Cs...> { \ + return {}; \ + } \ + \ + template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \ + class Container, \ + template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \ + class List, \ + INTERNAL_CATCH_REMOVE_PARENS(signature)> \ + struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { \ + using type = TypeList<Container<__VA_ARGS__>>; \ + }; \ + template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \ + class Container, \ + template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \ + class List, \ + INTERNAL_CATCH_REMOVE_PARENS(signature), \ + typename... Elements> \ + struct rewrap<NttpTemplateTypeList<Container>, \ + List<__VA_ARGS__>, \ + Elements...> { \ + using type = \ + typename append<TypeList<Container<__VA_ARGS__>>, \ + typename rewrap<NttpTemplateTypeList<Container>, \ + Elements...>::type>::type; \ + }; \ + template <template <typename...> class Final, \ + template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \ + class... Containers, \ + typename... Types> \ + struct create<Final, \ + NttpTemplateTypeList<Containers...>, \ + TypeList<Types...>> { \ + using type = \ + typename append<Final<>, \ + typename rewrap<NttpTemplateTypeList<Containers>, \ + Types...>::type...>::type; \ + }; #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName) -#define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\ - template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ - static void TestName() -#define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\ - template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ - static void TestName() +#define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature) \ + template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName() +#define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...) \ + template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName() #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName) -#define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\ - template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ - static void TestName() -#define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\ - template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ - static void TestName() +#define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature) \ + template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName() +#define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature, ...) \ + template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName() -#define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\ - template<typename Type>\ - void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\ - {\ - Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\ +#define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature) \ + template <typename Type> \ + void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags) { \ + Catch::AutoReg(Catch::makeTestInvoker(&TestFunc<Type>), \ + CATCH_INTERNAL_LINEINFO, \ + Catch::StringRef(), \ + nameAndTags); \ } -#define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\ - template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ - void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\ - {\ - Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\ +#define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...) \ + template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \ + void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags) { \ + Catch::AutoReg(Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), \ + CATCH_INTERNAL_LINEINFO, \ + Catch::StringRef(), \ + nameAndTags); \ } -#define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\ - template<typename Type>\ - void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\ - {\ - Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\ +#define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...) \ + template <typename Type> \ + void reg_test(TypeList<Type>, \ + Catch::StringRef className, \ + Catch::NameAndTags nameAndTags) { \ + Catch::AutoReg(Catch::makeTestInvoker(&TestName<Type>::test), \ + CATCH_INTERNAL_LINEINFO, \ + className, \ + nameAndTags); \ } -#define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\ - template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ - void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\ - {\ - Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\ +#define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...) \ + template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \ + void reg_test(Nttp<__VA_ARGS__>, \ + Catch::StringRef className, \ + Catch::NameAndTags nameAndTags) { \ + Catch::AutoReg(Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), \ + CATCH_INTERNAL_LINEINFO, \ + className, \ + nameAndTags); \ } #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName) -#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\ - template<typename TestType> \ - struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \ - void test();\ +#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1( \ + TestName, ClassName, signature) \ + template <typename TestType> \ + struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \ + void test(); \ } -#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\ - template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \ - struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \ - void test();\ +#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X( \ + TestName, ClassName, signature, ...) \ + template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \ + struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \ + void test(); \ } #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName) -#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\ - template<typename TestType> \ +#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature) \ + template <typename TestType> \ void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test() -#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\ - template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \ - void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test() +#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...) \ + template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \ + void INTERNAL_CATCH_MAKE_NAMESPACE( \ + TestName)::TestName<__VA_ARGS__>::test() #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_NTTP_0 -#define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__),INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_0) -#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__) -#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__) -#define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__) -#define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__) -#define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__) -#define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__) -#define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__) +#define INTERNAL_CATCH_NTTP_GEN(...) \ + INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, \ + INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \ + INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \ + INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \ + INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \ + INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \ + INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \ + INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \ + INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \ + INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \ + INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \ + INTERNAL_CATCH_NTTP_0) +#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) \ + INTERNAL_CATCH_VA_NARGS_IMPL("dummy", \ + __VA_ARGS__, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0) \ + (TestName, __VA_ARGS__) +#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) \ + INTERNAL_CATCH_VA_NARGS_IMPL("dummy", \ + __VA_ARGS__, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0) \ + (TestName, ClassName, __VA_ARGS__) +#define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) \ + INTERNAL_CATCH_VA_NARGS_IMPL("dummy", \ + __VA_ARGS__, \ + INTERNAL_CATCH_NTTP_REGISTER_METHOD, \ + INTERNAL_CATCH_NTTP_REGISTER_METHOD, \ + INTERNAL_CATCH_NTTP_REGISTER_METHOD, \ + INTERNAL_CATCH_NTTP_REGISTER_METHOD, \ + INTERNAL_CATCH_NTTP_REGISTER_METHOD, \ + INTERNAL_CATCH_NTTP_REGISTER_METHOD, \ + INTERNAL_CATCH_NTTP_REGISTER_METHOD, \ + INTERNAL_CATCH_NTTP_REGISTER_METHOD, \ + INTERNAL_CATCH_NTTP_REGISTER_METHOD, \ + INTERNAL_CATCH_NTTP_REGISTER_METHOD0, \ + INTERNAL_CATCH_NTTP_REGISTER_METHOD0) \ + (TestName, __VA_ARGS__) +#define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) \ + INTERNAL_CATCH_VA_NARGS_IMPL("dummy", \ + __VA_ARGS__, \ + INTERNAL_CATCH_NTTP_REGISTER, \ + INTERNAL_CATCH_NTTP_REGISTER, \ + INTERNAL_CATCH_NTTP_REGISTER, \ + INTERNAL_CATCH_NTTP_REGISTER, \ + INTERNAL_CATCH_NTTP_REGISTER, \ + INTERNAL_CATCH_NTTP_REGISTER, \ + INTERNAL_CATCH_NTTP_REGISTER, \ + INTERNAL_CATCH_NTTP_REGISTER, \ + INTERNAL_CATCH_NTTP_REGISTER, \ + INTERNAL_CATCH_NTTP_REGISTER0, \ + INTERNAL_CATCH_NTTP_REGISTER0) \ + (TestFunc, __VA_ARGS__) +#define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) \ + INTERNAL_CATCH_VA_NARGS_IMPL("dummy", \ + __VA_ARGS__, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST1, \ + INTERNAL_CATCH_DEFINE_SIG_TEST0) \ + (TestName, __VA_ARGS__) +#define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) \ + INTERNAL_CATCH_VA_NARGS_IMPL("dummy", \ + __VA_ARGS__, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST1, \ + INTERNAL_CATCH_DECLARE_SIG_TEST0) \ + (TestName, __VA_ARGS__) +#define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) \ + INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, \ + INTERNAL_CATCH_REMOVE_PARENS_11_ARG, \ + INTERNAL_CATCH_REMOVE_PARENS_10_ARG, \ + INTERNAL_CATCH_REMOVE_PARENS_9_ARG, \ + INTERNAL_CATCH_REMOVE_PARENS_8_ARG, \ + INTERNAL_CATCH_REMOVE_PARENS_7_ARG, \ + INTERNAL_CATCH_REMOVE_PARENS_6_ARG, \ + INTERNAL_CATCH_REMOVE_PARENS_5_ARG, \ + INTERNAL_CATCH_REMOVE_PARENS_4_ARG, \ + INTERNAL_CATCH_REMOVE_PARENS_3_ARG, \ + INTERNAL_CATCH_REMOVE_PARENS_2_ARG, \ + INTERNAL_CATCH_REMOVE_PARENS_1_ARG) \ + (__VA_ARGS__) #else #define INTERNAL_CATCH_NTTP_0(signature) -#define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1,INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_0)( __VA_ARGS__)) -#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__)) -#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__)) -#define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__)) -#define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__)) -#define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__)) -#define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__)) -#define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__)) +#define INTERNAL_CATCH_NTTP_GEN(...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, \ + INTERNAL_CATCH_NTTP_1, \ + INTERNAL_CATCH_NTTP_1, \ + INTERNAL_CATCH_NTTP_1, \ + INTERNAL_CATCH_NTTP_1, \ + INTERNAL_CATCH_NTTP_1, \ + INTERNAL_CATCH_NTTP_1, \ + INTERNAL_CATCH_NTTP_1, \ + INTERNAL_CATCH_NTTP_1, \ + INTERNAL_CATCH_NTTP_1, \ + INTERNAL_CATCH_NTTP_1, \ + INTERNAL_CATCH_NTTP_0)(__VA_ARGS__)) +#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) \ + INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \ + "dummy", \ + __VA_ARGS__, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__)) +#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_VA_NARGS_IMPL("dummy", \ + __VA_ARGS__, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)( \ + TestName, ClassName, __VA_ARGS__)) +#define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) \ + INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \ + "dummy", \ + __VA_ARGS__, \ + INTERNAL_CATCH_NTTP_REGISTER_METHOD, \ + INTERNAL_CATCH_NTTP_REGISTER_METHOD, \ + INTERNAL_CATCH_NTTP_REGISTER_METHOD, \ + INTERNAL_CATCH_NTTP_REGISTER_METHOD, \ + INTERNAL_CATCH_NTTP_REGISTER_METHOD, \ + INTERNAL_CATCH_NTTP_REGISTER_METHOD, \ + INTERNAL_CATCH_NTTP_REGISTER_METHOD, \ + INTERNAL_CATCH_NTTP_REGISTER_METHOD, \ + INTERNAL_CATCH_NTTP_REGISTER_METHOD, \ + INTERNAL_CATCH_NTTP_REGISTER_METHOD0, \ + INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__)) +#define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) \ + INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \ + "dummy", \ + __VA_ARGS__, \ + INTERNAL_CATCH_NTTP_REGISTER, \ + INTERNAL_CATCH_NTTP_REGISTER, \ + INTERNAL_CATCH_NTTP_REGISTER, \ + INTERNAL_CATCH_NTTP_REGISTER, \ + INTERNAL_CATCH_NTTP_REGISTER, \ + INTERNAL_CATCH_NTTP_REGISTER, \ + INTERNAL_CATCH_NTTP_REGISTER, \ + INTERNAL_CATCH_NTTP_REGISTER, \ + INTERNAL_CATCH_NTTP_REGISTER, \ + INTERNAL_CATCH_NTTP_REGISTER0, \ + INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__)) +#define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) \ + INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \ + "dummy", \ + __VA_ARGS__, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST1, \ + INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__)) +#define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) \ + INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \ + "dummy", \ + __VA_ARGS__, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_X, \ + INTERNAL_CATCH_DEFINE_SIG_TEST_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST_X, \ + INTERNAL_CATCH_DECLARE_SIG_TEST1, \ + INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__)) +#define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) \ + INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \ + __VA_ARGS__, \ + INTERNAL_CATCH_REMOVE_PARENS_11_ARG, \ + INTERNAL_CATCH_REMOVE_PARENS_10_ARG, \ + INTERNAL_CATCH_REMOVE_PARENS_9_ARG, \ + INTERNAL_CATCH_REMOVE_PARENS_8_ARG, \ + INTERNAL_CATCH_REMOVE_PARENS_7_ARG, \ + INTERNAL_CATCH_REMOVE_PARENS_6_ARG, \ + INTERNAL_CATCH_REMOVE_PARENS_5_ARG, \ + INTERNAL_CATCH_REMOVE_PARENS_4_ARG, \ + INTERNAL_CATCH_REMOVE_PARENS_3_ARG, \ + INTERNAL_CATCH_REMOVE_PARENS_2_ARG, \ + INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__)) #endif // end catch_preprocessor.hpp // start catch_meta.hpp - #include <type_traits> namespace Catch { - template<typename T> - struct always_false : std::false_type {}; + template <typename T> struct always_false : std::false_type {}; template <typename> struct true_given : std::true_type {}; struct is_callable_tester { template <typename Fun, typename... Args> - true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int); - template <typename...> - std::false_type static test(...); + true_given<decltype(std::declval<Fun>()( + std::declval<Args>()...))> static test(int); + template <typename...> std::false_type static test(...); }; - template <typename T> - struct is_callable; + template <typename T> struct is_callable; template <typename Fun, typename... Args> - struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {}; + struct is_callable<Fun(Args...)> + : decltype(is_callable_tester::test<Fun, Args...>(0)) {}; #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703 // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is // replaced with std::invoke_result here. template <typename Func, typename... U> - using FunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U...>>>; + using FunctionReturnType = std::remove_reference_t< + std::remove_cv_t<std::invoke_result_t<Func, U...>>>; #else // Keep ::type here because we still support C++11 template <typename Func, typename... U> - using FunctionReturnType = typename std::remove_reference<typename std::remove_cv<typename std::result_of<Func(U...)>::type>::type>::type; + using FunctionReturnType = + typename std::remove_reference<typename std::remove_cv< + typename std::result_of<Func(U...)>::type>::type>::type; #endif } // namespace Catch -namespace mpl_{ +namespace mpl_ { struct na; } // end catch_meta.hpp namespace Catch { -template<typename C> -class TestInvokerAsMethod : public ITestInvoker { - void (C::*m_testAsMethod)(); -public: - TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {} + template <typename C> class TestInvokerAsMethod : public ITestInvoker { + void (C::*m_testAsMethod)(); - void invoke() const override { - C obj; - (obj.*m_testAsMethod)(); + public: + TestInvokerAsMethod(void (C::*testAsMethod)()) noexcept : + m_testAsMethod(testAsMethod) {} + + void invoke() const override { + C obj; + (obj.*m_testAsMethod)(); + } + }; + + auto makeTestInvoker(void (*testAsFunction)()) noexcept -> ITestInvoker*; + + template <typename C> + auto makeTestInvoker(void (C::*testAsMethod)()) noexcept -> ITestInvoker* { + return new (std::nothrow) TestInvokerAsMethod<C>(testAsMethod); } -}; -auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*; + struct NameAndTags { + NameAndTags(StringRef const& name_ = StringRef(), + StringRef const& tags_ = StringRef()) noexcept; + StringRef name; + StringRef tags; + }; -template<typename C> -auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* { - return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod ); -} - -struct NameAndTags { - NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept; - StringRef name; - StringRef tags; -}; - -struct AutoReg : NonCopyable { - AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept; - ~AutoReg(); -}; + struct AutoReg : NonCopyable { + AutoReg(ITestInvoker* invoker, + SourceLineInfo const& lineInfo, + StringRef const& classOrMethod, + NameAndTags const& nameAndTags) noexcept; + ~AutoReg(); + }; } // end namespace Catch #if defined(CATCH_CONFIG_DISABLE) - #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \ - static void TestName() - #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \ - namespace{ \ - struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \ - void test(); \ - }; \ - } \ - void TestName::test() - #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \ - INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature)) - #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \ - namespace{ \ - namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \ - INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\ - } \ - } \ - INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature)) - - #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR - #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \ - INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) - #else - #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) ) - #endif - - #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR - #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \ - INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) - #else - #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) ) - #endif - - #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR - #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \ - INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) - #else - #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) ) - #endif - - #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR - #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \ - INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) - #else - #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) ) - #endif -#endif - - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \ - static void TestName(); \ - CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ - CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ - namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \ - CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ - static void TestName() - #define INTERNAL_CATCH_TESTCASE( ... ) \ - INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ ) - - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \ - CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ - CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ - namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \ - CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION - - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\ - CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ - CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ - namespace{ \ - struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \ - void test(); \ - }; \ - Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \ - } \ - CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ - void TestName::test() - #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \ - INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ ) - - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \ - CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ - CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ - Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \ - CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION - - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\ - CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ - CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ - CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ - CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ - INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\ - namespace {\ - namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\ - INTERNAL_CATCH_TYPE_GEN\ - INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\ - INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\ - template<typename...Types> \ - struct TestName{\ - TestName(){\ - int index = 0; \ - constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\ - using expander = int[];\ - (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \ - }\ - };\ - static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ - TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\ - return 0;\ - }();\ - }\ - }\ - CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ - INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature)) +#define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(TestName, ...) \ + static void TestName() +#define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( \ + TestName, ClassName, ...) \ + namespace { \ + struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \ + void test(); \ + }; \ + } \ + void TestName::test() +#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( \ + TestName, TestFunc, Name, Tags, Signature, ...) \ + INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, \ + INTERNAL_CATCH_REMOVE_PARENS(Signature)) +#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \ + TestNameClass, TestName, ClassName, Name, Tags, Signature, ...) \ + namespace { \ + namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD( \ + TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature)); \ + } \ + } \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD( \ + TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature)) #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR - #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \ - INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) +#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____), \ + Name, \ + Tags, \ + typename TestType, \ + __VA_ARGS__) #else - #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) ) +#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____), \ + Name, \ + Tags, \ + typename TestType, \ + __VA_ARGS__)) #endif #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR - #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \ - INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) +#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION( \ + Name, Tags, Signature, ...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____), \ + Name, \ + Tags, \ + Signature, \ + __VA_ARGS__) #else - #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) ) -#endif - - #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \ - CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ - CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ - CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ - CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ - template<typename TestType> static void TestFuncName(); \ - namespace {\ - namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \ - INTERNAL_CATCH_TYPE_GEN \ - INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \ - template<typename... Types> \ - struct TestName { \ - void reg_tests() { \ - int index = 0; \ - using expander = int[]; \ - constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\ - constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\ - constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\ - (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFuncName<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++)... };/* NOLINT */\ - } \ - }; \ - static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \ - using TestInit = typename create<TestName, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \ - TestInit t; \ - t.reg_tests(); \ - return 0; \ - }(); \ - } \ - } \ - CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ - template<typename TestType> \ - static void TestFuncName() - -#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR - #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\ - INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T,__VA_ARGS__) -#else - #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T, __VA_ARGS__ ) ) +#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION( \ + Name, Tags, Signature, ...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____), \ + Name, \ + Tags, \ + Signature, \ + __VA_ARGS__)) #endif #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR - #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\ - INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__) +#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( \ + ClassName, Name, Tags, ...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + ClassName, \ + Name, \ + Tags, \ + typename T, \ + __VA_ARGS__) #else - #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) ) -#endif - - #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\ - CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ - CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ - CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ - template<typename TestType> static void TestFunc(); \ - namespace {\ - namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\ - INTERNAL_CATCH_TYPE_GEN\ - template<typename... Types> \ - struct TestName { \ - void reg_tests() { \ - int index = 0; \ - using expander = int[]; \ - (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFunc<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... };/* NOLINT */\ - } \ - };\ - static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \ - using TestInit = typename convert<TestName, TmplList>::type; \ - TestInit t; \ - t.reg_tests(); \ - return 0; \ - }(); \ - }}\ - CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ - template<typename TestType> \ - static void TestFunc() - - #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \ - INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, TmplList ) - - #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \ - CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ - CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ - CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ - CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ - namespace {\ - namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \ - INTERNAL_CATCH_TYPE_GEN\ - INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\ - INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\ - INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\ - template<typename...Types> \ - struct TestNameClass{\ - TestNameClass(){\ - int index = 0; \ - constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\ - using expander = int[];\ - (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \ - }\ - };\ - static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ - TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\ - return 0;\ - }();\ - }\ - }\ - CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ - INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature)) - -#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR - #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \ - INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) -#else - #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) ) +#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( \ + ClassName, Name, Tags, ...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + ClassName, \ + Name, \ + Tags, \ + typename T, \ + __VA_ARGS__)) #endif #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR - #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \ - INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) +#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( \ + ClassName, Name, Tags, Signature, ...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + ClassName, \ + Name, \ + Tags, \ + Signature, \ + __VA_ARGS__) #else - #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) ) +#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( \ + ClassName, Name, Tags, Signature, ...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + ClassName, \ + Name, \ + Tags, \ + Signature, \ + __VA_ARGS__)) +#endif #endif - #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\ - CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ - CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ - CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ - CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ - template<typename TestType> \ - struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \ - void test();\ - };\ - namespace {\ - namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\ - INTERNAL_CATCH_TYPE_GEN \ - INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\ - template<typename...Types>\ - struct TestNameClass{\ - void reg_tests(){\ - int index = 0;\ - using expander = int[];\ - constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\ - constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\ - constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\ - (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++)... };/* NOLINT */ \ - }\ - };\ - static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ - using TestInit = typename create<TestNameClass, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type;\ - TestInit t;\ - t.reg_tests();\ - return 0;\ - }(); \ - }\ - }\ - CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ - template<typename TestType> \ - void TestName<TestType>::test() +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_TESTCASE2(TestName, ...) \ + static void TestName(); \ + CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + namespace { \ + Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)( \ + Catch::makeTestInvoker(&TestName), \ + CATCH_INTERNAL_LINEINFO, \ + Catch::StringRef(), \ + Catch::NameAndTags{__VA_ARGS__}); \ + } /* NOLINT */ \ + CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ + static void TestName() +#define INTERNAL_CATCH_TESTCASE(...) \ + INTERNAL_CATCH_TESTCASE2( \ + INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____), __VA_ARGS__) + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_METHOD_AS_TEST_CASE(QualifiedMethod, ...) \ + CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + namespace { \ + Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)( \ + Catch::makeTestInvoker(&QualifiedMethod), \ + CATCH_INTERNAL_LINEINFO, \ + "&" #QualifiedMethod, \ + Catch::NameAndTags{__VA_ARGS__}); \ + } /* NOLINT */ \ + CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_TEST_CASE_METHOD2(TestName, ClassName, ...) \ + CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + namespace { \ + struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \ + void test(); \ + }; \ + Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)( \ + Catch::makeTestInvoker(&TestName::test), \ + CATCH_INTERNAL_LINEINFO, \ + #ClassName, \ + Catch::NameAndTags{__VA_ARGS__}); /* NOLINT */ \ + } \ + CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ + void TestName::test() +#define INTERNAL_CATCH_TEST_CASE_METHOD(ClassName, ...) \ + INTERNAL_CATCH_TEST_CASE_METHOD2( \ + INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____), \ + ClassName, \ + __VA_ARGS__) + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_REGISTER_TESTCASE(Function, ...) \ + CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)( \ + Catch::makeTestInvoker(Function), \ + CATCH_INTERNAL_LINEINFO, \ + Catch::StringRef(), \ + Catch::NameAndTags{__VA_ARGS__}); /* NOLINT */ \ + CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( \ + TestName, TestFunc, Name, Tags, Signature, ...) \ + CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ + CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ + INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, \ + INTERNAL_CATCH_REMOVE_PARENS(Signature)); \ + namespace { \ + namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \ + INTERNAL_CATCH_TYPE_GEN \ + INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \ + INTERNAL_CATCH_NTTP_REG_GEN( \ + TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature)) \ + template <typename... Types> struct TestName { \ + TestName() { \ + int index = 0; \ + constexpr char const* tmpl_types[] = {CATCH_REC_LIST( \ + INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, \ + __VA_ARGS__)}; \ + using expander = int[]; \ + (void)expander{ \ + (reg_test( \ + Types{}, \ + Catch::NameAndTags{ \ + Name " - " + std::string(tmpl_types[index]), \ + Tags}), \ + index++)...}; /* NOLINT */ \ + } \ + }; \ + static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \ + TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES( \ + __VA_ARGS__)>(); \ + return 0; \ + }(); \ + } \ + } \ + CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ + INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, \ + INTERNAL_CATCH_REMOVE_PARENS(Signature)) #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR - #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\ - INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T, __VA_ARGS__ ) +#define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____), \ + Name, \ + Tags, \ + typename TestType, \ + __VA_ARGS__) #else - #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T,__VA_ARGS__ ) ) +#define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \ + INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____), \ + Name, \ + Tags, \ + typename TestType, \ + __VA_ARGS__)) #endif #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR - #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\ - INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature, __VA_ARGS__ ) +#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____), \ + Name, \ + Tags, \ + Signature, \ + __VA_ARGS__) #else - #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature,__VA_ARGS__ ) ) +#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \ + INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____), \ + Name, \ + Tags, \ + Signature, \ + __VA_ARGS__)) #endif - #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \ - CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ - CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ - CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ - template<typename TestType> \ - struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \ - void test();\ - };\ - namespace {\ - namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \ - INTERNAL_CATCH_TYPE_GEN\ - template<typename...Types>\ - struct TestNameClass{\ - void reg_tests(){\ - int index = 0;\ - using expander = int[];\ - (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... };/* NOLINT */ \ - }\ - };\ - static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ - using TestInit = typename convert<TestNameClass, TmplList>::type;\ - TestInit t;\ - t.reg_tests();\ - return 0;\ - }(); \ - }}\ - CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ - template<typename TestType> \ - void TestName<TestType>::test() +#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( \ + TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \ + CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ + CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ + template <typename TestType> static void TestFuncName(); \ + namespace { \ + namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \ + INTERNAL_CATCH_TYPE_GEN \ + INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \ + template <typename... Types> struct TestName { \ + void reg_tests() { \ + int index = 0; \ + using expander = int[]; \ + constexpr char const* tmpl_types[] = {CATCH_REC_LIST( \ + INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, \ + INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))}; \ + constexpr char const* types_list[] = {CATCH_REC_LIST( \ + INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, \ + INTERNAL_CATCH_REMOVE_PARENS(TypesList))}; \ + constexpr auto num_types = \ + sizeof(types_list) / sizeof(types_list[0]); \ + (void)expander{ \ + (Catch::AutoReg( \ + Catch::makeTestInvoker(&TestFuncName<Types>), \ + CATCH_INTERNAL_LINEINFO, \ + Catch::StringRef(), \ + Catch::NameAndTags{ \ + Name " - " + \ + std::string( \ + tmpl_types[index / num_types]) + \ + "<" + \ + std::string( \ + types_list[index % num_types]) + \ + ">", \ + Tags}), \ + index++)...}; /* NOLINT */ \ + } \ + }; \ + static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \ + using TestInit = typename create< \ + TestName, \ + decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS( \ + TmplTypes)>()), \ + TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES( \ + INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \ + TestInit t; \ + t.reg_tests(); \ + return 0; \ + }(); \ + } \ + } \ + CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ + template <typename TestType> static void TestFuncName() -#define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \ - INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, TmplList ) +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...) \ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____), \ + Name, \ + Tags, \ + typename T, \ + __VA_ARGS__) +#else +#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...) \ + INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____), \ + Name, \ + Tags, \ + typename T, \ + __VA_ARGS__)) +#endif + +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( \ + Name, Tags, Signature, ...) \ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____), \ + Name, \ + Tags, \ + Signature, \ + __VA_ARGS__) +#else +#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( \ + Name, Tags, Signature, ...) \ + INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____), \ + Name, \ + Tags, \ + Signature, \ + __VA_ARGS__)) +#endif + +#define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2( \ + TestName, TestFunc, Name, Tags, TmplList) \ + CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ + template <typename TestType> static void TestFunc(); \ + namespace { \ + namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \ + INTERNAL_CATCH_TYPE_GEN \ + template <typename... Types> struct TestName { \ + void reg_tests() { \ + int index = 0; \ + using expander = int[]; \ + (void)expander{ \ + (Catch::AutoReg( \ + Catch::makeTestInvoker(&TestFunc<Types>), \ + CATCH_INTERNAL_LINEINFO, \ + Catch::StringRef(), \ + Catch::NameAndTags{ \ + Name " - " + \ + std::string( \ + INTERNAL_CATCH_STRINGIZE(TmplList)) + \ + " - " + std::to_string(index), \ + Tags}), \ + index++)...}; /* NOLINT */ \ + } \ + }; \ + static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \ + using TestInit = typename convert<TestName, TmplList>::type; \ + TestInit t; \ + t.reg_tests(); \ + return 0; \ + }(); \ + } \ + } \ + CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ + template <typename TestType> static void TestFunc() + +#define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \ + INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____), \ + Name, \ + Tags, \ + TmplList) + +#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( \ + TestNameClass, TestName, ClassName, Name, Tags, Signature, ...) \ + CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ + CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ + namespace { \ + namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \ + INTERNAL_CATCH_TYPE_GEN \ + INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \ + INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD( \ + TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature)); \ + INTERNAL_CATCH_NTTP_REG_METHOD_GEN( \ + TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature)) \ + template <typename... Types> struct TestNameClass { \ + TestNameClass() { \ + int index = 0; \ + constexpr char const* tmpl_types[] = {CATCH_REC_LIST( \ + INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, \ + __VA_ARGS__)}; \ + using expander = int[]; \ + (void)expander{ \ + (reg_test( \ + Types{}, \ + #ClassName, \ + Catch::NameAndTags{ \ + Name " - " + std::string(tmpl_types[index]), \ + Tags}), \ + index++)...}; /* NOLINT */ \ + } \ + }; \ + static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \ + TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES( \ + __VA_ARGS__)>(); \ + return 0; \ + }(); \ + } \ + } \ + CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ + INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD( \ + TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature)) + +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(ClassName, Name, Tags, ...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + ClassName, \ + Name, \ + Tags, \ + typename T, \ + __VA_ARGS__) +#else +#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(ClassName, Name, Tags, ...) \ + INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + ClassName, \ + Name, \ + Tags, \ + typename T, \ + __VA_ARGS__)) +#endif + +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( \ + ClassName, Name, Tags, Signature, ...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + ClassName, \ + Name, \ + Tags, \ + Signature, \ + __VA_ARGS__) +#else +#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( \ + ClassName, Name, Tags, Signature, ...) \ + INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + ClassName, \ + Name, \ + Tags, \ + Signature, \ + __VA_ARGS__)) +#endif + +#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, \ + TestName, \ + ClassName, \ + Name, \ + Tags, \ + Signature, \ + TmplTypes, \ + TypesList) \ + CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ + CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ + template <typename TestType> \ + struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName<TestType>) { \ + void test(); \ + }; \ + namespace { \ + namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) { \ + INTERNAL_CATCH_TYPE_GEN \ + INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \ + template <typename... Types> struct TestNameClass { \ + void reg_tests() { \ + int index = 0; \ + using expander = int[]; \ + constexpr char const* tmpl_types[] = {CATCH_REC_LIST( \ + INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, \ + INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))}; \ + constexpr char const* types_list[] = {CATCH_REC_LIST( \ + INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, \ + INTERNAL_CATCH_REMOVE_PARENS(TypesList))}; \ + constexpr auto num_types = \ + sizeof(types_list) / sizeof(types_list[0]); \ + (void)expander{ \ + (Catch::AutoReg( \ + Catch::makeTestInvoker(&TestName<Types>::test), \ + CATCH_INTERNAL_LINEINFO, \ + #ClassName, \ + Catch::NameAndTags{ \ + Name " - " + \ + std::string( \ + tmpl_types[index / num_types]) + \ + "<" + \ + std::string( \ + types_list[index % num_types]) + \ + ">", \ + Tags}), \ + index++)...}; /* NOLINT */ \ + } \ + }; \ + static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \ + using TestInit = typename create< \ + TestNameClass, \ + decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS( \ + TmplTypes)>()), \ + TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES( \ + INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \ + TestInit t; \ + t.reg_tests(); \ + return 0; \ + }(); \ + } \ + } \ + CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ + template <typename TestType> void TestName<TestType>::test() + +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( \ + ClassName, Name, Tags, ...) \ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____), \ + ClassName, \ + Name, \ + Tags, \ + typename T, \ + __VA_ARGS__) +#else +#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( \ + ClassName, Name, Tags, ...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____), \ + ClassName, \ + Name, \ + Tags, \ + typename T, \ + __VA_ARGS__)) +#endif + +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( \ + ClassName, Name, Tags, Signature, ...) \ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____), \ + ClassName, \ + Name, \ + Tags, \ + Signature, \ + __VA_ARGS__) +#else +#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( \ + ClassName, Name, Tags, Signature, ...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____), \ + ClassName, \ + Name, \ + Tags, \ + Signature, \ + __VA_ARGS__)) +#endif + +#define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( \ + TestNameClass, TestName, ClassName, Name, Tags, TmplList) \ + CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ + template <typename TestType> \ + struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName<TestType>) { \ + void test(); \ + }; \ + namespace { \ + namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \ + INTERNAL_CATCH_TYPE_GEN \ + template <typename... Types> struct TestNameClass { \ + void reg_tests() { \ + int index = 0; \ + using expander = int[]; \ + (void)expander{ \ + (Catch::AutoReg( \ + Catch::makeTestInvoker(&TestName<Types>::test), \ + CATCH_INTERNAL_LINEINFO, \ + #ClassName, \ + Catch::NameAndTags{ \ + Name " - " + \ + std::string( \ + INTERNAL_CATCH_STRINGIZE(TmplList)) + \ + " - " + std::to_string(index), \ + Tags}), \ + index++)...}; /* NOLINT */ \ + } \ + }; \ + static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \ + using TestInit = \ + typename convert<TestNameClass, TmplList>::type; \ + TestInit t; \ + t.reg_tests(); \ + return 0; \ + }(); \ + } \ + } \ + CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ + template <typename TestType> void TestName<TestType>::test() + +#define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( \ + ClassName, Name, Tags, TmplList) \ + INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \ + INTERNAL_CATCH_UNIQUE_NAME( \ + ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____), \ + ClassName, \ + Name, \ + Tags, \ + TmplList) // end catch_test_registry.h // start catch_capture.hpp @@ -1348,51 +2143,59 @@ namespace Catch { // ResultWas::OfType enum - struct ResultWas { enum OfType { - Unknown = -1, - Ok = 0, - Info = 1, - Warning = 2, + struct ResultWas { + enum OfType { + Unknown = -1, + Ok = 0, + Info = 1, + Warning = 2, - FailureBit = 0x10, + FailureBit = 0x10, - ExpressionFailed = FailureBit | 1, - ExplicitFailure = FailureBit | 2, + ExpressionFailed = FailureBit | 1, + ExplicitFailure = FailureBit | 2, - Exception = 0x100 | FailureBit, + Exception = 0x100 | FailureBit, - ThrewException = Exception | 1, - DidntThrowException = Exception | 2, + ThrewException = Exception | 1, + DidntThrowException = Exception | 2, - FatalErrorCondition = 0x200 | FailureBit + FatalErrorCondition = 0x200 | FailureBit - }; }; + }; + }; - bool isOk( ResultWas::OfType resultType ); - bool isJustInfo( int flags ); + bool isOk(ResultWas::OfType resultType); + bool isJustInfo(int flags); // ResultDisposition::Flags enum - struct ResultDisposition { enum Flags { - Normal = 0x01, + struct ResultDisposition { + enum Flags { + Normal = 0x01, - ContinueOnFailure = 0x02, // Failures fail test, but execution continues - FalseTest = 0x04, // Prefix expression with ! - SuppressFail = 0x08 // Failures are reported but do not fail the test - }; }; + ContinueOnFailure = + 0x02, // Failures fail test, but execution continues + FalseTest = 0x04, // Prefix expression with ! + SuppressFail = + 0x08 // Failures are reported but do not fail the test + }; + }; - ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ); + ResultDisposition::Flags operator|(ResultDisposition::Flags lhs, + ResultDisposition::Flags rhs); - bool shouldContinueOnFailure( int flags ); - inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; } - bool shouldSuppressFailure( int flags ); + bool shouldContinueOnFailure(int flags); + inline bool isFalseTest(int flags) { + return (flags & ResultDisposition::FalseTest) != 0; + } + bool shouldSuppressFailure(int flags); } // end namespace Catch // end catch_result_type.h namespace Catch { - struct AssertionInfo - { + struct AssertionInfo { StringRef macroName; SourceLineInfo lineInfo; StringRef capturedExpression; @@ -1400,7 +2203,7 @@ // We want to delete this constructor but a compiler bug in 4.8 means // the struct is then treated as non-aggregate - //AssertionInfo() = delete; + // AssertionInfo() = delete; }; } // end namespace Catch @@ -1433,25 +2236,26 @@ virtual std::ostream& stream() const = 0; }; - auto makeStream( StringRef const &filename ) -> IStream const*; + auto makeStream(StringRef const& filename) -> IStream const*; class ReusableStringStream : NonCopyable { std::size_t m_index; std::ostream* m_oss; + public: ReusableStringStream(); ~ReusableStringStream(); auto str() const -> std::string; - template<typename T> - auto operator << ( T const& value ) -> ReusableStringStream& { + template <typename T> + auto operator<<(T const& value) -> ReusableStringStream& { *m_oss << value; return *this; } auto get() -> std::ostream& { return *m_oss; } }; -} +} // namespace Catch // end catch_stream.h // start catch_interfaces_enum_values_registry.h @@ -1467,27 +2271,33 @@ ~EnumInfo(); - StringRef lookup( int value ) const; + StringRef lookup(int value) const; }; } // namespace Detail struct IMutableEnumValuesRegistry { virtual ~IMutableEnumValuesRegistry(); - virtual Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values ) = 0; + virtual Detail::EnumInfo const& + registerEnum(StringRef enumName, + StringRef allEnums, + std::vector<int> const& values) = 0; - template<typename E> - Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::initializer_list<E> values ) { - static_assert(sizeof(int) >= sizeof(E), "Cannot serialize enum to int"); + template <typename E> + Detail::EnumInfo const& registerEnum(StringRef enumName, + StringRef allEnums, + std::initializer_list<E> values) { + static_assert(sizeof(int) >= sizeof(E), + "Cannot serialize enum to int"); std::vector<int> intValues; - intValues.reserve( values.size() ); - for( auto enumValue : values ) - intValues.push_back( static_cast<int>( enumValue ) ); - return registerEnum( enumName, allEnums, intValues ); + intValues.reserve(values.size()); + for (auto enumValue : values) + intValues.push_back(static_cast<int>(enumValue)); + return registerEnum(enumName, allEnums, intValues); } }; -} // Catch +} // namespace Catch // end catch_interfaces_enum_values_registry.h @@ -1506,29 +2316,27 @@ #define CATCH_ARC_ENABLED 0 #endif -void arcSafeRelease( NSObject* obj ); -id performOptionalSelector( id obj, SEL sel ); +void arcSafeRelease(NSObject* obj); +id performOptionalSelector(id obj, SEL sel); #if !CATCH_ARC_ENABLED -inline void arcSafeRelease( NSObject* obj ) { - [obj release]; -} -inline id performOptionalSelector( id obj, SEL sel ) { - if( [obj respondsToSelector: sel] ) - return [obj performSelector: sel]; +inline void arcSafeRelease(NSObject* obj) { [obj release]; } +inline id performOptionalSelector(id obj, SEL sel) { + if ([obj respondsToSelector:sel]) + return [obj performSelector:sel]; return nil; } #define CATCH_UNSAFE_UNRETAINED #define CATCH_ARC_STRONG #else -inline void arcSafeRelease( NSObject* ){} -inline id performOptionalSelector( id obj, SEL sel ) { +inline void arcSafeRelease(NSObject*) {} +inline id performOptionalSelector(id obj, SEL sel) { #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" #endif - if( [obj respondsToSelector: sel] ) - return [obj performSelector: sel]; + if ([obj respondsToSelector:sel]) + return [obj performSelector:sel]; #ifdef __clang__ #pragma clang diagnostic pop #endif @@ -1543,7 +2351,9 @@ #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless +#pragma warning( \ + disable : 4180) // We attempt to stream a function (address) by const&, + // which MSVC complains about but is harmless #endif namespace Catch { @@ -1551,81 +2361,82 @@ extern const std::string unprintableString; - std::string rawMemoryToString( const void *object, std::size_t size ); + std::string rawMemoryToString(const void* object, std::size_t size); - template<typename T> - std::string rawMemoryToString( const T& object ) { - return rawMemoryToString( &object, sizeof(object) ); + template <typename T> std::string rawMemoryToString(const T& object) { + return rawMemoryToString(&object, sizeof(object)); } - template<typename T> - class IsStreamInsertable { - template<typename Stream, typename U> + template <typename T> class IsStreamInsertable { + template <typename Stream, typename U> static auto test(int) - -> decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type()); + -> decltype(std::declval<Stream&>() << std::declval<U>(), + std::true_type()); - template<typename, typename> - static auto test(...)->std::false_type; + template <typename, typename> + static auto test(...) -> std::false_type; public: - static const bool value = decltype(test<std::ostream, const T&>(0))::value; + static const bool value = + decltype(test<std::ostream, const T&>(0))::value; }; - template<typename E> - std::string convertUnknownEnumToString( E e ); + template <typename E> std::string convertUnknownEnumToString(E e); - template<typename T> - typename std::enable_if< - !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value, - std::string>::type convertUnstreamable( T const& ) { + template <typename T> + typename std::enable_if<!std::is_enum<T>::value && + !std::is_base_of<std::exception, T>::value, + std::string>::type + convertUnstreamable(T const&) { return Detail::unprintableString; } - template<typename T> - typename std::enable_if< - !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value, - std::string>::type convertUnstreamable(T const& ex) { + template <typename T> + typename std::enable_if<!std::is_enum<T>::value && + std::is_base_of<std::exception, T>::value, + std::string>::type + convertUnstreamable(T const& ex) { return ex.what(); } - template<typename T> - typename std::enable_if< - std::is_enum<T>::value - , std::string>::type convertUnstreamable( T const& value ) { - return convertUnknownEnumToString( value ); + template <typename T> + typename std::enable_if<std::is_enum<T>::value, std::string>::type + convertUnstreamable(T const& value) { + return convertUnknownEnumToString(value); } #if defined(_MANAGED) //! Convert a CLR string to a utf8 std::string - template<typename T> - std::string clrReferenceToString( T^ ref ) { + template <typename T> std::string clrReferenceToString(T ^ ref) { if (ref == nullptr) return std::string("null"); - auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString()); + auto bytes = + System::Text::Encoding::UTF8->GetBytes(ref->ToString()); cli::pin_ptr<System::Byte> p = &bytes[0]; - return std::string(reinterpret_cast<char const *>(p), bytes->Length); + return std::string(reinterpret_cast<char const*>(p), bytes->Length); } #endif } // namespace Detail // If we decide for C++14, change these to enable_if_ts - template <typename T, typename = void> - struct StringMaker { + template <typename T, typename = void> struct StringMaker { template <typename Fake = T> - static - typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type - convert(const Fake& value) { - ReusableStringStream rss; - // NB: call using the function-like syntax to avoid ambiguity with - // user-defined templated operator<< under clang. - rss.operator<<(value); - return rss.str(); + static typename std::enable_if< + ::Catch::Detail::IsStreamInsertable<Fake>::value, + std::string>::type + convert(const Fake& value) { + ReusableStringStream rss; + // NB: call using the function-like syntax to avoid ambiguity with + // user-defined templated operator<< under clang. + rss.operator<<(value); + return rss.str(); } template <typename Fake = T> - static - typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type - convert( const Fake& value ) { + static typename std::enable_if< + !::Catch::Detail::IsStreamInsertable<Fake>::value, + std::string>::type + convert(const Fake& value) { #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER) return Detail::convertUnstreamable(value); #else @@ -1636,22 +2447,22 @@ namespace Detail { - // This function dispatches all stringification requests inside of Catch. - // Should be preferably called fully qualified, like ::Catch::Detail::stringify - template <typename T> - std::string stringify(const T& e) { - return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e); + // This function dispatches all stringification requests inside of + // Catch. Should be preferably called fully qualified, like + // ::Catch::Detail::stringify + template <typename T> std::string stringify(const T& e) { + return ::Catch::StringMaker<typename std::remove_cv< + typename std::remove_reference<T>::type>::type>::convert(e); } - template<typename E> - std::string convertUnknownEnumToString( E e ) { - return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e)); + template <typename E> std::string convertUnknownEnumToString(E e) { + return ::Catch::Detail::stringify( + static_cast<typename std::underlying_type<E>::type>(e)); } #if defined(_MANAGED) - template <typename T> - std::string stringify( T^ e ) { - return ::Catch::StringMaker<T^>::convert(e); + template <typename T> std::string stringify(T ^ e) { + return ::Catch::StringMaker<T ^>::convert(e); } #endif @@ -1659,141 +2470,117 @@ // Some predefined specializations - template<> - struct StringMaker<std::string> { + template <> struct StringMaker<std::string> { static std::string convert(const std::string& str); }; #ifdef CATCH_CONFIG_CPP17_STRING_VIEW - template<> - struct StringMaker<std::string_view> { + template <> struct StringMaker<std::string_view> { static std::string convert(std::string_view str); }; #endif - template<> - struct StringMaker<char const *> { - static std::string convert(char const * str); + template <> struct StringMaker<char const*> { + static std::string convert(char const* str); }; - template<> - struct StringMaker<char *> { - static std::string convert(char * str); + template <> struct StringMaker<char*> { + static std::string convert(char* str); }; #ifdef CATCH_CONFIG_WCHAR - template<> - struct StringMaker<std::wstring> { + template <> struct StringMaker<std::wstring> { static std::string convert(const std::wstring& wstr); }; -# ifdef CATCH_CONFIG_CPP17_STRING_VIEW - template<> - struct StringMaker<std::wstring_view> { +#ifdef CATCH_CONFIG_CPP17_STRING_VIEW + template <> struct StringMaker<std::wstring_view> { static std::string convert(std::wstring_view str); }; -# endif - - template<> - struct StringMaker<wchar_t const *> { - static std::string convert(wchar_t const * str); - }; - template<> - struct StringMaker<wchar_t *> { - static std::string convert(wchar_t * str); - }; #endif - // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer, + template <> struct StringMaker<wchar_t const*> { + static std::string convert(wchar_t const* str); + }; + template <> struct StringMaker<wchar_t*> { + static std::string convert(wchar_t* str); + }; +#endif + + // TBD: Should we use `strnlen` to ensure that we don't go out of the + // buffer, // while keeping string semantics? - template<int SZ> - struct StringMaker<char[SZ]> { + template <int SZ> struct StringMaker<char[SZ]> { static std::string convert(char const* str) { - return ::Catch::Detail::stringify(std::string{ str }); + return ::Catch::Detail::stringify(std::string{str}); } }; - template<int SZ> - struct StringMaker<signed char[SZ]> { + template <int SZ> struct StringMaker<signed char[SZ]> { static std::string convert(signed char const* str) { - return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) }); + return ::Catch::Detail::stringify( + std::string{reinterpret_cast<char const*>(str)}); } }; - template<int SZ> - struct StringMaker<unsigned char[SZ]> { + template <int SZ> struct StringMaker<unsigned char[SZ]> { static std::string convert(unsigned char const* str) { - return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) }); + return ::Catch::Detail::stringify( + std::string{reinterpret_cast<char const*>(str)}); } }; #if defined(CATCH_CONFIG_CPP17_BYTE) - template<> - struct StringMaker<std::byte> { + template <> struct StringMaker<std::byte> { static std::string convert(std::byte value); }; #endif // defined(CATCH_CONFIG_CPP17_BYTE) - template<> - struct StringMaker<int> { + template <> struct StringMaker<int> { static std::string convert(int value); }; - template<> - struct StringMaker<long> { + template <> struct StringMaker<long> { static std::string convert(long value); }; - template<> - struct StringMaker<long long> { + template <> struct StringMaker<long long> { static std::string convert(long long value); }; - template<> - struct StringMaker<unsigned int> { + template <> struct StringMaker<unsigned int> { static std::string convert(unsigned int value); }; - template<> - struct StringMaker<unsigned long> { + template <> struct StringMaker<unsigned long> { static std::string convert(unsigned long value); }; - template<> - struct StringMaker<unsigned long long> { + template <> struct StringMaker<unsigned long long> { static std::string convert(unsigned long long value); }; - template<> - struct StringMaker<bool> { + template <> struct StringMaker<bool> { static std::string convert(bool b); }; - template<> - struct StringMaker<char> { + template <> struct StringMaker<char> { static std::string convert(char c); }; - template<> - struct StringMaker<signed char> { + template <> struct StringMaker<signed char> { static std::string convert(signed char c); }; - template<> - struct StringMaker<unsigned char> { + template <> struct StringMaker<unsigned char> { static std::string convert(unsigned char c); }; - template<> - struct StringMaker<std::nullptr_t> { + template <> struct StringMaker<std::nullptr_t> { static std::string convert(std::nullptr_t); }; - template<> - struct StringMaker<float> { + template <> struct StringMaker<float> { static std::string convert(float value); static int precision; }; - template<> - struct StringMaker<double> { + template <> struct StringMaker<double> { static std::string convert(double value); static int precision; }; - template <typename T> - struct StringMaker<T*> { - template <typename U> - static std::string convert(U* p) { + template <typename T> struct StringMaker<T*> { + template <typename U> static std::string convert(U* p) { if (p) { return ::Catch::Detail::rawMemoryToString(p); } else { @@ -1802,9 +2589,8 @@ } }; - template <typename R, typename C> - struct StringMaker<R C::*> { - static std::string convert(R C::* p) { + template <typename R, typename C> struct StringMaker<R C::*> { + static std::string convert(R C::*p) { if (p) { return ::Catch::Detail::rawMemoryToString(p); } else { @@ -1814,16 +2600,15 @@ }; #if defined(_MANAGED) - template <typename T> - struct StringMaker<T^> { - static std::string convert( T^ ref ) { + template <typename T> struct StringMaker<T ^> { + static std::string convert(T ^ ref) { return ::Catch::Detail::clrReferenceToString(ref); } }; #endif namespace Detail { - template<typename InputIterator, typename Sentinel = InputIterator> + template <typename InputIterator, typename Sentinel = InputIterator> std::string rangeToString(InputIterator first, Sentinel last) { ReusableStringStream rss; rss << "{ "; @@ -1835,30 +2620,27 @@ rss << " }"; return rss.str(); } - } + } // namespace Detail #ifdef __OBJC__ - template<> - struct StringMaker<NSString*> { - static std::string convert(NSString * nsstring) { + template <> struct StringMaker<NSString*> { + static std::string convert(NSString* nsstring) { if (!nsstring) return "nil"; return std::string("@") + [nsstring UTF8String]; } }; - template<> - struct StringMaker<NSObject*> { + template <> struct StringMaker<NSObject*> { static std::string convert(NSObject* nsObject) { return ::Catch::Detail::stringify([nsObject description]); } - }; namespace Detail { - inline std::string stringify( NSString* nsstring ) { - return StringMaker<NSString*>::convert( nsstring ); + inline std::string stringify(NSString* nsstring) { + return StringMaker<NSString*>::convert(nsstring); } - } // namespace Detail + } // namespace Detail #endif // __OBJC__ } // namespace Catch @@ -1868,37 +2650,33 @@ // This means that we do not bring in #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS) -# define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER -# define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER -# define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER -# define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER -# define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER +#define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER +#define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER +#define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER +#define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER +#define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER #endif // Separate std::pair specialization #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER) #include <utility> namespace Catch { - template<typename T1, typename T2> - struct StringMaker<std::pair<T1, T2> > { + template <typename T1, typename T2> struct StringMaker<std::pair<T1, T2>> { static std::string convert(const std::pair<T1, T2>& pair) { ReusableStringStream rss; - rss << "{ " - << ::Catch::Detail::stringify(pair.first) - << ", " - << ::Catch::Detail::stringify(pair.second) - << " }"; + rss << "{ " << ::Catch::Detail::stringify(pair.first) << ", " + << ::Catch::Detail::stringify(pair.second) << " }"; return rss.str(); } }; -} +} // namespace Catch #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER -#if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL) +#if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && \ + defined(CATCH_CONFIG_CPP17_OPTIONAL) #include <optional> namespace Catch { - template<typename T> - struct StringMaker<std::optional<T> > { + template <typename T> struct StringMaker<std::optional<T>> { static std::string convert(const std::optional<T>& optional) { ReusableStringStream rss; if (optional.has_value()) { @@ -1909,7 +2687,7 @@ return rss.str(); } }; -} +} // namespace Catch #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER // Separate std::tuple specialization @@ -1917,53 +2695,46 @@ #include <tuple> namespace Catch { namespace Detail { - template< - typename Tuple, - std::size_t N = 0, - bool = (N < std::tuple_size<Tuple>::value) - > - struct TupleElementPrinter { + template <typename Tuple, + std::size_t N = 0, + bool = (N < std::tuple_size<Tuple>::value)> + struct TupleElementPrinter { static void print(const Tuple& tuple, std::ostream& os) { os << (N ? ", " : " ") - << ::Catch::Detail::stringify(std::get<N>(tuple)); + << ::Catch::Detail::stringify(std::get<N>(tuple)); TupleElementPrinter<Tuple, N + 1>::print(tuple, os); } }; - template< - typename Tuple, - std::size_t N - > - struct TupleElementPrinter<Tuple, N, false> { + template <typename Tuple, std::size_t N> + struct TupleElementPrinter<Tuple, N, false> { static void print(const Tuple&, std::ostream&) {} }; - } + } // namespace Detail - template<typename ...Types> - struct StringMaker<std::tuple<Types...>> { + template <typename... Types> struct StringMaker<std::tuple<Types...>> { static std::string convert(const std::tuple<Types...>& tuple) { ReusableStringStream rss; rss << '{'; - Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get()); + Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, + rss.get()); rss << " }"; return rss.str(); } }; -} +} // namespace Catch #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER -#if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT) +#if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && \ + defined(CATCH_CONFIG_CPP17_VARIANT) #include <variant> namespace Catch { - template<> - struct StringMaker<std::monostate> { - static std::string convert(const std::monostate&) { - return "{ }"; - } + template <> struct StringMaker<std::monostate> { + static std::string convert(const std::monostate&) { return "{ }"; } }; - template<typename... Elements> + template <typename... Elements> struct StringMaker<std::variant<Elements...>> { static std::string convert(const std::variant<Elements...>& variant) { if (variant.valueless_by_exception()) { @@ -1973,12 +2744,11 @@ [](const auto& value) { return ::Catch::Detail::stringify(value); }, - variant - ); + variant); } } }; -} +} // namespace Catch #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER namespace Catch { @@ -1987,63 +2757,60 @@ using std::end; namespace detail { - template <typename...> - struct void_type { - using type = void; - }; + template <typename...> struct void_type { using type = void; }; template <typename T, typename = void> - struct is_range_impl : std::false_type { - }; + struct is_range_impl : std::false_type {}; template <typename T> - struct is_range_impl<T, typename void_type<decltype(begin(std::declval<T>()))>::type> : std::true_type { - }; + struct is_range_impl< + T, + typename void_type<decltype(begin(std::declval<T>()))>::type> + : std::true_type {}; } // namespace detail - template <typename T> - struct is_range : detail::is_range_impl<T> { - }; + template <typename T> struct is_range : detail::is_range_impl<T> {}; #if defined(_MANAGED) // Managed types are never ranges - template <typename T> - struct is_range<T^> { + template <typename T> struct is_range<T ^> { static const bool value = false; }; #endif - template<typename Range> - std::string rangeToString( Range const& range ) { - return ::Catch::Detail::rangeToString( begin( range ), end( range ) ); + template <typename Range> std::string rangeToString(Range const& range) { + return ::Catch::Detail::rangeToString(begin(range), end(range)); } // Handle vector<bool> specially - template<typename Allocator> - std::string rangeToString( std::vector<bool, Allocator> const& v ) { + template <typename Allocator> + std::string rangeToString(std::vector<bool, Allocator> const& v) { ReusableStringStream rss; rss << "{ "; bool first = true; - for( bool b : v ) { - if( first ) + for (bool b : v) { + if (first) first = false; else rss << ", "; - rss << ::Catch::Detail::stringify( b ); + rss << ::Catch::Detail::stringify(b); } rss << " }"; return rss.str(); } - template<typename R> - struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> { - static std::string convert( R const& range ) { - return rangeToString( range ); + template <typename R> + struct StringMaker< + R, + typename std::enable_if< + is_range<R>::value && + !::Catch::Detail::IsStreamInsertable<R>::value>::type> { + static std::string convert(R const& range) { + return rangeToString(range); } }; - template <typename T, int SZ> - struct StringMaker<T[SZ]> { - static std::string convert(T const(&arr)[SZ]) { + template <typename T, int SZ> struct StringMaker<T[SZ]> { + static std::string convert(T const (&arr)[SZ]) { return rangeToString(arr); } }; @@ -2058,72 +2825,60 @@ namespace Catch { -template <class Ratio> -struct ratio_string { - static std::string symbol(); -}; + template <class Ratio> struct ratio_string { static std::string symbol(); }; -template <class Ratio> -std::string ratio_string<Ratio>::symbol() { - Catch::ReusableStringStream rss; - rss << '[' << Ratio::num << '/' - << Ratio::den << ']'; - return rss.str(); -} -template <> -struct ratio_string<std::atto> { - static std::string symbol(); -}; -template <> -struct ratio_string<std::femto> { - static std::string symbol(); -}; -template <> -struct ratio_string<std::pico> { - static std::string symbol(); -}; -template <> -struct ratio_string<std::nano> { - static std::string symbol(); -}; -template <> -struct ratio_string<std::micro> { - static std::string symbol(); -}; -template <> -struct ratio_string<std::milli> { - static std::string symbol(); -}; + template <class Ratio> std::string ratio_string<Ratio>::symbol() { + Catch::ReusableStringStream rss; + rss << '[' << Ratio::num << '/' << Ratio::den << ']'; + return rss.str(); + } + template <> struct ratio_string<std::atto> { static std::string symbol(); }; + template <> struct ratio_string<std::femto> { + static std::string symbol(); + }; + template <> struct ratio_string<std::pico> { static std::string symbol(); }; + template <> struct ratio_string<std::nano> { static std::string symbol(); }; + template <> struct ratio_string<std::micro> { + static std::string symbol(); + }; + template <> struct ratio_string<std::milli> { + static std::string symbol(); + }; //////////// // std::chrono::duration specializations - template<typename Value, typename Ratio> + template <typename Value, typename Ratio> struct StringMaker<std::chrono::duration<Value, Ratio>> { - static std::string convert(std::chrono::duration<Value, Ratio> const& duration) { + static std::string + convert(std::chrono::duration<Value, Ratio> const& duration) { ReusableStringStream rss; - rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's'; + rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() + << 's'; return rss.str(); } }; - template<typename Value> + template <typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> { - static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) { + static std::string + convert(std::chrono::duration<Value, std::ratio<1>> const& duration) { ReusableStringStream rss; rss << duration.count() << " s"; return rss.str(); } }; - template<typename Value> + template <typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> { - static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) { + static std::string + convert(std::chrono::duration<Value, std::ratio<60>> const& duration) { ReusableStringStream rss; rss << duration.count() << " m"; return rss.str(); } }; - template<typename Value> + template <typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> { - static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) { + static std::string convert( + std::chrono::duration<Value, std::ratio<3600>> const& duration) { ReusableStringStream rss; rss << duration.count() << " h"; return rss.str(); @@ -2132,17 +2887,23 @@ //////////// // std::chrono::time_point specialization - // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock> - template<typename Clock, typename Duration> + // Generic time_point cannot be specialized, only + // std::chrono::time_point<system_clock> + template <typename Clock, typename Duration> struct StringMaker<std::chrono::time_point<Clock, Duration>> { - static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) { - return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch"; + static std::string + convert(std::chrono::time_point<Clock, Duration> const& time_point) { + return ::Catch::Detail::stringify(time_point.time_since_epoch()) + + " since epoch"; } }; // std::chrono::time_point<system_clock> specialization - template<typename Duration> - struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> { - static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) { + template <typename Duration> + struct StringMaker< + std::chrono::time_point<std::chrono::system_clock, Duration>> { + static std::string + convert(std::chrono::time_point<std::chrono::system_clock, + Duration> const& time_point) { auto converted = std::chrono::system_clock::to_time_t(time_point); #ifdef _MSC_VER @@ -2154,7 +2915,7 @@ auto const timeStampSize = sizeof("2017-01-16T17:06:45Z"); char timeStamp[timeStampSize]; - const char * const fmt = "%Y-%m-%dT%H:%M:%SZ"; + const char* const fmt = "%Y-%m-%dT%H:%M:%SZ"; #ifdef _MSC_VER std::strftime(timeStamp, timeStampSize, fmt, &timeInfo); @@ -2164,20 +2925,25 @@ return std::string(timeStamp); } }; -} +} // namespace Catch #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER -#define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \ -namespace Catch { \ - template<> struct StringMaker<enumName> { \ - static std::string convert( enumName value ) { \ - static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \ - return static_cast<std::string>(enumInfo.lookup( static_cast<int>( value ) )); \ - } \ - }; \ -} +#define INTERNAL_CATCH_REGISTER_ENUM(enumName, ...) \ + namespace Catch { \ + template <> struct StringMaker<enumName> { \ + static std::string convert(enumName value) { \ + static const auto& enumInfo = \ + ::Catch::getMutableRegistryHub() \ + .getMutableEnumValuesRegistry() \ + .registerEnum(#enumName, #__VA_ARGS__, {__VA_ARGS__}); \ + return static_cast<std::string>( \ + enumInfo.lookup(static_cast<int>(value))); \ + } \ + }; \ + } -#define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ ) +#define CATCH_REGISTER_ENUM(enumName, ...) \ + INTERNAL_CATCH_REGISTER_ENUM(enumName, __VA_ARGS__) #ifdef _MSC_VER #pragma warning(pop) @@ -2188,11 +2954,13 @@ #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable:4389) // '==' : signed/unsigned mismatch -#pragma warning(disable:4018) // more "signed/unsigned mismatch" -#pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform) -#pragma warning(disable:4180) // qualifier applied to function type has no meaning -#pragma warning(disable:4800) // Forcing result to true or false +#pragma warning(disable : 4389) // '==' : signed/unsigned mismatch +#pragma warning(disable : 4018) // more "signed/unsigned mismatch" +#pragma warning(disable : 4312) // Converting int to T* using reinterpret_cast + // (issue on x64 platform) +#pragma warning( \ + disable : 4180) // qualifier applied to function type has no meaning +#pragma warning(disable : 4800) // Forcing result to true or false #endif namespace Catch { @@ -2200,223 +2968,249 @@ struct ITransientExpression { auto isBinaryExpression() const -> bool { return m_isBinaryExpression; } auto getResult() const -> bool { return m_result; } - virtual void streamReconstructedExpression( std::ostream &os ) const = 0; + virtual void streamReconstructedExpression(std::ostream& os) const = 0; - ITransientExpression( bool isBinaryExpression, bool result ) - : m_isBinaryExpression( isBinaryExpression ), - m_result( result ) - {} + ITransientExpression(bool isBinaryExpression, bool result) : + m_isBinaryExpression(isBinaryExpression), m_result(result) {} - // We don't actually need a virtual destructor, but many static analysers - // complain if it's not here :-( + // We don't actually need a virtual destructor, but many static + // analysers complain if it's not here :-( virtual ~ITransientExpression(); bool m_isBinaryExpression; bool m_result; - }; - void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ); + void formatReconstructedExpression(std::ostream& os, + std::string const& lhs, + StringRef op, + std::string const& rhs); - template<typename LhsT, typename RhsT> - class BinaryExpr : public ITransientExpression { + template <typename LhsT, typename RhsT> + class BinaryExpr : public ITransientExpression { LhsT m_lhs; StringRef m_op; RhsT m_rhs; - void streamReconstructedExpression( std::ostream &os ) const override { - formatReconstructedExpression - ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) ); + void streamReconstructedExpression(std::ostream& os) const override { + formatReconstructedExpression(os, + Catch::Detail::stringify(m_lhs), + m_op, + Catch::Detail::stringify(m_rhs)); } public: - BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs ) - : ITransientExpression{ true, comparisonResult }, - m_lhs( lhs ), - m_op( op ), - m_rhs( rhs ) - {} + BinaryExpr(bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs) : + ITransientExpression{true, comparisonResult}, + m_lhs(lhs), + m_op(op), + m_rhs(rhs) {} - template<typename T> - auto operator && ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { - static_assert(always_false<T>::value, - "chained comparisons are not supported inside assertions, " - "wrap the expression inside parentheses, or decompose it"); + template <typename T> + auto operator&&(T) const -> BinaryExpr<LhsT, RhsT const&> const { + static_assert( + always_false<T>::value, + "chained comparisons are not supported inside assertions, " + "wrap the expression inside parentheses, or decompose it"); } - template<typename T> - auto operator || ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { - static_assert(always_false<T>::value, - "chained comparisons are not supported inside assertions, " - "wrap the expression inside parentheses, or decompose it"); + template <typename T> + auto operator||(T) const -> BinaryExpr<LhsT, RhsT const&> const { + static_assert( + always_false<T>::value, + "chained comparisons are not supported inside assertions, " + "wrap the expression inside parentheses, or decompose it"); } - template<typename T> - auto operator == ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { - static_assert(always_false<T>::value, - "chained comparisons are not supported inside assertions, " - "wrap the expression inside parentheses, or decompose it"); + template <typename T> + auto operator==(T) const -> BinaryExpr<LhsT, RhsT const&> const { + static_assert( + always_false<T>::value, + "chained comparisons are not supported inside assertions, " + "wrap the expression inside parentheses, or decompose it"); } - template<typename T> - auto operator != ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { - static_assert(always_false<T>::value, - "chained comparisons are not supported inside assertions, " - "wrap the expression inside parentheses, or decompose it"); + template <typename T> + auto operator!=(T) const -> BinaryExpr<LhsT, RhsT const&> const { + static_assert( + always_false<T>::value, + "chained comparisons are not supported inside assertions, " + "wrap the expression inside parentheses, or decompose it"); } - template<typename T> - auto operator > ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { - static_assert(always_false<T>::value, - "chained comparisons are not supported inside assertions, " - "wrap the expression inside parentheses, or decompose it"); + template <typename T> + auto operator>(T) const -> BinaryExpr<LhsT, RhsT const&> const { + static_assert( + always_false<T>::value, + "chained comparisons are not supported inside assertions, " + "wrap the expression inside parentheses, or decompose it"); } - template<typename T> - auto operator < ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { - static_assert(always_false<T>::value, - "chained comparisons are not supported inside assertions, " - "wrap the expression inside parentheses, or decompose it"); + template <typename T> + auto operator<(T) const -> BinaryExpr<LhsT, RhsT const&> const { + static_assert( + always_false<T>::value, + "chained comparisons are not supported inside assertions, " + "wrap the expression inside parentheses, or decompose it"); } - template<typename T> - auto operator >= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { - static_assert(always_false<T>::value, - "chained comparisons are not supported inside assertions, " - "wrap the expression inside parentheses, or decompose it"); + template <typename T> + auto operator>=(T) const -> BinaryExpr<LhsT, RhsT const&> const { + static_assert( + always_false<T>::value, + "chained comparisons are not supported inside assertions, " + "wrap the expression inside parentheses, or decompose it"); } - template<typename T> - auto operator <= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const { - static_assert(always_false<T>::value, - "chained comparisons are not supported inside assertions, " - "wrap the expression inside parentheses, or decompose it"); + template <typename T> + auto operator<=(T) const -> BinaryExpr<LhsT, RhsT const&> const { + static_assert( + always_false<T>::value, + "chained comparisons are not supported inside assertions, " + "wrap the expression inside parentheses, or decompose it"); } }; - template<typename LhsT> - class UnaryExpr : public ITransientExpression { + template <typename LhsT> class UnaryExpr : public ITransientExpression { LhsT m_lhs; - void streamReconstructedExpression( std::ostream &os ) const override { - os << Catch::Detail::stringify( m_lhs ); + void streamReconstructedExpression(std::ostream& os) const override { + os << Catch::Detail::stringify(m_lhs); } public: - explicit UnaryExpr( LhsT lhs ) - : ITransientExpression{ false, static_cast<bool>(lhs) }, - m_lhs( lhs ) - {} + explicit UnaryExpr(LhsT lhs) : + ITransientExpression{false, static_cast<bool>(lhs)}, m_lhs(lhs) {} }; - // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int) - template<typename LhsT, typename RhsT> - auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); } - template<typename T> - auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); } - template<typename T> - auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); } - template<typename T> - auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; } - template<typename T> - auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; } + // Specialised comparison functions to handle equality comparisons between + // ints and pointers (NULL deduces as an int) + template <typename LhsT, typename RhsT> + auto compareEqual(LhsT const& lhs, RhsT const& rhs) -> bool { + return static_cast<bool>(lhs == rhs); + } + template <typename T> auto compareEqual(T* const& lhs, int rhs) -> bool { + return lhs == reinterpret_cast<void const*>(rhs); + } + template <typename T> auto compareEqual(T* const& lhs, long rhs) -> bool { + return lhs == reinterpret_cast<void const*>(rhs); + } + template <typename T> auto compareEqual(int lhs, T* const& rhs) -> bool { + return reinterpret_cast<void const*>(lhs) == rhs; + } + template <typename T> auto compareEqual(long lhs, T* const& rhs) -> bool { + return reinterpret_cast<void const*>(lhs) == rhs; + } - template<typename LhsT, typename RhsT> - auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); } - template<typename T> - auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); } - template<typename T> - auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); } - template<typename T> - auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; } - template<typename T> - auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; } + template <typename LhsT, typename RhsT> + auto compareNotEqual(LhsT const& lhs, RhsT&& rhs) -> bool { + return static_cast<bool>(lhs != rhs); + } + template <typename T> auto compareNotEqual(T* const& lhs, int rhs) -> bool { + return lhs != reinterpret_cast<void const*>(rhs); + } + template <typename T> + auto compareNotEqual(T* const& lhs, long rhs) -> bool { + return lhs != reinterpret_cast<void const*>(rhs); + } + template <typename T> auto compareNotEqual(int lhs, T* const& rhs) -> bool { + return reinterpret_cast<void const*>(lhs) != rhs; + } + template <typename T> + auto compareNotEqual(long lhs, T* const& rhs) -> bool { + return reinterpret_cast<void const*>(lhs) != rhs; + } - template<typename LhsT> - class ExprLhs { + template <typename LhsT> class ExprLhs { LhsT m_lhs; + public: - explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {} + explicit ExprLhs(LhsT lhs) : m_lhs(lhs) {} - template<typename RhsT> - auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { - return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs }; + template <typename RhsT> + auto operator==(RhsT const& rhs) + -> BinaryExpr<LhsT, RhsT const&> const { + return {compareEqual(m_lhs, rhs), m_lhs, "==", rhs}; } - auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const { - return { m_lhs == rhs, m_lhs, "==", rhs }; + auto operator==(bool rhs) -> BinaryExpr<LhsT, bool> const { + return {m_lhs == rhs, m_lhs, "==", rhs}; } - template<typename RhsT> - auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { - return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs }; + template <typename RhsT> + auto operator!=(RhsT const& rhs) + -> BinaryExpr<LhsT, RhsT const&> const { + return {compareNotEqual(m_lhs, rhs), m_lhs, "!=", rhs}; } - auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const { - return { m_lhs != rhs, m_lhs, "!=", rhs }; + auto operator!=(bool rhs) -> BinaryExpr<LhsT, bool> const { + return {m_lhs != rhs, m_lhs, "!=", rhs}; } - template<typename RhsT> - auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { - return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs }; - } - template<typename RhsT> - auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { - return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs }; - } - template<typename RhsT> - auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { - return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs }; - } - template<typename RhsT> - auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { - return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs }; + template <typename RhsT> + auto operator>(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const { + return {static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs}; } template <typename RhsT> - auto operator | (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const { - return { static_cast<bool>(m_lhs | rhs), m_lhs, "|", rhs }; + auto operator<(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const { + return {static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs}; } template <typename RhsT> - auto operator & (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const { - return { static_cast<bool>(m_lhs & rhs), m_lhs, "&", rhs }; + auto operator>=(RhsT const& rhs) + -> BinaryExpr<LhsT, RhsT const&> const { + return {static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs}; } template <typename RhsT> - auto operator ^ (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const { - return { static_cast<bool>(m_lhs ^ rhs), m_lhs, "^", rhs }; + auto operator<=(RhsT const& rhs) + -> BinaryExpr<LhsT, RhsT const&> const { + return {static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs}; + } + template <typename RhsT> + auto operator|(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const { + return {static_cast<bool>(m_lhs | rhs), m_lhs, "|", rhs}; + } + template <typename RhsT> + auto operator&(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const { + return {static_cast<bool>(m_lhs & rhs), m_lhs, "&", rhs}; + } + template <typename RhsT> + auto operator^(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const { + return {static_cast<bool>(m_lhs ^ rhs), m_lhs, "^", rhs}; } - template<typename RhsT> - auto operator && ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const { - static_assert(always_false<RhsT>::value, - "operator&& is not supported inside assertions, " - "wrap the expression inside parentheses, or decompose it"); + template <typename RhsT> + auto operator&&(RhsT const&) -> BinaryExpr<LhsT, RhsT const&> const { + static_assert( + always_false<RhsT>::value, + "operator&& is not supported inside assertions, " + "wrap the expression inside parentheses, or decompose it"); } - template<typename RhsT> - auto operator || ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const { - static_assert(always_false<RhsT>::value, - "operator|| is not supported inside assertions, " - "wrap the expression inside parentheses, or decompose it"); + template <typename RhsT> + auto operator||(RhsT const&) -> BinaryExpr<LhsT, RhsT const&> const { + static_assert( + always_false<RhsT>::value, + "operator|| is not supported inside assertions, " + "wrap the expression inside parentheses, or decompose it"); } auto makeUnaryExpr() const -> UnaryExpr<LhsT> { - return UnaryExpr<LhsT>{ m_lhs }; + return UnaryExpr<LhsT>{m_lhs}; } }; - void handleExpression( ITransientExpression const& expr ); + void handleExpression(ITransientExpression const& expr); - template<typename T> - void handleExpression( ExprLhs<T> const& expr ) { - handleExpression( expr.makeUnaryExpr() ); + template <typename T> void handleExpression(ExprLhs<T> const& expr) { + handleExpression(expr.makeUnaryExpr()); } struct Decomposer { - template<typename T> - auto operator <= ( T const& lhs ) -> ExprLhs<T const&> { - return ExprLhs<T const&>{ lhs }; + template <typename T> + auto operator<=(T const& lhs) -> ExprLhs<T const&> { + return ExprLhs<T const&>{lhs}; } - auto operator <=( bool value ) -> ExprLhs<bool> { - return ExprLhs<bool>{ value }; + auto operator<=(bool value) -> ExprLhs<bool> { + return ExprLhs<bool>{value}; } }; @@ -2457,49 +3251,47 @@ virtual ~IResultCapture(); - virtual bool sectionStarted( SectionInfo const& sectionInfo, - Counts& assertions ) = 0; - virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0; - virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0; + virtual bool sectionStarted(SectionInfo const& sectionInfo, + Counts& assertions) = 0; + virtual void sectionEnded(SectionEndInfo const& endInfo) = 0; + virtual void sectionEndedEarly(SectionEndInfo const& endInfo) = 0; - virtual auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0; + virtual auto acquireGeneratorTracker(StringRef generatorName, + SourceLineInfo const& lineInfo) + -> IGeneratorTracker& = 0; #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) - virtual void benchmarkPreparing( std::string const& name ) = 0; - virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0; - virtual void benchmarkEnded( BenchmarkStats<> const& stats ) = 0; - virtual void benchmarkFailed( std::string const& error ) = 0; + virtual void benchmarkPreparing(std::string const& name) = 0; + virtual void benchmarkStarting(BenchmarkInfo const& info) = 0; + virtual void benchmarkEnded(BenchmarkStats<> const& stats) = 0; + virtual void benchmarkFailed(std::string const& error) = 0; #endif // CATCH_CONFIG_ENABLE_BENCHMARKING - virtual void pushScopedMessage( MessageInfo const& message ) = 0; - virtual void popScopedMessage( MessageInfo const& message ) = 0; + virtual void pushScopedMessage(MessageInfo const& message) = 0; + virtual void popScopedMessage(MessageInfo const& message) = 0; - virtual void emplaceUnscopedMessage( MessageBuilder const& builder ) = 0; + virtual void emplaceUnscopedMessage(MessageBuilder const& builder) = 0; - virtual void handleFatalErrorCondition( StringRef message ) = 0; + virtual void handleFatalErrorCondition(StringRef message) = 0; - virtual void handleExpr - ( AssertionInfo const& info, - ITransientExpression const& expr, - AssertionReaction& reaction ) = 0; - virtual void handleMessage - ( AssertionInfo const& info, - ResultWas::OfType resultType, - StringRef const& message, - AssertionReaction& reaction ) = 0; - virtual void handleUnexpectedExceptionNotThrown - ( AssertionInfo const& info, - AssertionReaction& reaction ) = 0; - virtual void handleUnexpectedInflightException - ( AssertionInfo const& info, - std::string const& message, - AssertionReaction& reaction ) = 0; - virtual void handleIncomplete - ( AssertionInfo const& info ) = 0; - virtual void handleNonExpr - ( AssertionInfo const &info, - ResultWas::OfType resultType, - AssertionReaction &reaction ) = 0; + virtual void handleExpr(AssertionInfo const& info, + ITransientExpression const& expr, + AssertionReaction& reaction) = 0; + virtual void handleMessage(AssertionInfo const& info, + ResultWas::OfType resultType, + StringRef const& message, + AssertionReaction& reaction) = 0; + virtual void + handleUnexpectedExceptionNotThrown(AssertionInfo const& info, + AssertionReaction& reaction) = 0; + virtual void + handleUnexpectedInflightException(AssertionInfo const& info, + std::string const& message, + AssertionReaction& reaction) = 0; + virtual void handleIncomplete(AssertionInfo const& info) = 0; + virtual void handleNonExpr(AssertionInfo const& info, + ResultWas::OfType resultType, + AssertionReaction& reaction) = 0; virtual bool lastAssertionPassed() = 0; virtual void assertionPassed() = 0; @@ -2511,12 +3303,12 @@ }; IResultCapture& getResultCapture(); -} +} // namespace Catch // end catch_interfaces_capture.h namespace Catch { - struct TestFailureException{}; + struct TestFailureException {}; struct AssertionResultData; struct IResultCapture; class RunContext; @@ -2528,14 +3320,16 @@ ITransientExpression const* m_transientExpression = nullptr; bool m_isNegated; + public: - LazyExpression( bool isNegated ); - LazyExpression( LazyExpression const& other ); - LazyExpression& operator = ( LazyExpression const& ) = delete; + LazyExpression(bool isNegated); + LazyExpression(LazyExpression const& other); + LazyExpression& operator=(LazyExpression const&) = delete; explicit operator bool() const; - friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&; + friend auto operator<<(std::ostream& os, LazyExpression const& lazyExpr) + -> std::ostream&; }; struct AssertionReaction { @@ -2550,24 +3344,23 @@ IResultCapture& m_resultCapture; public: - AssertionHandler - ( StringRef const& macroName, - SourceLineInfo const& lineInfo, - StringRef capturedExpression, - ResultDisposition::Flags resultDisposition ); + AssertionHandler(StringRef const& macroName, + SourceLineInfo const& lineInfo, + StringRef capturedExpression, + ResultDisposition::Flags resultDisposition); ~AssertionHandler() { - if ( !m_completed ) { - m_resultCapture.handleIncomplete( m_assertionInfo ); + if (!m_completed) { + m_resultCapture.handleIncomplete(m_assertionInfo); } } - template<typename T> - void handleExpr( ExprLhs<T> const& expr ) { - handleExpr( expr.makeUnaryExpr() ); + template <typename T> void handleExpr(ExprLhs<T> const& expr) { + handleExpr(expr.makeUnaryExpr()); } - void handleExpr( ITransientExpression const& expr ); + void handleExpr(ITransientExpression const& expr); - void handleMessage(ResultWas::OfType resultType, StringRef const& message); + void handleMessage(ResultWas::OfType resultType, + StringRef const& message); void handleExceptionThrownAsExpected(); void handleUnexpectedExceptionNotThrown(); @@ -2582,7 +3375,9 @@ auto allowThrows() const -> bool; }; - void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ); + void handleExceptionMatchExpr(AssertionHandler& handler, + std::string const& str, + StringRef const& matcherString); } // namespace Catch @@ -2595,9 +3390,9 @@ namespace Catch { struct MessageInfo { - MessageInfo( StringRef const& _macroName, - SourceLineInfo const& _lineInfo, - ResultWas::OfType _type ); + MessageInfo(StringRef const& _macroName, + SourceLineInfo const& _lineInfo, + ResultWas::OfType _type); StringRef macroName; std::string message; @@ -2605,16 +3400,16 @@ ResultWas::OfType type; unsigned int sequence; - bool operator == ( MessageInfo const& other ) const; - bool operator < ( MessageInfo const& other ) const; + bool operator==(MessageInfo const& other) const; + bool operator<(MessageInfo const& other) const; + private: static unsigned int globalCount; }; struct MessageStream { - template<typename T> - MessageStream& operator << ( T const& value ) { + template <typename T> MessageStream& operator<<(T const& value) { m_stream << value; return *this; } @@ -2623,12 +3418,11 @@ }; struct MessageBuilder : MessageStream { - MessageBuilder( StringRef const& macroName, - SourceLineInfo const& lineInfo, - ResultWas::OfType type ); + MessageBuilder(StringRef const& macroName, + SourceLineInfo const& lineInfo, + ResultWas::OfType type); - template<typename T> - MessageBuilder& operator << ( T const& value ) { + template <typename T> MessageBuilder& operator<<(T const& value) { m_stream << value; return *this; } @@ -2638,9 +3432,9 @@ class ScopedMessage { public: - explicit ScopedMessage( MessageBuilder const& builder ); - ScopedMessage( ScopedMessage& duplicate ) = delete; - ScopedMessage( ScopedMessage&& old ); + explicit ScopedMessage(MessageBuilder const& builder); + ScopedMessage(ScopedMessage& duplicate) = delete; + ScopedMessage(ScopedMessage&& old); ~ScopedMessage(); MessageInfo m_info; @@ -2651,21 +3445,24 @@ std::vector<MessageInfo> m_messages; IResultCapture& m_resultCapture = getResultCapture(); size_t m_captured = 0; + public: - Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ); + Capturer(StringRef macroName, + SourceLineInfo const& lineInfo, + ResultWas::OfType resultType, + StringRef names); ~Capturer(); - void captureValue( size_t index, std::string const& value ); + void captureValue(size_t index, std::string const& value); - template<typename T> - void captureValues( size_t index, T const& value ) { - captureValue( index, Catch::Detail::stringify( value ) ); + template <typename T> void captureValues(size_t index, T const& value) { + captureValue(index, Catch::Detail::stringify(value)); } - template<typename T, typename... Ts> - void captureValues( size_t index, T const& value, Ts const&... values ) { - captureValue( index, Catch::Detail::stringify(value) ); - captureValues( index+1, values... ); + template <typename T, typename... Ts> + void captureValues(size_t index, T const& value, Ts const&... values) { + captureValue(index, Catch::Detail::stringify(value)); + captureValues(index + 1, values...); } }; @@ -2675,141 +3472,185 @@ #if !defined(CATCH_CONFIG_DISABLE) #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION) - #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__ +#define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__ #else - #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION" +#define CATCH_INTERNAL_STRINGIFY(...) \ + "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION" #endif -#if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) +#if defined(CATCH_CONFIG_FAST_COMPILE) || \ + defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) /////////////////////////////////////////////////////////////////////////////// // Another way to speed-up compilation is to omit local try-catch for REQUIRE* // macros. #define INTERNAL_CATCH_TRY -#define INTERNAL_CATCH_CATCH( capturer ) +#define INTERNAL_CATCH_CATCH(capturer) #else // CATCH_CONFIG_FAST_COMPILE #define INTERNAL_CATCH_TRY try -#define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); } +#define INTERNAL_CATCH_CATCH(handler) \ + catch (...) { \ + handler.handleUnexpectedInflightException(); \ + } #endif -#define INTERNAL_CATCH_REACT( handler ) handler.complete(); +#define INTERNAL_CATCH_REACT(handler) handler.complete(); /////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \ - do { \ - CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \ - Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \ - INTERNAL_CATCH_TRY { \ - CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ - CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ - catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \ - CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ - } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \ - INTERNAL_CATCH_REACT( catchAssertionHandler ) \ - } while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) ) +#define INTERNAL_CATCH_TEST(macroName, resultDisposition, ...) \ + do { \ + CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \ + Catch::AssertionHandler catchAssertionHandler( \ + macroName##_catch_sr, \ + CATCH_INTERNAL_LINEINFO, \ + CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), \ + resultDisposition); \ + INTERNAL_CATCH_TRY { \ + CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ + CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ + catchAssertionHandler.handleExpr(Catch::Decomposer() <= \ + __VA_ARGS__); \ + CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ + } \ + INTERNAL_CATCH_CATCH(catchAssertionHandler) \ + INTERNAL_CATCH_REACT(catchAssertionHandler) \ + } while ((void)0, (false) && static_cast<bool>(!!(__VA_ARGS__))) /////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \ - INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \ - if( Catch::getResultCapture().lastAssertionPassed() ) +#define INTERNAL_CATCH_IF(macroName, resultDisposition, ...) \ + INTERNAL_CATCH_TEST(macroName, resultDisposition, __VA_ARGS__); \ + if (Catch::getResultCapture().lastAssertionPassed()) /////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \ - INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \ - if( !Catch::getResultCapture().lastAssertionPassed() ) +#define INTERNAL_CATCH_ELSE(macroName, resultDisposition, ...) \ + INTERNAL_CATCH_TEST(macroName, resultDisposition, __VA_ARGS__); \ + if (!Catch::getResultCapture().lastAssertionPassed()) /////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \ - do { \ - Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \ - try { \ - static_cast<void>(__VA_ARGS__); \ - catchAssertionHandler.handleExceptionNotThrownAsExpected(); \ - } \ - catch( ... ) { \ - catchAssertionHandler.handleUnexpectedInflightException(); \ - } \ - INTERNAL_CATCH_REACT( catchAssertionHandler ) \ - } while( false ) +#define INTERNAL_CATCH_NO_THROW(macroName, resultDisposition, ...) \ + do { \ + Catch::AssertionHandler catchAssertionHandler( \ + macroName##_catch_sr, \ + CATCH_INTERNAL_LINEINFO, \ + CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), \ + resultDisposition); \ + try { \ + static_cast<void>(__VA_ARGS__); \ + catchAssertionHandler.handleExceptionNotThrownAsExpected(); \ + } catch (...) { \ + catchAssertionHandler.handleUnexpectedInflightException(); \ + } \ + INTERNAL_CATCH_REACT(catchAssertionHandler) \ + } while (false) /////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \ - do { \ - Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \ - if( catchAssertionHandler.allowThrows() ) \ - try { \ - static_cast<void>(__VA_ARGS__); \ - catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ - } \ - catch( ... ) { \ - catchAssertionHandler.handleExceptionThrownAsExpected(); \ - } \ - else \ - catchAssertionHandler.handleThrowingCallSkipped(); \ - INTERNAL_CATCH_REACT( catchAssertionHandler ) \ - } while( false ) +#define INTERNAL_CATCH_THROWS(macroName, resultDisposition, ...) \ + do { \ + Catch::AssertionHandler catchAssertionHandler( \ + macroName##_catch_sr, \ + CATCH_INTERNAL_LINEINFO, \ + CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), \ + resultDisposition); \ + if (catchAssertionHandler.allowThrows()) \ + try { \ + static_cast<void>(__VA_ARGS__); \ + catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ + } catch (...) { \ + catchAssertionHandler.handleExceptionThrownAsExpected(); \ + } \ + else \ + catchAssertionHandler.handleThrowingCallSkipped(); \ + INTERNAL_CATCH_REACT(catchAssertionHandler) \ + } while (false) /////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \ - do { \ - Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \ - if( catchAssertionHandler.allowThrows() ) \ - try { \ - static_cast<void>(expr); \ - catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ - } \ - catch( exceptionType const& ) { \ - catchAssertionHandler.handleExceptionThrownAsExpected(); \ - } \ - catch( ... ) { \ - catchAssertionHandler.handleUnexpectedInflightException(); \ - } \ - else \ - catchAssertionHandler.handleThrowingCallSkipped(); \ - INTERNAL_CATCH_REACT( catchAssertionHandler ) \ - } while( false ) +#define INTERNAL_CATCH_THROWS_AS( \ + macroName, exceptionType, resultDisposition, expr) \ + do { \ + Catch::AssertionHandler catchAssertionHandler( \ + macroName##_catch_sr, \ + CATCH_INTERNAL_LINEINFO, \ + CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY( \ + exceptionType), \ + resultDisposition); \ + if (catchAssertionHandler.allowThrows()) \ + try { \ + static_cast<void>(expr); \ + catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ + } catch (exceptionType const&) { \ + catchAssertionHandler.handleExceptionThrownAsExpected(); \ + } catch (...) { \ + catchAssertionHandler.handleUnexpectedInflightException(); \ + } \ + else \ + catchAssertionHandler.handleThrowingCallSkipped(); \ + INTERNAL_CATCH_REACT(catchAssertionHandler) \ + } while (false) /////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \ - do { \ - Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \ - catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \ - INTERNAL_CATCH_REACT( catchAssertionHandler ) \ - } while( false ) +#define INTERNAL_CATCH_MSG(macroName, messageType, resultDisposition, ...) \ + do { \ + Catch::AssertionHandler catchAssertionHandler(macroName##_catch_sr, \ + CATCH_INTERNAL_LINEINFO, \ + Catch::StringRef(), \ + resultDisposition); \ + catchAssertionHandler.handleMessage( \ + messageType, \ + (Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop()) \ + .m_stream.str()); \ + INTERNAL_CATCH_REACT(catchAssertionHandler) \ + } while (false) /////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \ - auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \ - varName.captureValues( 0, __VA_ARGS__ ) +#define INTERNAL_CATCH_CAPTURE(varName, macroName, ...) \ + auto varName = Catch::Capturer(macroName, \ + CATCH_INTERNAL_LINEINFO, \ + Catch::ResultWas::Info, \ + #__VA_ARGS__); \ + varName.captureValues(0, __VA_ARGS__) /////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_INFO( macroName, log ) \ - Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log ); +#define INTERNAL_CATCH_INFO(macroName, log) \ + Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME(scopedMessage)( \ + Catch::MessageBuilder(macroName##_catch_sr, \ + CATCH_INTERNAL_LINEINFO, \ + Catch::ResultWas::Info) \ + << log); /////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \ - Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log ) +#define INTERNAL_CATCH_UNSCOPED_INFO(macroName, log) \ + Catch::getResultCapture().emplaceUnscopedMessage( \ + Catch::MessageBuilder(macroName##_catch_sr, \ + CATCH_INTERNAL_LINEINFO, \ + Catch::ResultWas::Info) \ + << log) /////////////////////////////////////////////////////////////////////////////// // Although this is matcher-based, it can be used with just a string -#define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \ - do { \ - Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ - if( catchAssertionHandler.allowThrows() ) \ - try { \ - static_cast<void>(__VA_ARGS__); \ - catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ - } \ - catch( ... ) { \ - Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \ - } \ - else \ - catchAssertionHandler.handleThrowingCallSkipped(); \ - INTERNAL_CATCH_REACT( catchAssertionHandler ) \ - } while( false ) +#define INTERNAL_CATCH_THROWS_STR_MATCHES( \ + macroName, resultDisposition, matcher, ...) \ + do { \ + Catch::AssertionHandler catchAssertionHandler( \ + macroName##_catch_sr, \ + CATCH_INTERNAL_LINEINFO, \ + CATCH_INTERNAL_STRINGIFY( \ + __VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), \ + resultDisposition); \ + if (catchAssertionHandler.allowThrows()) \ + try { \ + static_cast<void>(__VA_ARGS__); \ + catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ + } catch (...) { \ + Catch::handleExceptionMatchExpr( \ + catchAssertionHandler, matcher, #matcher##_catch_sr); \ + } \ + else \ + catchAssertionHandler.handleThrowingCallSkipped(); \ + INTERNAL_CATCH_REACT(catchAssertionHandler) \ + } while (false) #endif // CATCH_CONFIG_DISABLE @@ -2825,8 +3666,8 @@ namespace Catch { struct Counts { - Counts operator - ( Counts const& other ) const; - Counts& operator += ( Counts const& other ); + Counts operator-(Counts const& other) const; + Counts& operator+=(Counts const& other); std::size_t total() const; bool allPassed() const; @@ -2839,16 +3680,16 @@ struct Totals { - Totals operator - ( Totals const& other ) const; - Totals& operator += ( Totals const& other ); + Totals operator-(Totals const& other) const; + Totals& operator+=(Totals const& other); - Totals delta( Totals const& prevTotals ) const; + Totals delta(Totals const& prevTotals) const; int error = 0; Counts assertions; Counts testCases; }; -} +} // namespace Catch // end catch_totals.h #include <string> @@ -2856,15 +3697,13 @@ namespace Catch { struct SectionInfo { - SectionInfo - ( SourceLineInfo const& _lineInfo, - std::string const& _name ); + SectionInfo(SourceLineInfo const& _lineInfo, std::string const& _name); // Deprecated - SectionInfo - ( SourceLineInfo const& _lineInfo, - std::string const& _name, - std::string const& ) : SectionInfo( _lineInfo, _name ) {} + SectionInfo(SourceLineInfo const& _lineInfo, + std::string const& _name, + std::string const&) : + SectionInfo(_lineInfo, _name) {} std::string name; std::string description; // !Deprecated: this will always be empty @@ -2891,6 +3730,7 @@ class Timer { uint64_t m_nanoseconds = 0; + public: void start(); auto getElapsedNanoseconds() const -> uint64_t; @@ -2908,7 +3748,7 @@ class Section : NonCopyable { public: - Section( SectionInfo const& info ); + Section(SectionInfo const& info); ~Section(); // This indicates whether the section should be executed or not @@ -2925,16 +3765,22 @@ } // end namespace Catch -#define INTERNAL_CATCH_SECTION( ... ) \ - CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ - CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ - if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \ +#define INTERNAL_CATCH_SECTION(...) \ + CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ + CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ + if (Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( \ + catch_internal_Section) = \ + Catch::SectionInfo(CATCH_INTERNAL_LINEINFO, __VA_ARGS__)) \ CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION -#define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \ - CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ - CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ - if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \ +#define INTERNAL_CATCH_DYNAMIC_SECTION(...) \ + CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ + CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ + if (Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( \ + catch_internal_Section) = \ + Catch::SectionInfo( \ + CATCH_INTERNAL_LINEINFO, \ + (Catch::ReusableStringStream() << __VA_ARGS__).str())) \ CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION // end catch_section.h @@ -2966,18 +3812,24 @@ virtual IReporterRegistry const& getReporterRegistry() const = 0; virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0; virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0; - virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0; + virtual IExceptionTranslatorRegistry const& + getExceptionTranslatorRegistry() const = 0; - virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0; + virtual StartupExceptionRegistry const& + getStartupExceptionRegistry() const = 0; }; struct IMutableRegistryHub { virtual ~IMutableRegistryHub(); - virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0; - virtual void registerListener( IReporterFactoryPtr const& factory ) = 0; - virtual void registerTest( TestCase const& testInfo ) = 0; - virtual void registerTranslator( const IExceptionTranslator* translator ) = 0; - virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0; + virtual void registerReporter(std::string const& name, + IReporterFactoryPtr const& factory) = 0; + virtual void registerListener(IReporterFactoryPtr const& factory) = 0; + virtual void registerTest(TestCase const& testInfo) = 0; + virtual void + registerTranslator(const IExceptionTranslator* translator) = 0; + virtual void registerTagAlias(std::string const& alias, + std::string const& tag, + SourceLineInfo const& lineInfo) = 0; virtual void registerStartupException() noexcept = 0; virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0; }; @@ -2987,12 +3839,12 @@ void cleanUp(); std::string translateActiveException(); -} +} // namespace Catch // end catch_interfaces_registry_hub.h #if defined(CATCH_CONFIG_DISABLE) - #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \ - static std::string translatorName( signature ) +#define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG(translatorName, signature) \ + static std::string translatorName(signature) #endif #include <exception> @@ -3000,14 +3852,17 @@ #include <vector> namespace Catch { - using exceptionTranslateFunction = std::string(*)(); + using exceptionTranslateFunction = std::string (*)(); struct IExceptionTranslator; - using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>; + using ExceptionTranslators = + std::vector<std::unique_ptr<IExceptionTranslator const>>; struct IExceptionTranslator { virtual ~IExceptionTranslator(); - virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0; + virtual std::string + translate(ExceptionTranslators::const_iterator it, + ExceptionTranslators::const_iterator itEnd) const = 0; }; struct IExceptionTranslatorRegistry { @@ -3017,53 +3872,58 @@ }; class ExceptionTranslatorRegistrar { - template<typename T> + template <typename T> class ExceptionTranslator : public IExceptionTranslator { public: + ExceptionTranslator(std::string (*translateFunction)(T&)) : + m_translateFunction(translateFunction) {} - ExceptionTranslator( std::string(*translateFunction)( T& ) ) - : m_translateFunction( translateFunction ) - {} - - std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override { + std::string translate( + ExceptionTranslators::const_iterator it, + ExceptionTranslators::const_iterator itEnd) const override { #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) return ""; #else try { - if( it == itEnd ) + if (it == itEnd) std::rethrow_exception(std::current_exception()); else - return (*it)->translate( it+1, itEnd ); - } - catch( T& ex ) { - return m_translateFunction( ex ); + return (*it)->translate(it + 1, itEnd); + } catch (T& ex) { + return m_translateFunction(ex); } #endif } protected: - std::string(*m_translateFunction)( T& ); + std::string (*m_translateFunction)(T&); }; public: - template<typename T> - ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) { - getMutableRegistryHub().registerTranslator - ( new ExceptionTranslator<T>( translateFunction ) ); + template <typename T> + ExceptionTranslatorRegistrar(std::string (*translateFunction)(T&)) { + getMutableRegistryHub().registerTranslator( + new ExceptionTranslator<T>(translateFunction)); } }; -} +} // namespace Catch /////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \ - static std::string translatorName( signature ); \ - CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ - CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ - namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \ - CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ - static std::string translatorName( signature ) +#define INTERNAL_CATCH_TRANSLATE_EXCEPTION2(translatorName, signature) \ + static std::string translatorName(signature); \ + CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + namespace { \ + Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( \ + catch_internal_ExceptionRegistrar)(&translatorName); \ + } \ + CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ + static std::string translatorName(signature) -#define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature ) +#define INTERNAL_CATCH_TRANSLATE_EXCEPTION(signature) \ + INTERNAL_CATCH_TRANSLATE_EXCEPTION2( \ + INTERNAL_CATCH_UNIQUE_NAME(catch_internal_ExceptionTranslator), \ + signature) // end catch_interfaces_exception.h // start catch_approx.h @@ -3071,118 +3931,143 @@ #include <type_traits> namespace Catch { -namespace Detail { + namespace Detail { - class Approx { - private: - bool equalityComparisonImpl(double other) const; - // Validates the new margin (margin >= 0) - // out-of-line to avoid including stdexcept in the header - void setMargin(double margin); - // Validates the new epsilon (0 < epsilon < 1) - // out-of-line to avoid including stdexcept in the header - void setEpsilon(double epsilon); + class Approx { + private: + bool equalityComparisonImpl(double other) const; + // Validates the new margin (margin >= 0) + // out-of-line to avoid including stdexcept in the header + void setMargin(double margin); + // Validates the new epsilon (0 < epsilon < 1) + // out-of-line to avoid including stdexcept in the header + void setEpsilon(double epsilon); - public: - explicit Approx ( double value ); + public: + explicit Approx(double value); - static Approx custom(); + static Approx custom(); - Approx operator-() const; + Approx operator-() const; - template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> - Approx operator()( T const& value ) { - Approx approx( static_cast<double>(value) ); - approx.m_epsilon = m_epsilon; - approx.m_margin = m_margin; - approx.m_scale = m_scale; - return approx; - } + template <typename T, + typename = typename std::enable_if< + std::is_constructible<double, T>::value>::type> + Approx operator()(T const& value) { + Approx approx(static_cast<double>(value)); + approx.m_epsilon = m_epsilon; + approx.m_margin = m_margin; + approx.m_scale = m_scale; + return approx; + } - template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> - explicit Approx( T const& value ): Approx(static_cast<double>(value)) - {} + template <typename T, + typename = typename std::enable_if< + std::is_constructible<double, T>::value>::type> + explicit Approx(T const& value) : + Approx(static_cast<double>(value)) {} - template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> - friend bool operator == ( const T& lhs, Approx const& rhs ) { - auto lhs_v = static_cast<double>(lhs); - return rhs.equalityComparisonImpl(lhs_v); - } + template <typename T, + typename = typename std::enable_if< + std::is_constructible<double, T>::value>::type> + friend bool operator==(const T& lhs, Approx const& rhs) { + auto lhs_v = static_cast<double>(lhs); + return rhs.equalityComparisonImpl(lhs_v); + } - template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> - friend bool operator == ( Approx const& lhs, const T& rhs ) { - return operator==( rhs, lhs ); - } + template <typename T, + typename = typename std::enable_if< + std::is_constructible<double, T>::value>::type> + friend bool operator==(Approx const& lhs, const T& rhs) { + return operator==(rhs, lhs); + } - template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> - friend bool operator != ( T const& lhs, Approx const& rhs ) { - return !operator==( lhs, rhs ); - } + template <typename T, + typename = typename std::enable_if< + std::is_constructible<double, T>::value>::type> + friend bool operator!=(T const& lhs, Approx const& rhs) { + return !operator==(lhs, rhs); + } - template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> - friend bool operator != ( Approx const& lhs, T const& rhs ) { - return !operator==( rhs, lhs ); - } + template <typename T, + typename = typename std::enable_if< + std::is_constructible<double, T>::value>::type> + friend bool operator!=(Approx const& lhs, T const& rhs) { + return !operator==(rhs, lhs); + } - template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> - friend bool operator <= ( T const& lhs, Approx const& rhs ) { - return static_cast<double>(lhs) < rhs.m_value || lhs == rhs; - } + template <typename T, + typename = typename std::enable_if< + std::is_constructible<double, T>::value>::type> + friend bool operator<=(T const& lhs, Approx const& rhs) { + return static_cast<double>(lhs) < rhs.m_value || lhs == rhs; + } - template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> - friend bool operator <= ( Approx const& lhs, T const& rhs ) { - return lhs.m_value < static_cast<double>(rhs) || lhs == rhs; - } + template <typename T, + typename = typename std::enable_if< + std::is_constructible<double, T>::value>::type> + friend bool operator<=(Approx const& lhs, T const& rhs) { + return lhs.m_value < static_cast<double>(rhs) || lhs == rhs; + } - template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> - friend bool operator >= ( T const& lhs, Approx const& rhs ) { - return static_cast<double>(lhs) > rhs.m_value || lhs == rhs; - } + template <typename T, + typename = typename std::enable_if< + std::is_constructible<double, T>::value>::type> + friend bool operator>=(T const& lhs, Approx const& rhs) { + return static_cast<double>(lhs) > rhs.m_value || lhs == rhs; + } - template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> - friend bool operator >= ( Approx const& lhs, T const& rhs ) { - return lhs.m_value > static_cast<double>(rhs) || lhs == rhs; - } + template <typename T, + typename = typename std::enable_if< + std::is_constructible<double, T>::value>::type> + friend bool operator>=(Approx const& lhs, T const& rhs) { + return lhs.m_value > static_cast<double>(rhs) || lhs == rhs; + } - template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> - Approx& epsilon( T const& newEpsilon ) { - double epsilonAsDouble = static_cast<double>(newEpsilon); - setEpsilon(epsilonAsDouble); - return *this; - } + template <typename T, + typename = typename std::enable_if< + std::is_constructible<double, T>::value>::type> + Approx& epsilon(T const& newEpsilon) { + double epsilonAsDouble = static_cast<double>(newEpsilon); + setEpsilon(epsilonAsDouble); + return *this; + } - template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> - Approx& margin( T const& newMargin ) { - double marginAsDouble = static_cast<double>(newMargin); - setMargin(marginAsDouble); - return *this; - } + template <typename T, + typename = typename std::enable_if< + std::is_constructible<double, T>::value>::type> + Approx& margin(T const& newMargin) { + double marginAsDouble = static_cast<double>(newMargin); + setMargin(marginAsDouble); + return *this; + } - template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> - Approx& scale( T const& newScale ) { - m_scale = static_cast<double>(newScale); - return *this; - } + template <typename T, + typename = typename std::enable_if< + std::is_constructible<double, T>::value>::type> + Approx& scale(T const& newScale) { + m_scale = static_cast<double>(newScale); + return *this; + } - std::string toString() const; + std::string toString() const; - private: - double m_epsilon; - double m_margin; - double m_scale; - double m_value; + private: + double m_epsilon; + double m_margin; + double m_scale; + double m_value; + }; + } // end namespace Detail + + namespace literals { + Detail::Approx operator"" _a(long double val); + Detail::Approx operator"" _a(unsigned long long val); + } // end namespace literals + + template <> struct StringMaker<Catch::Detail::Approx> { + static std::string convert(Catch::Detail::Approx const& value); }; -} // end namespace Detail - -namespace literals { - Detail::Approx operator "" _a(long double val); - Detail::Approx operator "" _a(unsigned long long val); -} // end namespace literals - -template<> -struct StringMaker<Catch::Detail::Approx> { - static std::string convert(Catch::Detail::Approx const& value); -}; } // end namespace Catch @@ -3195,31 +4080,36 @@ namespace Catch { - bool startsWith( std::string const& s, std::string const& prefix ); - bool startsWith( std::string const& s, char prefix ); - bool endsWith( std::string const& s, std::string const& suffix ); - bool endsWith( std::string const& s, char suffix ); - bool contains( std::string const& s, std::string const& infix ); - void toLowerInPlace( std::string& s ); - std::string toLower( std::string const& s ); + bool startsWith(std::string const& s, std::string const& prefix); + bool startsWith(std::string const& s, char prefix); + bool endsWith(std::string const& s, std::string const& suffix); + bool endsWith(std::string const& s, char suffix); + bool contains(std::string const& s, std::string const& infix); + void toLowerInPlace(std::string& s); + std::string toLower(std::string const& s); //! Returns a new string without whitespace at the start/end - std::string trim( std::string const& str ); - //! Returns a substring of the original ref without whitespace. Beware lifetimes! + std::string trim(std::string const& str); + //! Returns a substring of the original ref without whitespace. Beware + //! lifetimes! StringRef trim(StringRef ref); - // !!! Be aware, returns refs into original string - make sure original string outlives them - std::vector<StringRef> splitStringRef( StringRef str, char delimiter ); - bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ); + // !!! Be aware, returns refs into original string - make sure original + // string outlives them + std::vector<StringRef> splitStringRef(StringRef str, char delimiter); + bool replaceInPlace(std::string& str, + std::string const& replaceThis, + std::string const& withThis); struct pluralise { - pluralise( std::size_t count, std::string const& label ); + pluralise(std::size_t count, std::string const& label); - friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ); + friend std::ostream& operator<<(std::ostream& os, + pluralise const& pluraliser); std::size_t m_count; std::string m_label; }; -} +} // namespace Catch // end catch_string_manip.h #ifndef CATCH_CONFIG_DISABLE_MATCHERS @@ -3231,159 +4121,160 @@ #include <vector> namespace Catch { -namespace Matchers { - namespace Impl { + namespace Matchers { + namespace Impl { - template<typename ArgT> struct MatchAllOf; - template<typename ArgT> struct MatchAnyOf; - template<typename ArgT> struct MatchNotOf; + template <typename ArgT> struct MatchAllOf; + template <typename ArgT> struct MatchAnyOf; + template <typename ArgT> struct MatchNotOf; - class MatcherUntypedBase { - public: - MatcherUntypedBase() = default; - MatcherUntypedBase ( MatcherUntypedBase const& ) = default; - MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete; - std::string toString() const; + class MatcherUntypedBase { + public: + MatcherUntypedBase() = default; + MatcherUntypedBase(MatcherUntypedBase const&) = default; + MatcherUntypedBase& + operator=(MatcherUntypedBase const&) = delete; + std::string toString() const; - protected: - virtual ~MatcherUntypedBase(); - virtual std::string describe() const = 0; - mutable std::string m_cachedToString; - }; + protected: + virtual ~MatcherUntypedBase(); + virtual std::string describe() const = 0; + mutable std::string m_cachedToString; + }; #ifdef __clang__ -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wnon-virtual-dtor" +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wnon-virtual-dtor" #endif - template<typename ObjectT> - struct MatcherMethod { - virtual bool match( ObjectT const& arg ) const = 0; - }; + template <typename ObjectT> struct MatcherMethod { + virtual bool match(ObjectT const& arg) const = 0; + }; #if defined(__OBJC__) - // Hack to fix Catch GH issue #1661. Could use id for generic Object support. - // use of const for Object pointers is very uncommon and under ARC it causes some kind of signature mismatch that breaks compilation - template<> - struct MatcherMethod<NSString*> { - virtual bool match( NSString* arg ) const = 0; - }; + // Hack to fix Catch GH issue #1661. Could use id for generic Object + // support. use of const for Object pointers is very uncommon and + // under ARC it causes some kind of signature mismatch that breaks + // compilation + template <> struct MatcherMethod<NSString*> { + virtual bool match(NSString* arg) const = 0; + }; #endif #ifdef __clang__ -# pragma clang diagnostic pop +#pragma clang diagnostic pop #endif - template<typename T> - struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> { + template <typename T> + struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> { - MatchAllOf<T> operator && ( MatcherBase const& other ) const; - MatchAnyOf<T> operator || ( MatcherBase const& other ) const; - MatchNotOf<T> operator ! () const; - }; + MatchAllOf<T> operator&&(MatcherBase const& other) const; + MatchAnyOf<T> operator||(MatcherBase const& other) const; + MatchNotOf<T> operator!() const; + }; - template<typename ArgT> - struct MatchAllOf : MatcherBase<ArgT> { - bool match( ArgT const& arg ) const override { - for( auto matcher : m_matchers ) { - if (!matcher->match(arg)) - return false; + template <typename ArgT> struct MatchAllOf : MatcherBase<ArgT> { + bool match(ArgT const& arg) const override { + for (auto matcher : m_matchers) { + if (!matcher->match(arg)) + return false; + } + return true; } - return true; - } - std::string describe() const override { - std::string description; - description.reserve( 4 + m_matchers.size()*32 ); - description += "( "; - bool first = true; - for( auto matcher : m_matchers ) { - if( first ) - first = false; - else - description += " and "; - description += matcher->toString(); + std::string describe() const override { + std::string description; + description.reserve(4 + m_matchers.size() * 32); + description += "( "; + bool first = true; + for (auto matcher : m_matchers) { + if (first) + first = false; + else + description += " and "; + description += matcher->toString(); + } + description += " )"; + return description; } - description += " )"; - return description; - } - MatchAllOf<ArgT> operator && ( MatcherBase<ArgT> const& other ) { - auto copy(*this); - copy.m_matchers.push_back( &other ); - return copy; - } - - std::vector<MatcherBase<ArgT> const*> m_matchers; - }; - template<typename ArgT> - struct MatchAnyOf : MatcherBase<ArgT> { - - bool match( ArgT const& arg ) const override { - for( auto matcher : m_matchers ) { - if (matcher->match(arg)) - return true; + MatchAllOf<ArgT> operator&&(MatcherBase<ArgT> const& other) { + auto copy(*this); + copy.m_matchers.push_back(&other); + return copy; } - return false; - } - std::string describe() const override { - std::string description; - description.reserve( 4 + m_matchers.size()*32 ); - description += "( "; - bool first = true; - for( auto matcher : m_matchers ) { - if( first ) - first = false; - else - description += " or "; - description += matcher->toString(); + + std::vector<MatcherBase<ArgT> const*> m_matchers; + }; + template <typename ArgT> struct MatchAnyOf : MatcherBase<ArgT> { + + bool match(ArgT const& arg) const override { + for (auto matcher : m_matchers) { + if (matcher->match(arg)) + return true; + } + return false; } - description += " )"; - return description; + std::string describe() const override { + std::string description; + description.reserve(4 + m_matchers.size() * 32); + description += "( "; + bool first = true; + for (auto matcher : m_matchers) { + if (first) + first = false; + else + description += " or "; + description += matcher->toString(); + } + description += " )"; + return description; + } + + MatchAnyOf<ArgT> operator||(MatcherBase<ArgT> const& other) { + auto copy(*this); + copy.m_matchers.push_back(&other); + return copy; + } + + std::vector<MatcherBase<ArgT> const*> m_matchers; + }; + + template <typename ArgT> struct MatchNotOf : MatcherBase<ArgT> { + + MatchNotOf(MatcherBase<ArgT> const& underlyingMatcher) : + m_underlyingMatcher(underlyingMatcher) {} + + bool match(ArgT const& arg) const override { + return !m_underlyingMatcher.match(arg); + } + + std::string describe() const override { + return "not " + m_underlyingMatcher.toString(); + } + MatcherBase<ArgT> const& m_underlyingMatcher; + }; + + template <typename T> + MatchAllOf<T> + MatcherBase<T>::operator&&(MatcherBase const& other) const { + return MatchAllOf<T>() && *this && other; + } + template <typename T> + MatchAnyOf<T> + MatcherBase<T>::operator||(MatcherBase const& other) const { + return MatchAnyOf<T>() || *this || other; + } + template <typename T> + MatchNotOf<T> MatcherBase<T>::operator!() const { + return MatchNotOf<T>(*this); } - MatchAnyOf<ArgT> operator || ( MatcherBase<ArgT> const& other ) { - auto copy(*this); - copy.m_matchers.push_back( &other ); - return copy; - } + } // namespace Impl - std::vector<MatcherBase<ArgT> const*> m_matchers; - }; + } // namespace Matchers - template<typename ArgT> - struct MatchNotOf : MatcherBase<ArgT> { - - MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {} - - bool match( ArgT const& arg ) const override { - return !m_underlyingMatcher.match( arg ); - } - - std::string describe() const override { - return "not " + m_underlyingMatcher.toString(); - } - MatcherBase<ArgT> const& m_underlyingMatcher; - }; - - template<typename T> - MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const { - return MatchAllOf<T>() && *this && other; - } - template<typename T> - MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const { - return MatchAnyOf<T>() || *this || other; - } - template<typename T> - MatchNotOf<T> MatcherBase<T>::operator ! () const { - return MatchNotOf<T>( *this ); - } - - } // namespace Impl - -} // namespace Matchers - -using namespace Matchers; -using Matchers::Impl::MatcherBase; + using namespace Matchers; + using Matchers::Impl::MatcherBase; } // namespace Catch @@ -3391,88 +4282,94 @@ // start catch_matchers_exception.hpp namespace Catch { -namespace Matchers { -namespace Exception { + namespace Matchers { + namespace Exception { -class ExceptionMessageMatcher : public MatcherBase<std::exception> { - std::string m_message; -public: + class ExceptionMessageMatcher : public MatcherBase<std::exception> { + std::string m_message; - ExceptionMessageMatcher(std::string const& message): - m_message(message) - {} + public: + ExceptionMessageMatcher(std::string const& message) : + m_message(message) {} - bool match(std::exception const& ex) const override; + bool match(std::exception const& ex) const override; - std::string describe() const override; -}; + std::string describe() const override; + }; -} // namespace Exception + } // namespace Exception -Exception::ExceptionMessageMatcher Message(std::string const& message); + Exception::ExceptionMessageMatcher Message(std::string const& message); -} // namespace Matchers + } // namespace Matchers } // namespace Catch // end catch_matchers_exception.hpp // start catch_matchers_floating.h namespace Catch { -namespace Matchers { + namespace Matchers { - namespace Floating { + namespace Floating { - enum class FloatingPointKind : uint8_t; + enum class FloatingPointKind : uint8_t; - struct WithinAbsMatcher : MatcherBase<double> { - WithinAbsMatcher(double target, double margin); - bool match(double const& matchee) const override; - std::string describe() const override; - private: - double m_target; - double m_margin; - }; + struct WithinAbsMatcher : MatcherBase<double> { + WithinAbsMatcher(double target, double margin); + bool match(double const& matchee) const override; + std::string describe() const override; - struct WithinUlpsMatcher : MatcherBase<double> { - WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType); - bool match(double const& matchee) const override; - std::string describe() const override; - private: - double m_target; - uint64_t m_ulps; - FloatingPointKind m_type; - }; + private: + double m_target; + double m_margin; + }; - // Given IEEE-754 format for floats and doubles, we can assume - // that float -> double promotion is lossless. Given this, we can - // assume that if we do the standard relative comparison of - // |lhs - rhs| <= epsilon * max(fabs(lhs), fabs(rhs)), then we get - // the same result if we do this for floats, as if we do this for - // doubles that were promoted from floats. - struct WithinRelMatcher : MatcherBase<double> { - WithinRelMatcher(double target, double epsilon); - bool match(double const& matchee) const override; - std::string describe() const override; - private: - double m_target; - double m_epsilon; - }; + struct WithinUlpsMatcher : MatcherBase<double> { + WithinUlpsMatcher(double target, + uint64_t ulps, + FloatingPointKind baseType); + bool match(double const& matchee) const override; + std::string describe() const override; - } // namespace Floating + private: + double m_target; + uint64_t m_ulps; + FloatingPointKind m_type; + }; - // The following functions create the actual matcher objects. - // This allows the types to be inferred - Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff); - Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff); - Floating::WithinAbsMatcher WithinAbs(double target, double margin); - Floating::WithinRelMatcher WithinRel(double target, double eps); - // defaults epsilon to 100*numeric_limits<double>::epsilon() - Floating::WithinRelMatcher WithinRel(double target); - Floating::WithinRelMatcher WithinRel(float target, float eps); - // defaults epsilon to 100*numeric_limits<float>::epsilon() - Floating::WithinRelMatcher WithinRel(float target); + // Given IEEE-754 format for floats and doubles, we can assume + // that float -> double promotion is lossless. Given this, we can + // assume that if we do the standard relative comparison of + // |lhs - rhs| <= epsilon * max(fabs(lhs), fabs(rhs)), then we get + // the same result if we do this for floats, as if we do this for + // doubles that were promoted from floats. + struct WithinRelMatcher : MatcherBase<double> { + WithinRelMatcher(double target, double epsilon); + bool match(double const& matchee) const override; + std::string describe() const override; -} // namespace Matchers + private: + double m_target; + double m_epsilon; + }; + + } // namespace Floating + + // The following functions create the actual matcher objects. + // This allows the types to be inferred + Floating::WithinUlpsMatcher WithinULP(double target, + uint64_t maxUlpDiff); + Floating::WithinUlpsMatcher WithinULP(float target, + uint64_t maxUlpDiff); + Floating::WithinAbsMatcher WithinAbs(double target, double margin); + Floating::WithinRelMatcher WithinRel(double target, double eps); + // defaults epsilon to 100*numeric_limits<double>::epsilon() + Floating::WithinRelMatcher WithinRel(double target); + Floating::WithinRelMatcher WithinRel(float target, float eps); + // defaults epsilon to 100*numeric_limits<float>::epsilon() + Floating::WithinRelMatcher WithinRel(float target); + + } // namespace Matchers } // namespace Catch // end catch_matchers_floating.h @@ -3482,45 +4379,45 @@ #include <string> namespace Catch { -namespace Matchers { -namespace Generic { + namespace Matchers { + namespace Generic { -namespace Detail { - std::string finalizeDescription(const std::string& desc); -} + namespace Detail { + std::string finalizeDescription(const std::string& desc); + } -template <typename T> -class PredicateMatcher : public MatcherBase<T> { - std::function<bool(T const&)> m_predicate; - std::string m_description; -public: + template <typename T> + class PredicateMatcher : public MatcherBase<T> { + std::function<bool(T const&)> m_predicate; + std::string m_description; - PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr) - :m_predicate(std::move(elem)), - m_description(Detail::finalizeDescription(descr)) - {} + public: + PredicateMatcher(std::function<bool(T const&)> const& elem, + std::string const& descr) : + m_predicate(std::move(elem)), + m_description(Detail::finalizeDescription(descr)) {} - bool match( T const& item ) const override { - return m_predicate(item); - } + bool match(T const& item) const override { + return m_predicate(item); + } - std::string describe() const override { - return m_description; - } -}; + std::string describe() const override { return m_description; } + }; -} // namespace Generic + } // namespace Generic - // The following functions create the actual matcher objects. - // The user has to explicitly specify type to the function, because - // inferring std::function<bool(T const&)> is hard (but possible) and - // requires a lot of TMP. - template<typename T> - Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") { - return Generic::PredicateMatcher<T>(predicate, description); - } + // The following functions create the actual matcher objects. + // The user has to explicitly specify type to the function, because + // inferring std::function<bool(T const&)> is hard (but possible) and + // requires a lot of TMP. + template <typename T> + Generic::PredicateMatcher<T> + Predicate(std::function<bool(T const&)> const& predicate, + std::string const& description = "") { + return Generic::PredicateMatcher<T>(predicate, description); + } -} // namespace Matchers + } // namespace Matchers } // namespace Catch // end catch_matchers_generic.hpp @@ -3529,67 +4426,79 @@ #include <string> namespace Catch { -namespace Matchers { + namespace Matchers { - namespace StdString { + namespace StdString { - struct CasedString - { - CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity ); - std::string adjustString( std::string const& str ) const; - std::string caseSensitivitySuffix() const; + struct CasedString { + CasedString(std::string const& str, + CaseSensitive::Choice caseSensitivity); + std::string adjustString(std::string const& str) const; + std::string caseSensitivitySuffix() const; - CaseSensitive::Choice m_caseSensitivity; - std::string m_str; - }; + CaseSensitive::Choice m_caseSensitivity; + std::string m_str; + }; - struct StringMatcherBase : MatcherBase<std::string> { - StringMatcherBase( std::string const& operation, CasedString const& comparator ); - std::string describe() const override; + struct StringMatcherBase : MatcherBase<std::string> { + StringMatcherBase(std::string const& operation, + CasedString const& comparator); + std::string describe() const override; - CasedString m_comparator; - std::string m_operation; - }; + CasedString m_comparator; + std::string m_operation; + }; - struct EqualsMatcher : StringMatcherBase { - EqualsMatcher( CasedString const& comparator ); - bool match( std::string const& source ) const override; - }; - struct ContainsMatcher : StringMatcherBase { - ContainsMatcher( CasedString const& comparator ); - bool match( std::string const& source ) const override; - }; - struct StartsWithMatcher : StringMatcherBase { - StartsWithMatcher( CasedString const& comparator ); - bool match( std::string const& source ) const override; - }; - struct EndsWithMatcher : StringMatcherBase { - EndsWithMatcher( CasedString const& comparator ); - bool match( std::string const& source ) const override; - }; + struct EqualsMatcher : StringMatcherBase { + EqualsMatcher(CasedString const& comparator); + bool match(std::string const& source) const override; + }; + struct ContainsMatcher : StringMatcherBase { + ContainsMatcher(CasedString const& comparator); + bool match(std::string const& source) const override; + }; + struct StartsWithMatcher : StringMatcherBase { + StartsWithMatcher(CasedString const& comparator); + bool match(std::string const& source) const override; + }; + struct EndsWithMatcher : StringMatcherBase { + EndsWithMatcher(CasedString const& comparator); + bool match(std::string const& source) const override; + }; - struct RegexMatcher : MatcherBase<std::string> { - RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity ); - bool match( std::string const& matchee ) const override; - std::string describe() const override; + struct RegexMatcher : MatcherBase<std::string> { + RegexMatcher(std::string regex, + CaseSensitive::Choice caseSensitivity); + bool match(std::string const& matchee) const override; + std::string describe() const override; - private: - std::string m_regex; - CaseSensitive::Choice m_caseSensitivity; - }; + private: + std::string m_regex; + CaseSensitive::Choice m_caseSensitivity; + }; - } // namespace StdString + } // namespace StdString - // The following functions create the actual matcher objects. - // This allows the types to be inferred + // The following functions create the actual matcher objects. + // This allows the types to be inferred - StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); - StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); - StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); - StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); - StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); + StdString::EqualsMatcher + Equals(std::string const& str, + CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes); + StdString::ContainsMatcher + Contains(std::string const& str, + CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes); + StdString::EndsWithMatcher + EndsWith(std::string const& str, + CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes); + StdString::StartsWithMatcher + StartsWith(std::string const& str, + CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes); + StdString::RegexMatcher + Matches(std::string const& regex, + CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes); -} // namespace Matchers + } // namespace Matchers } // namespace Catch // end catch_matchers_string.h @@ -3598,189 +4507,227 @@ #include <algorithm> namespace Catch { -namespace Matchers { + namespace Matchers { - namespace Vector { - template<typename T, typename Alloc> - struct ContainsElementMatcher : MatcherBase<std::vector<T, Alloc>> { + namespace Vector { + template <typename T, typename Alloc> + struct ContainsElementMatcher : MatcherBase<std::vector<T, Alloc>> { - ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {} + ContainsElementMatcher(T const& comparator) : + m_comparator(comparator) {} - bool match(std::vector<T, Alloc> const &v) const override { - for (auto const& el : v) { - if (el == m_comparator) { - return true; - } - } - return false; - } - - std::string describe() const override { - return "Contains: " + ::Catch::Detail::stringify( m_comparator ); - } - - T const& m_comparator; - }; - - template<typename T, typename AllocComp, typename AllocMatch> - struct ContainsMatcher : MatcherBase<std::vector<T, AllocMatch>> { - - ContainsMatcher(std::vector<T, AllocComp> const &comparator) : m_comparator( comparator ) {} - - bool match(std::vector<T, AllocMatch> const &v) const override { - // !TBD: see note in EqualsMatcher - if (m_comparator.size() > v.size()) - return false; - for (auto const& comparator : m_comparator) { - auto present = false; - for (const auto& el : v) { - if (el == comparator) { - present = true; - break; + bool match(std::vector<T, Alloc> const& v) const override { + for (auto const& el : v) { + if (el == m_comparator) { + return true; } } - if (!present) { + return false; + } + + std::string describe() const override { + return "Contains: " + + ::Catch::Detail::stringify(m_comparator); + } + + T const& m_comparator; + }; + + template <typename T, typename AllocComp, typename AllocMatch> + struct ContainsMatcher : MatcherBase<std::vector<T, AllocMatch>> { + + ContainsMatcher(std::vector<T, AllocComp> const& comparator) : + m_comparator(comparator) {} + + bool match(std::vector<T, AllocMatch> const& v) const override { + // !TBD: see note in EqualsMatcher + if (m_comparator.size() > v.size()) + return false; + for (auto const& comparator : m_comparator) { + auto present = false; + for (const auto& el : v) { + if (el == comparator) { + present = true; + break; + } + } + if (!present) { + return false; + } + } + return true; + } + std::string describe() const override { + return "Contains: " + + ::Catch::Detail::stringify(m_comparator); + } + + std::vector<T, AllocComp> const& m_comparator; + }; + + template <typename T, typename AllocComp, typename AllocMatch> + struct EqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> { + + EqualsMatcher(std::vector<T, AllocComp> const& comparator) : + m_comparator(comparator) {} + + bool match(std::vector<T, AllocMatch> const& v) const override { + // !TBD: This currently works if all elements can be + // compared using != + // - a more general approach would be via a compare template + // that defaults to using !=. but could be specialised for, + // e.g. std::vector<T, Alloc> etc + // - then just call that directly + if (m_comparator.size() != v.size()) + return false; + for (std::size_t i = 0; i < v.size(); ++i) + if (m_comparator[i] != v[i]) + return false; + return true; + } + std::string describe() const override { + return "Equals: " + + ::Catch::Detail::stringify(m_comparator); + } + std::vector<T, AllocComp> const& m_comparator; + }; + + template <typename T, typename AllocComp, typename AllocMatch> + struct ApproxMatcher : MatcherBase<std::vector<T, AllocMatch>> { + + ApproxMatcher(std::vector<T, AllocComp> const& comparator) : + m_comparator(comparator) {} + + bool match(std::vector<T, AllocMatch> const& v) const override { + if (m_comparator.size() != v.size()) + return false; + for (std::size_t i = 0; i < v.size(); ++i) + if (m_comparator[i] != approx(v[i])) + return false; + return true; + } + std::string describe() const override { + return "is approx: " + + ::Catch::Detail::stringify(m_comparator); + } + template <typename = typename std::enable_if< + std::is_constructible<double, T>::value>::type> + ApproxMatcher& epsilon(T const& newEpsilon) { + approx.epsilon(newEpsilon); + return *this; + } + template <typename = typename std::enable_if< + std::is_constructible<double, T>::value>::type> + ApproxMatcher& margin(T const& newMargin) { + approx.margin(newMargin); + return *this; + } + template <typename = typename std::enable_if< + std::is_constructible<double, T>::value>::type> + ApproxMatcher& scale(T const& newScale) { + approx.scale(newScale); + return *this; + } + + std::vector<T, AllocComp> const& m_comparator; + mutable Catch::Detail::Approx approx = + Catch::Detail::Approx::custom(); + }; + + template <typename T, typename AllocComp, typename AllocMatch> + struct UnorderedEqualsMatcher + : MatcherBase<std::vector<T, AllocMatch>> { + UnorderedEqualsMatcher( + std::vector<T, AllocComp> const& target) : + m_target(target) {} + bool + match(std::vector<T, AllocMatch> const& vec) const override { + if (m_target.size() != vec.size()) { return false; } + return std::is_permutation( + m_target.begin(), m_target.end(), vec.begin()); } - return true; - } - std::string describe() const override { - return "Contains: " + ::Catch::Detail::stringify( m_comparator ); - } - std::vector<T, AllocComp> const& m_comparator; - }; - - template<typename T, typename AllocComp, typename AllocMatch> - struct EqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> { - - EqualsMatcher(std::vector<T, AllocComp> const &comparator) : m_comparator( comparator ) {} - - bool match(std::vector<T, AllocMatch> const &v) const override { - // !TBD: This currently works if all elements can be compared using != - // - a more general approach would be via a compare template that defaults - // to using !=. but could be specialised for, e.g. std::vector<T, Alloc> etc - // - then just call that directly - if (m_comparator.size() != v.size()) - return false; - for (std::size_t i = 0; i < v.size(); ++i) - if (m_comparator[i] != v[i]) - return false; - return true; - } - std::string describe() const override { - return "Equals: " + ::Catch::Detail::stringify( m_comparator ); - } - std::vector<T, AllocComp> const& m_comparator; - }; - - template<typename T, typename AllocComp, typename AllocMatch> - struct ApproxMatcher : MatcherBase<std::vector<T, AllocMatch>> { - - ApproxMatcher(std::vector<T, AllocComp> const& comparator) : m_comparator( comparator ) {} - - bool match(std::vector<T, AllocMatch> const &v) const override { - if (m_comparator.size() != v.size()) - return false; - for (std::size_t i = 0; i < v.size(); ++i) - if (m_comparator[i] != approx(v[i])) - return false; - return true; - } - std::string describe() const override { - return "is approx: " + ::Catch::Detail::stringify( m_comparator ); - } - template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> - ApproxMatcher& epsilon( T const& newEpsilon ) { - approx.epsilon(newEpsilon); - return *this; - } - template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> - ApproxMatcher& margin( T const& newMargin ) { - approx.margin(newMargin); - return *this; - } - template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> - ApproxMatcher& scale( T const& newScale ) { - approx.scale(newScale); - return *this; - } - - std::vector<T, AllocComp> const& m_comparator; - mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom(); - }; - - template<typename T, typename AllocComp, typename AllocMatch> - struct UnorderedEqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> { - UnorderedEqualsMatcher(std::vector<T, AllocComp> const& target) : m_target(target) {} - bool match(std::vector<T, AllocMatch> const& vec) const override { - if (m_target.size() != vec.size()) { - return false; + std::string describe() const override { + return "UnorderedEquals: " + + ::Catch::Detail::stringify(m_target); } - return std::is_permutation(m_target.begin(), m_target.end(), vec.begin()); - } - std::string describe() const override { - return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target); - } - private: - std::vector<T, AllocComp> const& m_target; - }; + private: + std::vector<T, AllocComp> const& m_target; + }; - } // namespace Vector + } // namespace Vector - // The following functions create the actual matcher objects. - // This allows the types to be inferred + // The following functions create the actual matcher objects. + // This allows the types to be inferred - template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp> - Vector::ContainsMatcher<T, AllocComp, AllocMatch> Contains( std::vector<T, AllocComp> const& comparator ) { - return Vector::ContainsMatcher<T, AllocComp, AllocMatch>( comparator ); - } + template <typename T, + typename AllocComp = std::allocator<T>, + typename AllocMatch = AllocComp> + Vector::ContainsMatcher<T, AllocComp, AllocMatch> + Contains(std::vector<T, AllocComp> const& comparator) { + return Vector::ContainsMatcher<T, AllocComp, AllocMatch>( + comparator); + } - template<typename T, typename Alloc = std::allocator<T>> - Vector::ContainsElementMatcher<T, Alloc> VectorContains( T const& comparator ) { - return Vector::ContainsElementMatcher<T, Alloc>( comparator ); - } + template <typename T, typename Alloc = std::allocator<T>> + Vector::ContainsElementMatcher<T, Alloc> + VectorContains(T const& comparator) { + return Vector::ContainsElementMatcher<T, Alloc>(comparator); + } - template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp> - Vector::EqualsMatcher<T, AllocComp, AllocMatch> Equals( std::vector<T, AllocComp> const& comparator ) { - return Vector::EqualsMatcher<T, AllocComp, AllocMatch>( comparator ); - } + template <typename T, + typename AllocComp = std::allocator<T>, + typename AllocMatch = AllocComp> + Vector::EqualsMatcher<T, AllocComp, AllocMatch> + Equals(std::vector<T, AllocComp> const& comparator) { + return Vector::EqualsMatcher<T, AllocComp, AllocMatch>(comparator); + } - template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp> - Vector::ApproxMatcher<T, AllocComp, AllocMatch> Approx( std::vector<T, AllocComp> const& comparator ) { - return Vector::ApproxMatcher<T, AllocComp, AllocMatch>( comparator ); - } + template <typename T, + typename AllocComp = std::allocator<T>, + typename AllocMatch = AllocComp> + Vector::ApproxMatcher<T, AllocComp, AllocMatch> + Approx(std::vector<T, AllocComp> const& comparator) { + return Vector::ApproxMatcher<T, AllocComp, AllocMatch>(comparator); + } - template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp> - Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch> UnorderedEquals(std::vector<T, AllocComp> const& target) { - return Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch>( target ); - } + template <typename T, + typename AllocComp = std::allocator<T>, + typename AllocMatch = AllocComp> + Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch> + UnorderedEquals(std::vector<T, AllocComp> const& target) { + return Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch>( + target); + } -} // namespace Matchers + } // namespace Matchers } // namespace Catch // end catch_matchers_vector.h namespace Catch { - template<typename ArgT, typename MatcherT> + template <typename ArgT, typename MatcherT> class MatchExpr : public ITransientExpression { ArgT const& m_arg; MatcherT m_matcher; StringRef m_matcherString; - public: - MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) - : ITransientExpression{ true, matcher.match( arg ) }, - m_arg( arg ), - m_matcher( matcher ), - m_matcherString( matcherString ) - {} - void streamReconstructedExpression( std::ostream &os ) const override { + public: + MatchExpr(ArgT const& arg, + MatcherT const& matcher, + StringRef const& matcherString) : + ITransientExpression{true, matcher.match(arg)}, + m_arg(arg), + m_matcher(matcher), + m_matcherString(matcherString) {} + + void streamReconstructedExpression(std::ostream& os) const override { auto matcherAsString = m_matcher.toString(); - os << Catch::Detail::stringify( m_arg ) << ' '; - if( matcherAsString == Detail::unprintableString ) + os << Catch::Detail::stringify(m_arg) << ' '; + if (matcherAsString == Detail::unprintableString) os << m_matcherString; else os << matcherAsString; @@ -3789,44 +4736,63 @@ using StringMatcher = Matchers::Impl::MatcherBase<std::string>; - void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ); + void handleExceptionMatchExpr(AssertionHandler& handler, + StringMatcher const& matcher, + StringRef const& matcherString); - template<typename ArgT, typename MatcherT> - auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> { - return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString ); + template <typename ArgT, typename MatcherT> + auto makeMatchExpr(ArgT const& arg, + MatcherT const& matcher, + StringRef const& matcherString) + -> MatchExpr<ArgT, MatcherT> { + return MatchExpr<ArgT, MatcherT>(arg, matcher, matcherString); } } // namespace Catch /////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \ - do { \ - Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ - INTERNAL_CATCH_TRY { \ - catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \ - } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \ - INTERNAL_CATCH_REACT( catchAssertionHandler ) \ - } while( false ) +#define INTERNAL_CHECK_THAT(macroName, matcher, resultDisposition, arg) \ + do { \ + Catch::AssertionHandler catchAssertionHandler( \ + macroName##_catch_sr, \ + CATCH_INTERNAL_LINEINFO, \ + CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY( \ + matcher), \ + resultDisposition); \ + INTERNAL_CATCH_TRY { \ + catchAssertionHandler.handleExpr( \ + Catch::makeMatchExpr(arg, matcher, #matcher##_catch_sr)); \ + } \ + INTERNAL_CATCH_CATCH(catchAssertionHandler) \ + INTERNAL_CATCH_REACT(catchAssertionHandler) \ + } while (false) /////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \ - do { \ - Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ - if( catchAssertionHandler.allowThrows() ) \ - try { \ - static_cast<void>(__VA_ARGS__ ); \ - catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ - } \ - catch( exceptionType const& ex ) { \ - catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \ - } \ - catch( ... ) { \ - catchAssertionHandler.handleUnexpectedInflightException(); \ - } \ - else \ - catchAssertionHandler.handleThrowingCallSkipped(); \ - INTERNAL_CATCH_REACT( catchAssertionHandler ) \ - } while( false ) +#define INTERNAL_CATCH_THROWS_MATCHES( \ + macroName, exceptionType, resultDisposition, matcher, ...) \ + do { \ + Catch:: \ + AssertionHandler \ + catchAssertionHandler(macroName##_catch_sr, \ + CATCH_INTERNAL_LINEINFO, \ + CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY( \ + exceptionType) "," \ + " " CATCH_INTERNAL_STRINGIFY(matcher), \ + resultDisposition); \ + if (catchAssertionHandler.allowThrows()) \ + try { \ + static_cast<void>(__VA_ARGS__); \ + catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ + } catch (exceptionType const& ex) { \ + catchAssertionHandler.handleExpr( \ + Catch::makeMatchExpr(ex, matcher, #matcher##_catch_sr)); \ + } catch (...) { \ + catchAssertionHandler.handleUnexpectedInflightException(); \ + } \ + else \ + catchAssertionHandler.handleThrowingCallSkipped(); \ + INTERNAL_CATCH_REACT(catchAssertionHandler) \ + } while (false) // end catch_capture_matchers.h #endif @@ -3834,7 +4800,6 @@ // start catch_interfaces_generatortracker.h - #include <memory> namespace Catch { @@ -3845,9 +4810,9 @@ GeneratorUntypedBase() = default; virtual ~GeneratorUntypedBase(); // Attempts to move the generator to the next element - // - // Returns true iff the move succeeded (and a valid element - // can be retrieved). + // + // Returns true iff the move succeeded (and a valid element + // can be retrieved). virtual bool next() = 0; }; using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>; @@ -3857,8 +4822,9 @@ struct IGeneratorTracker { virtual ~IGeneratorTracker(); virtual auto hasGenerator() const -> bool = 0; - virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0; - virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0; + virtual auto getGenerator() const + -> Generators::GeneratorBasePtr const& = 0; + virtual void setGenerator(Generators::GeneratorBasePtr&& generator) = 0; }; } // namespace Catch @@ -3870,39 +4836,36 @@ namespace Catch { #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) - template <typename Ex> - [[noreturn]] - void throw_exception(Ex const& e) { + template <typename Ex> [[noreturn]] void throw_exception(Ex const& e) { throw e; } #else // ^^ Exceptions are enabled // Exceptions are disabled vv - [[noreturn]] - void throw_exception(std::exception const& e); + [[noreturn]] void throw_exception(std::exception const& e); #endif - [[noreturn]] - void throw_logic_error(std::string const& msg); - [[noreturn]] - void throw_domain_error(std::string const& msg); - [[noreturn]] - void throw_runtime_error(std::string const& msg); + [[noreturn]] void throw_logic_error(std::string const& msg); + [[noreturn]] void throw_domain_error(std::string const& msg); + [[noreturn]] void throw_runtime_error(std::string const& msg); -} // namespace Catch; +} // namespace Catch -#define CATCH_MAKE_MSG(...) \ - (Catch::ReusableStringStream() << __VA_ARGS__).str() +#define CATCH_MAKE_MSG(...) (Catch::ReusableStringStream() << __VA_ARGS__).str() -#define CATCH_INTERNAL_ERROR(...) \ - Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__)) +#define CATCH_INTERNAL_ERROR(...) \ + Catch::throw_logic_error(CATCH_MAKE_MSG(CATCH_INTERNAL_LINEINFO \ + << ": Internal Catch2 error: " \ + << __VA_ARGS__)) -#define CATCH_ERROR(...) \ - Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ )) +#define CATCH_ERROR(...) Catch::throw_domain_error(CATCH_MAKE_MSG(__VA_ARGS__)) -#define CATCH_RUNTIME_ERROR(...) \ - Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ )) +#define CATCH_RUNTIME_ERROR(...) \ + Catch::throw_runtime_error(CATCH_MAKE_MSG(__VA_ARGS__)) -#define CATCH_ENFORCE( condition, ... ) \ - do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false) +#define CATCH_ENFORCE(condition, ...) \ + do { \ + if (!(condition)) \ + CATCH_ERROR(__VA_ARGS__); \ + } while (false) // end catch_enforce.h #include <memory> @@ -3914,422 +4877,448 @@ namespace Catch { -class GeneratorException : public std::exception { - const char* const m_msg = ""; - -public: - GeneratorException(const char* msg): - m_msg(msg) - {} - - const char* what() const noexcept override final; -}; - -namespace Generators { - - // !TBD move this into its own location? - namespace pf{ - template<typename T, typename... Args> - std::unique_ptr<T> make_unique( Args&&... args ) { - return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); - } - } - - template<typename T> - struct IGenerator : GeneratorUntypedBase { - virtual ~IGenerator() = default; - - // Returns the current element of the generator - // - // \Precondition The generator is either freshly constructed, - // or the last call to `next()` returned true - virtual T const& get() const = 0; - using type = T; - }; - - template<typename T> - class SingleValueGenerator final : public IGenerator<T> { - T m_value; - public: - SingleValueGenerator(T&& value) : m_value(std::move(value)) {} - - T const& get() const override { - return m_value; - } - bool next() override { - return false; - } - }; - - template<typename T> - class FixedValuesGenerator final : public IGenerator<T> { - static_assert(!std::is_same<T, bool>::value, - "FixedValuesGenerator does not support bools because of std::vector<bool>" - "specialization, use SingleValue Generator instead."); - std::vector<T> m_values; - size_t m_idx = 0; - public: - FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {} - - T const& get() const override { - return m_values[m_idx]; - } - bool next() override { - ++m_idx; - return m_idx < m_values.size(); - } - }; - - template <typename T> - class GeneratorWrapper final { - std::unique_ptr<IGenerator<T>> m_generator; - public: - GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator): - m_generator(std::move(generator)) - {} - T const& get() const { - return m_generator->get(); - } - bool next() { - return m_generator->next(); - } - }; - - template <typename T> - GeneratorWrapper<T> value(T&& value) { - return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value))); - } - template <typename T> - GeneratorWrapper<T> values(std::initializer_list<T> values) { - return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values)); - } - - template<typename T> - class Generators : public IGenerator<T> { - std::vector<GeneratorWrapper<T>> m_generators; - size_t m_current = 0; - - void populate(GeneratorWrapper<T>&& generator) { - m_generators.emplace_back(std::move(generator)); - } - void populate(T&& val) { - m_generators.emplace_back(value(std::forward<T>(val))); - } - template<typename U> - void populate(U&& val) { - populate(T(std::forward<U>(val))); - } - template<typename U, typename... Gs> - void populate(U&& valueOrGenerator, Gs &&... moreGenerators) { - populate(std::forward<U>(valueOrGenerator)); - populate(std::forward<Gs>(moreGenerators)...); - } + class GeneratorException : public std::exception { + const char* const m_msg = ""; public: - template <typename... Gs> - Generators(Gs &&... moreGenerators) { - m_generators.reserve(sizeof...(Gs)); - populate(std::forward<Gs>(moreGenerators)...); - } + GeneratorException(const char* msg) : m_msg(msg) {} - T const& get() const override { - return m_generators[m_current].get(); - } + const char* what() const noexcept override final; + }; - bool next() override { - if (m_current >= m_generators.size()) { - return false; + namespace Generators { + + // !TBD move this into its own location? + namespace pf { + template <typename T, typename... Args> + std::unique_ptr<T> make_unique(Args&&... args) { + return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } - const bool current_status = m_generators[m_current].next(); - if (!current_status) { - ++m_current; + } // namespace pf + + template <typename T> struct IGenerator : GeneratorUntypedBase { + virtual ~IGenerator() = default; + + // Returns the current element of the generator + // + // \Precondition The generator is either freshly constructed, + // or the last call to `next()` returned true + virtual T const& get() const = 0; + using type = T; + }; + + template <typename T> + class SingleValueGenerator final : public IGenerator<T> { + T m_value; + + public: + SingleValueGenerator(T&& value) : m_value(std::move(value)) {} + + T const& get() const override { return m_value; } + bool next() override { return false; } + }; + + template <typename T> + class FixedValuesGenerator final : public IGenerator<T> { + static_assert(!std::is_same<T, bool>::value, + "FixedValuesGenerator does not support bools because " + "of std::vector<bool>" + "specialization, use SingleValue Generator instead."); + std::vector<T> m_values; + size_t m_idx = 0; + + public: + FixedValuesGenerator(std::initializer_list<T> values) : + m_values(values) {} + + T const& get() const override { return m_values[m_idx]; } + bool next() override { + ++m_idx; + return m_idx < m_values.size(); } - return m_current < m_generators.size(); + }; + + template <typename T> class GeneratorWrapper final { + std::unique_ptr<IGenerator<T>> m_generator; + + public: + GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator) : + m_generator(std::move(generator)) {} + T const& get() const { return m_generator->get(); } + bool next() { return m_generator->next(); } + }; + + template <typename T> GeneratorWrapper<T> value(T&& value) { + return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>( + std::forward<T>(value))); } - }; - - template<typename... Ts> - GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples ) { - return values<std::tuple<Ts...>>( tuples ); - } - - // Tag type to signal that a generator sequence should convert arguments to a specific type - template <typename T> - struct as {}; - - template<typename T, typename... Gs> - auto makeGenerators( GeneratorWrapper<T>&& generator, Gs &&... moreGenerators ) -> Generators<T> { - return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...); - } - template<typename T> - auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> { - return Generators<T>(std::move(generator)); - } - template<typename T, typename... Gs> - auto makeGenerators( T&& val, Gs &&... moreGenerators ) -> Generators<T> { - return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... ); - } - template<typename T, typename U, typename... Gs> - auto makeGenerators( as<T>, U&& val, Gs &&... moreGenerators ) -> Generators<T> { - return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... ); - } - - auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker&; - - template<typename L> - // Note: The type after -> is weird, because VS2015 cannot parse - // the expression used in the typedef inside, when it is in - // return type. Yeah. - auto generate( StringRef generatorName, SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) { - using UnderlyingType = typename decltype(generatorExpression())::type; - - IGeneratorTracker& tracker = acquireGeneratorTracker( generatorName, lineInfo ); - if (!tracker.hasGenerator()) { - tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression())); + template <typename T> + GeneratorWrapper<T> values(std::initializer_list<T> values) { + return GeneratorWrapper<T>( + pf::make_unique<FixedValuesGenerator<T>>(values)); } - auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() ); - return generator.get(); - } + template <typename T> class Generators : public IGenerator<T> { + std::vector<GeneratorWrapper<T>> m_generators; + size_t m_current = 0; -} // namespace Generators + void populate(GeneratorWrapper<T>&& generator) { + m_generators.emplace_back(std::move(generator)); + } + void populate(T&& val) { + m_generators.emplace_back(value(std::forward<T>(val))); + } + template <typename U> void populate(U&& val) { + populate(T(std::forward<U>(val))); + } + template <typename U, typename... Gs> + void populate(U&& valueOrGenerator, Gs&&... moreGenerators) { + populate(std::forward<U>(valueOrGenerator)); + populate(std::forward<Gs>(moreGenerators)...); + } + + public: + template <typename... Gs> Generators(Gs&&... moreGenerators) { + m_generators.reserve(sizeof...(Gs)); + populate(std::forward<Gs>(moreGenerators)...); + } + + T const& get() const override { + return m_generators[m_current].get(); + } + + bool next() override { + if (m_current >= m_generators.size()) { + return false; + } + const bool current_status = m_generators[m_current].next(); + if (!current_status) { + ++m_current; + } + return m_current < m_generators.size(); + } + }; + + template <typename... Ts> + GeneratorWrapper<std::tuple<Ts...>> table( + std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> + tuples) { + return values<std::tuple<Ts...>>(tuples); + } + + // Tag type to signal that a generator sequence should convert arguments + // to a specific type + template <typename T> struct as {}; + + template <typename T, typename... Gs> + auto makeGenerators(GeneratorWrapper<T>&& generator, + Gs&&... moreGenerators) -> Generators<T> { + return Generators<T>(std::move(generator), + std::forward<Gs>(moreGenerators)...); + } + template <typename T> + auto makeGenerators(GeneratorWrapper<T>&& generator) -> Generators<T> { + return Generators<T>(std::move(generator)); + } + template <typename T, typename... Gs> + auto makeGenerators(T&& val, Gs&&... moreGenerators) -> Generators<T> { + return makeGenerators(value(std::forward<T>(val)), + std::forward<Gs>(moreGenerators)...); + } + template <typename T, typename U, typename... Gs> + auto makeGenerators(as<T>, U&& val, Gs&&... moreGenerators) + -> Generators<T> { + return makeGenerators(value(T(std::forward<U>(val))), + std::forward<Gs>(moreGenerators)...); + } + + auto acquireGeneratorTracker(StringRef generatorName, + SourceLineInfo const& lineInfo) + -> IGeneratorTracker&; + + template <typename L> + // Note: The type after -> is weird, because VS2015 cannot parse + // the expression used in the typedef inside, when it is in + // return type. Yeah. + auto generate(StringRef generatorName, + SourceLineInfo const& lineInfo, + L const& generatorExpression) + -> decltype(std::declval<decltype(generatorExpression())>().get()) { + using UnderlyingType = + typename decltype(generatorExpression())::type; + + IGeneratorTracker& tracker = + acquireGeneratorTracker(generatorName, lineInfo); + if (!tracker.hasGenerator()) { + tracker.setGenerator( + pf::make_unique<Generators<UnderlyingType>>( + generatorExpression())); + } + + auto const& generator = + static_cast<IGenerator<UnderlyingType> const&>( + *tracker.getGenerator()); + return generator.get(); + } + + } // namespace Generators } // namespace Catch -#define GENERATE( ... ) \ - Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \ - CATCH_INTERNAL_LINEINFO, \ - [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace) -#define GENERATE_COPY( ... ) \ - Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \ - CATCH_INTERNAL_LINEINFO, \ - [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace) -#define GENERATE_REF( ... ) \ - Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \ - CATCH_INTERNAL_LINEINFO, \ - [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace) +#define GENERATE(...) \ + Catch::Generators::generate( \ + INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \ + CATCH_INTERNAL_LINEINFO, \ + [] { \ + using namespace Catch::Generators; \ + return makeGenerators(__VA_ARGS__); \ + }) // NOLINT(google-build-using-namespace) +#define GENERATE_COPY(...) \ + Catch::Generators::generate( \ + INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \ + CATCH_INTERNAL_LINEINFO, \ + [=] { \ + using namespace Catch::Generators; \ + return makeGenerators(__VA_ARGS__); \ + }) // NOLINT(google-build-using-namespace) +#define GENERATE_REF(...) \ + Catch::Generators::generate( \ + INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \ + CATCH_INTERNAL_LINEINFO, \ + [&] { \ + using namespace Catch::Generators; \ + return makeGenerators(__VA_ARGS__); \ + }) // NOLINT(google-build-using-namespace) // end catch_generators.hpp // start catch_generators_generic.hpp namespace Catch { -namespace Generators { + namespace Generators { - template <typename T> - class TakeGenerator : public IGenerator<T> { - GeneratorWrapper<T> m_generator; - size_t m_returned = 0; - size_t m_target; - public: - TakeGenerator(size_t target, GeneratorWrapper<T>&& generator): - m_generator(std::move(generator)), - m_target(target) - { - assert(target != 0 && "Empty generators are not allowed"); - } - T const& get() const override { - return m_generator.get(); - } - bool next() override { - ++m_returned; - if (m_returned >= m_target) { - return false; + template <typename T> class TakeGenerator : public IGenerator<T> { + GeneratorWrapper<T> m_generator; + size_t m_returned = 0; + size_t m_target; + + public: + TakeGenerator(size_t target, GeneratorWrapper<T>&& generator) : + m_generator(std::move(generator)), m_target(target) { + assert(target != 0 && "Empty generators are not allowed"); } + T const& get() const override { return m_generator.get(); } + bool next() override { + ++m_returned; + if (m_returned >= m_target) { + return false; + } - const auto success = m_generator.next(); - // If the underlying generator does not contain enough values - // then we cut short as well - if (!success) { - m_returned = m_target; + const auto success = m_generator.next(); + // If the underlying generator does not contain enough values + // then we cut short as well + if (!success) { + m_returned = m_target; + } + return success; } - return success; + }; + + template <typename T> + GeneratorWrapper<T> take(size_t target, + GeneratorWrapper<T>&& generator) { + return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>( + target, std::move(generator))); } - }; - template <typename T> - GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) { - return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator))); - } + template <typename T, typename Predicate> + class FilterGenerator : public IGenerator<T> { + GeneratorWrapper<T> m_generator; + Predicate m_predicate; - template <typename T, typename Predicate> - class FilterGenerator : public IGenerator<T> { - GeneratorWrapper<T> m_generator; - Predicate m_predicate; - public: - template <typename P = Predicate> - FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator): - m_generator(std::move(generator)), - m_predicate(std::forward<P>(pred)) - { - if (!m_predicate(m_generator.get())) { - // It might happen that there are no values that pass the - // filter. In that case we throw an exception. - auto has_initial_value = next(); - if (!has_initial_value) { - Catch::throw_exception(GeneratorException("No valid value found in filtered generator")); + public: + template <typename P = Predicate> + FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator) : + m_generator(std::move(generator)), + m_predicate(std::forward<P>(pred)) { + if (!m_predicate(m_generator.get())) { + // It might happen that there are no values that pass the + // filter. In that case we throw an exception. + auto has_initial_value = next(); + if (!has_initial_value) { + Catch::throw_exception(GeneratorException( + "No valid value found in filtered generator")); + } } } - } - T const& get() const override { - return m_generator.get(); - } + T const& get() const override { return m_generator.get(); } - bool next() override { - bool success = m_generator.next(); - if (!success) { - return false; - } - while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true); - return success; - } - }; - - template <typename T, typename Predicate> - GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) { - return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator)))); - } - - template <typename T> - class RepeatGenerator : public IGenerator<T> { - static_assert(!std::is_same<T, bool>::value, - "RepeatGenerator currently does not support bools" - "because of std::vector<bool> specialization"); - GeneratorWrapper<T> m_generator; - mutable std::vector<T> m_returned; - size_t m_target_repeats; - size_t m_current_repeat = 0; - size_t m_repeat_index = 0; - public: - RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator): - m_generator(std::move(generator)), - m_target_repeats(repeats) - { - assert(m_target_repeats > 0 && "Repeat generator must repeat at least once"); - } - - T const& get() const override { - if (m_current_repeat == 0) { - m_returned.push_back(m_generator.get()); - return m_returned.back(); - } - return m_returned[m_repeat_index]; - } - - bool next() override { - // There are 2 basic cases: - // 1) We are still reading the generator - // 2) We are reading our own cache - - // In the first case, we need to poke the underlying generator. - // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache - if (m_current_repeat == 0) { - const auto success = m_generator.next(); + bool next() override { + bool success = m_generator.next(); if (!success) { + return false; + } + while (!m_predicate(m_generator.get()) && + (success = m_generator.next()) == true) + ; + return success; + } + }; + + template <typename T, typename Predicate> + GeneratorWrapper<T> filter(Predicate&& pred, + GeneratorWrapper<T>&& generator) { + return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>( + pf::make_unique<FilterGenerator<T, Predicate>>( + std::forward<Predicate>(pred), std::move(generator)))); + } + + template <typename T> class RepeatGenerator : public IGenerator<T> { + static_assert(!std::is_same<T, bool>::value, + "RepeatGenerator currently does not support bools" + "because of std::vector<bool> specialization"); + GeneratorWrapper<T> m_generator; + mutable std::vector<T> m_returned; + size_t m_target_repeats; + size_t m_current_repeat = 0; + size_t m_repeat_index = 0; + + public: + RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator) : + m_generator(std::move(generator)), m_target_repeats(repeats) { + assert(m_target_repeats > 0 && + "Repeat generator must repeat at least once"); + } + + T const& get() const override { + if (m_current_repeat == 0) { + m_returned.push_back(m_generator.get()); + return m_returned.back(); + } + return m_returned[m_repeat_index]; + } + + bool next() override { + // There are 2 basic cases: + // 1) We are still reading the generator + // 2) We are reading our own cache + + // In the first case, we need to poke the underlying generator. + // If it happily moves, we are left in that state, otherwise it + // is time to start reading from our cache + if (m_current_repeat == 0) { + const auto success = m_generator.next(); + if (!success) { + ++m_current_repeat; + } + return m_current_repeat < m_target_repeats; + } + + // In the second case, we need to move indices forward and check + // that we haven't run up against the end + ++m_repeat_index; + if (m_repeat_index == m_returned.size()) { + m_repeat_index = 0; ++m_current_repeat; } return m_current_repeat < m_target_repeats; } + }; - // In the second case, we need to move indices forward and check that we haven't run up against the end - ++m_repeat_index; - if (m_repeat_index == m_returned.size()) { - m_repeat_index = 0; - ++m_current_repeat; + template <typename T> + GeneratorWrapper<T> repeat(size_t repeats, + GeneratorWrapper<T>&& generator) { + return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>( + repeats, std::move(generator))); + } + + template <typename T, typename U, typename Func> + class MapGenerator : public IGenerator<T> { + // TBD: provide static assert for mapping function, for friendly + // error message + GeneratorWrapper<U> m_generator; + Func m_function; + // To avoid returning dangling reference, we have to save the values + T m_cache; + + public: + template <typename F2 = Func> + MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) : + m_generator(std::move(generator)), + m_function(std::forward<F2>(function)), + m_cache(m_function(m_generator.get())) {} + + T const& get() const override { return m_cache; } + bool next() override { + const auto success = m_generator.next(); + if (success) { + m_cache = m_function(m_generator.get()); + } + return success; } - return m_current_repeat < m_target_repeats; + }; + + template <typename Func, + typename U, + typename T = FunctionReturnType<Func, U>> + GeneratorWrapper<T> map(Func&& function, + GeneratorWrapper<U>&& generator) { + return GeneratorWrapper<T>( + pf::make_unique<MapGenerator<T, U, Func>>( + std::forward<Func>(function), std::move(generator))); } - }; - template <typename T> - GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) { - return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator))); - } - - template <typename T, typename U, typename Func> - class MapGenerator : public IGenerator<T> { - // TBD: provide static assert for mapping function, for friendly error message - GeneratorWrapper<U> m_generator; - Func m_function; - // To avoid returning dangling reference, we have to save the values - T m_cache; - public: - template <typename F2 = Func> - MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) : - m_generator(std::move(generator)), - m_function(std::forward<F2>(function)), - m_cache(m_function(m_generator.get())) - {} - - T const& get() const override { - return m_cache; + template <typename T, typename U, typename Func> + GeneratorWrapper<T> map(Func&& function, + GeneratorWrapper<U>&& generator) { + return GeneratorWrapper<T>( + pf::make_unique<MapGenerator<T, U, Func>>( + std::forward<Func>(function), std::move(generator))); } - bool next() override { - const auto success = m_generator.next(); - if (success) { - m_cache = m_function(m_generator.get()); + + template <typename T> + class ChunkGenerator final : public IGenerator<std::vector<T>> { + std::vector<T> m_chunk; + size_t m_chunk_size; + GeneratorWrapper<T> m_generator; + bool m_used_up = false; + + public: + ChunkGenerator(size_t size, GeneratorWrapper<T> generator) : + m_chunk_size(size), m_generator(std::move(generator)) { + m_chunk.reserve(m_chunk_size); + if (m_chunk_size != 0) { + m_chunk.push_back(m_generator.get()); + for (size_t i = 1; i < m_chunk_size; ++i) { + if (!m_generator.next()) { + Catch::throw_exception(GeneratorException( + "Not enough values to initialize the first " + "chunk")); + } + m_chunk.push_back(m_generator.get()); + } + } } - return success; - } - }; - - template <typename Func, typename U, typename T = FunctionReturnType<Func, U>> - GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) { - return GeneratorWrapper<T>( - pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator)) - ); - } - - template <typename T, typename U, typename Func> - GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) { - return GeneratorWrapper<T>( - pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator)) - ); - } - - template <typename T> - class ChunkGenerator final : public IGenerator<std::vector<T>> { - std::vector<T> m_chunk; - size_t m_chunk_size; - GeneratorWrapper<T> m_generator; - bool m_used_up = false; - public: - ChunkGenerator(size_t size, GeneratorWrapper<T> generator) : - m_chunk_size(size), m_generator(std::move(generator)) - { - m_chunk.reserve(m_chunk_size); - if (m_chunk_size != 0) { - m_chunk.push_back(m_generator.get()); - for (size_t i = 1; i < m_chunk_size; ++i) { + std::vector<T> const& get() const override { return m_chunk; } + bool next() override { + m_chunk.clear(); + for (size_t idx = 0; idx < m_chunk_size; ++idx) { if (!m_generator.next()) { - Catch::throw_exception(GeneratorException("Not enough values to initialize the first chunk")); + return false; } m_chunk.push_back(m_generator.get()); } + return true; } - } - std::vector<T> const& get() const override { - return m_chunk; - } - bool next() override { - m_chunk.clear(); - for (size_t idx = 0; idx < m_chunk_size; ++idx) { - if (!m_generator.next()) { - return false; - } - m_chunk.push_back(m_generator.get()); - } - return true; - } - }; + }; - template <typename T> - GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) { - return GeneratorWrapper<std::vector<T>>( - pf::make_unique<ChunkGenerator<T>>(size, std::move(generator)) - ); - } + template <typename T> + GeneratorWrapper<std::vector<T>> + chunk(size_t size, GeneratorWrapper<T>&& generator) { + return GeneratorWrapper<std::vector<T>>( + pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))); + } -} // namespace Generators + } // namespace Generators } // namespace Catch // end catch_generators_generic.hpp @@ -4348,8 +5337,7 @@ using IConfigPtr = std::shared_ptr<IConfig const>; - struct IContext - { + struct IContext { virtual ~IContext(); virtual IResultCapture* getResultCapture() = 0; @@ -4357,38 +5345,33 @@ virtual IConfigPtr const& getConfig() const = 0; }; - struct IMutableContext : IContext - { + struct IMutableContext : IContext { virtual ~IMutableContext(); - virtual void setResultCapture( IResultCapture* resultCapture ) = 0; - virtual void setRunner( IRunner* runner ) = 0; - virtual void setConfig( IConfigPtr const& config ) = 0; + virtual void setResultCapture(IResultCapture* resultCapture) = 0; + virtual void setRunner(IRunner* runner) = 0; + virtual void setConfig(IConfigPtr const& config) = 0; private: - static IMutableContext *currentContext; + static IMutableContext* currentContext; friend IMutableContext& getCurrentMutableContext(); friend void cleanUpContext(); static void createContext(); }; - inline IMutableContext& getCurrentMutableContext() - { - if( !IMutableContext::currentContext ) + inline IMutableContext& getCurrentMutableContext() { + if (!IMutableContext::currentContext) IMutableContext::createContext(); // NOLINTNEXTLINE(clang-analyzer-core.uninitialized.UndefReturn) return *IMutableContext::currentContext; } - inline IContext& getCurrentContext() - { - return getCurrentMutableContext(); - } + inline IContext& getCurrentContext() { return getCurrentMutableContext(); } void cleanUpContext(); class SimplePcg32; SimplePcg32& rng(); -} +} // namespace Catch // end catch_context.h // start catch_interfaces_config.h @@ -4398,37 +5381,31 @@ namespace Catch { // An optional type - template<typename T> - class Option { + template <typename T> class Option { public: - Option() : nullableValue( nullptr ) {} - Option( T const& _value ) - : nullableValue( new( storage ) T( _value ) ) - {} - Option( Option const& _other ) - : nullableValue( _other ? new( storage ) T( *_other ) : nullptr ) - {} + Option() : nullableValue(nullptr) {} + Option(T const& _value) : nullableValue(new (storage) T(_value)) {} + Option(Option const& _other) : + nullableValue(_other ? new (storage) T(*_other) : nullptr) {} - ~Option() { - reset(); - } + ~Option() { reset(); } - Option& operator= ( Option const& _other ) { - if( &_other != this ) { + Option& operator=(Option const& _other) { + if (&_other != this) { reset(); - if( _other ) - nullableValue = new( storage ) T( *_other ); + if (_other) + nullableValue = new (storage) T(*_other); } return *this; } - Option& operator = ( T const& _value ) { + Option& operator=(T const& _value) { reset(); - nullableValue = new( storage ) T( _value ); + nullableValue = new (storage) T(_value); return *this; } void reset() { - if( nullableValue ) + if (nullableValue) nullableValue->~T(); nullableValue = nullptr; } @@ -4438,20 +5415,18 @@ T* operator->() { return nullableValue; } const T* operator->() const { return nullableValue; } - T valueOr( T const& defaultValue ) const { + T valueOr(T const& defaultValue) const { return nullableValue ? *nullableValue : defaultValue; } bool some() const { return nullableValue != nullptr; } bool none() const { return nullableValue == nullptr; } - bool operator !() const { return nullableValue == nullptr; } - explicit operator bool() const { - return some(); - } + bool operator!() const { return nullableValue == nullptr; } + explicit operator bool() const { return some(); } private: - T *nullableValue; + T* nullableValue; alignas(alignof(T)) char storage[sizeof(T)]; }; @@ -4466,39 +5441,33 @@ namespace Catch { - enum class Verbosity { - Quiet = 0, - Normal, - High + enum class Verbosity { Quiet = 0, Normal, High }; + + struct WarnAbout { + enum What { Nothing = 0x00, NoAssertions = 0x01, NoTests = 0x02 }; }; - struct WarnAbout { enum What { - Nothing = 0x00, - NoAssertions = 0x01, - NoTests = 0x02 - }; }; - - struct ShowDurations { enum OrNot { - DefaultForReporter, - Always, - Never - }; }; - struct RunTests { enum InWhatOrder { - InDeclarationOrder, - InLexicographicalOrder, - InRandomOrder - }; }; - struct UseColour { enum YesOrNo { - Auto, - Yes, - No - }; }; - struct WaitForKeypress { enum When { - Never, - BeforeStart = 1, - BeforeExit = 2, - BeforeStartAndExit = BeforeStart | BeforeExit - }; }; + struct ShowDurations { + enum OrNot { DefaultForReporter, Always, Never }; + }; + struct RunTests { + enum InWhatOrder { + InDeclarationOrder, + InLexicographicalOrder, + InRandomOrder + }; + }; + struct UseColour { + enum YesOrNo { Auto, Yes, No }; + }; + struct WaitForKeypress { + enum When { + Never, + BeforeStart = 1, + BeforeExit = 2, + BeforeStartAndExit = BeforeStart | BeforeExit + }; + }; class TestSpec; @@ -4534,7 +5503,7 @@ }; using IConfigPtr = std::shared_ptr<IConfig const>; -} +} // namespace Catch // end catch_interfaces_config.h // start catch_random_number_generator.h @@ -4550,17 +5519,16 @@ // The implementation is based on the PCG family (http://pcg-random.org) class SimplePcg32 { using state_type = std::uint64_t; + public: using result_type = std::uint32_t; - static constexpr result_type (min)() { - return 0; - } - static constexpr result_type (max)() { + static constexpr result_type(min)() { return 0; } + static constexpr result_type(max)() { return static_cast<result_type>(-1); } // Provide some default initial state for the default constructor - SimplePcg32():SimplePcg32(0xed743cc4U) {} + SimplePcg32() : SimplePcg32(0xed743cc4U) {} explicit SimplePcg32(result_type seed_); @@ -4581,7 +5549,8 @@ // is chosen -- we take it as a constant for Catch2, so we only // need to deal with seeding the main state. // Picked by reading 8 bytes from `/dev/random` :-) - static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL; + static const std::uint64_t s_inc = + (0x13ed0cc53f939476ULL << 1ULL) | 1ULL; }; } // end namespace Catch @@ -4590,157 +5559,162 @@ #include <random> namespace Catch { -namespace Generators { + namespace Generators { -template <typename Float> -class RandomFloatingGenerator final : public IGenerator<Float> { - Catch::SimplePcg32& m_rng; - std::uniform_real_distribution<Float> m_dist; - Float m_current_number; -public: + template <typename Float> + class RandomFloatingGenerator final : public IGenerator<Float> { + Catch::SimplePcg32& m_rng; + std::uniform_real_distribution<Float> m_dist; + Float m_current_number; - RandomFloatingGenerator(Float a, Float b): - m_rng(rng()), - m_dist(a, b) { - static_cast<void>(next()); - } + public: + RandomFloatingGenerator(Float a, Float b) : + m_rng(rng()), m_dist(a, b) { + static_cast<void>(next()); + } - Float const& get() const override { - return m_current_number; - } - bool next() override { - m_current_number = m_dist(m_rng); - return true; - } -}; + Float const& get() const override { return m_current_number; } + bool next() override { + m_current_number = m_dist(m_rng); + return true; + } + }; -template <typename Integer> -class RandomIntegerGenerator final : public IGenerator<Integer> { - Catch::SimplePcg32& m_rng; - std::uniform_int_distribution<Integer> m_dist; - Integer m_current_number; -public: + template <typename Integer> + class RandomIntegerGenerator final : public IGenerator<Integer> { + Catch::SimplePcg32& m_rng; + std::uniform_int_distribution<Integer> m_dist; + Integer m_current_number; - RandomIntegerGenerator(Integer a, Integer b): - m_rng(rng()), - m_dist(a, b) { - static_cast<void>(next()); - } + public: + RandomIntegerGenerator(Integer a, Integer b) : + m_rng(rng()), m_dist(a, b) { + static_cast<void>(next()); + } - Integer const& get() const override { - return m_current_number; - } - bool next() override { - m_current_number = m_dist(m_rng); - return true; - } -}; + Integer const& get() const override { return m_current_number; } + bool next() override { + m_current_number = m_dist(m_rng); + return true; + } + }; -// TODO: Ideally this would be also constrained against the various char types, -// but I don't expect users to run into that in practice. -template <typename T> -typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value, -GeneratorWrapper<T>>::type -random(T a, T b) { - return GeneratorWrapper<T>( - pf::make_unique<RandomIntegerGenerator<T>>(a, b) - ); -} - -template <typename T> -typename std::enable_if<std::is_floating_point<T>::value, -GeneratorWrapper<T>>::type -random(T a, T b) { - return GeneratorWrapper<T>( - pf::make_unique<RandomFloatingGenerator<T>>(a, b) - ); -} - -template <typename T> -class RangeGenerator final : public IGenerator<T> { - T m_current; - T m_end; - T m_step; - bool m_positive; - -public: - RangeGenerator(T const& start, T const& end, T const& step): - m_current(start), - m_end(end), - m_step(step), - m_positive(m_step > T(0)) - { - assert(m_current != m_end && "Range start and end cannot be equal"); - assert(m_step != T(0) && "Step size cannot be zero"); - assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end"); - } - - RangeGenerator(T const& start, T const& end): - RangeGenerator(start, end, (start < end) ? T(1) : T(-1)) - {} - - T const& get() const override { - return m_current; - } - - bool next() override { - m_current += m_step; - return (m_positive) ? (m_current < m_end) : (m_current > m_end); - } -}; - -template <typename T> -GeneratorWrapper<T> range(T const& start, T const& end, T const& step) { - static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value, "Type must be numeric"); - return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step)); -} - -template <typename T> -GeneratorWrapper<T> range(T const& start, T const& end) { - static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer"); - return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end)); -} - -template <typename T> -class IteratorGenerator final : public IGenerator<T> { - static_assert(!std::is_same<T, bool>::value, - "IteratorGenerator currently does not support bools" - "because of std::vector<bool> specialization"); - - std::vector<T> m_elems; - size_t m_current = 0; -public: - template <typename InputIterator, typename InputSentinel> - IteratorGenerator(InputIterator first, InputSentinel last):m_elems(first, last) { - if (m_elems.empty()) { - Catch::throw_exception(GeneratorException("IteratorGenerator received no valid values")); + // TODO: Ideally this would be also constrained against the various char + // types, + // but I don't expect users to run into that in practice. + template <typename T> + typename std::enable_if<std::is_integral<T>::value && + !std::is_same<T, bool>::value, + GeneratorWrapper<T>>::type + random(T a, T b) { + return GeneratorWrapper<T>( + pf::make_unique<RandomIntegerGenerator<T>>(a, b)); } - } - T const& get() const override { - return m_elems[m_current]; - } + template <typename T> + typename std::enable_if<std::is_floating_point<T>::value, + GeneratorWrapper<T>>::type + random(T a, T b) { + return GeneratorWrapper<T>( + pf::make_unique<RandomFloatingGenerator<T>>(a, b)); + } - bool next() override { - ++m_current; - return m_current != m_elems.size(); - } -}; + template <typename T> + class RangeGenerator final : public IGenerator<T> { + T m_current; + T m_end; + T m_step; + bool m_positive; -template <typename InputIterator, - typename InputSentinel, - typename ResultType = typename std::iterator_traits<InputIterator>::value_type> -GeneratorWrapper<ResultType> from_range(InputIterator from, InputSentinel to) { - return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(from, to)); -} + public: + RangeGenerator(T const& start, T const& end, T const& step) : + m_current(start), + m_end(end), + m_step(step), + m_positive(m_step > T(0)) { + assert(m_current != m_end && + "Range start and end cannot be equal"); + assert(m_step != T(0) && "Step size cannot be zero"); + assert(((m_positive && m_current <= m_end) || + (!m_positive && m_current >= m_end)) && + "Step moves away from end"); + } -template <typename Container, - typename ResultType = typename Container::value_type> -GeneratorWrapper<ResultType> from_range(Container const& cnt) { - return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(cnt.begin(), cnt.end())); -} + RangeGenerator(T const& start, T const& end) : + RangeGenerator(start, end, (start < end) ? T(1) : T(-1)) {} -} // namespace Generators + T const& get() const override { return m_current; } + + bool next() override { + m_current += m_step; + return (m_positive) ? (m_current < m_end) : (m_current > m_end); + } + }; + + template <typename T> + GeneratorWrapper<T> range(T const& start, T const& end, T const& step) { + static_assert(std::is_arithmetic<T>::value && + !std::is_same<T, bool>::value, + "Type must be numeric"); + return GeneratorWrapper<T>( + pf::make_unique<RangeGenerator<T>>(start, end, step)); + } + + template <typename T> + GeneratorWrapper<T> range(T const& start, T const& end) { + static_assert(std::is_integral<T>::value && + !std::is_same<T, bool>::value, + "Type must be an integer"); + return GeneratorWrapper<T>( + pf::make_unique<RangeGenerator<T>>(start, end)); + } + + template <typename T> + class IteratorGenerator final : public IGenerator<T> { + static_assert(!std::is_same<T, bool>::value, + "IteratorGenerator currently does not support bools" + "because of std::vector<bool> specialization"); + + std::vector<T> m_elems; + size_t m_current = 0; + + public: + template <typename InputIterator, typename InputSentinel> + IteratorGenerator(InputIterator first, InputSentinel last) : + m_elems(first, last) { + if (m_elems.empty()) { + Catch::throw_exception(GeneratorException( + "IteratorGenerator received no valid values")); + } + } + + T const& get() const override { return m_elems[m_current]; } + + bool next() override { + ++m_current; + return m_current != m_elems.size(); + } + }; + + template <typename InputIterator, + typename InputSentinel, + typename ResultType = + typename std::iterator_traits<InputIterator>::value_type> + GeneratorWrapper<ResultType> from_range(InputIterator from, + InputSentinel to) { + return GeneratorWrapper<ResultType>( + pf::make_unique<IteratorGenerator<ResultType>>(from, to)); + } + + template <typename Container, + typename ResultType = typename Container::value_type> + GeneratorWrapper<ResultType> from_range(Container const& cnt) { + return GeneratorWrapper<ResultType>( + pf::make_unique<IteratorGenerator<ResultType>>(cnt.begin(), + cnt.end())); + } + + } // namespace Generators } // namespace Catch // end catch_generators_specific.hpp @@ -4763,7 +5737,7 @@ struct ITestInvoker; struct TestCaseInfo { - enum SpecialProperties{ + enum SpecialProperties { None = 0, IsHidden = 1 << 1, ShouldFail = 1 << 2, @@ -4773,13 +5747,14 @@ Benchmark = 1 << 6 }; - TestCaseInfo( std::string const& _name, - std::string const& _className, - std::string const& _description, - std::vector<std::string> const& _tags, - SourceLineInfo const& _lineInfo ); + TestCaseInfo(std::string const& _name, + std::string const& _className, + std::string const& _description, + std::vector<std::string> const& _tags, + SourceLineInfo const& _lineInfo); - friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ); + friend void setTags(TestCaseInfo& testCaseInfo, + std::vector<std::string> tags); bool isHidden() const; bool throws() const; @@ -4799,27 +5774,26 @@ class TestCase : public TestCaseInfo { public: + TestCase(ITestInvoker* testCase, TestCaseInfo&& info); - TestCase( ITestInvoker* testCase, TestCaseInfo&& info ); - - TestCase withName( std::string const& _newName ) const; + TestCase withName(std::string const& _newName) const; void invoke() const; TestCaseInfo const& getTestCaseInfo() const; - bool operator == ( TestCase const& other ) const; - bool operator < ( TestCase const& other ) const; + bool operator==(TestCase const& other) const; + bool operator<(TestCase const& other) const; private: std::shared_ptr<ITestInvoker> test; }; - TestCase makeTestCase( ITestInvoker* testCase, - std::string const& className, - NameAndTags const& nameAndTags, - SourceLineInfo const& lineInfo ); -} + TestCase makeTestCase(ITestInvoker* testCase, + std::string const& className, + NameAndTags const& nameAndTags, + SourceLineInfo const& lineInfo); +} // namespace Catch #ifdef __clang__ #pragma clang diagnostic pop @@ -4834,7 +5808,7 @@ virtual ~IRunner(); virtual bool aborting() const = 0; }; -} +} // namespace Catch // end catch_interfaces_runner.h @@ -4856,8 +5830,8 @@ @optional --(void) setUp; --(void) tearDown; +- (void)setUp; +- (void)tearDown; @end @@ -4866,17 +5840,18 @@ class OcMethod : public ITestInvoker { public: - OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {} + OcMethod(Class cls, SEL sel) : m_cls(cls), m_sel(sel) {} virtual void invoke() const { id obj = [[m_cls alloc] init]; - performOptionalSelector( obj, @selector(setUp) ); - performOptionalSelector( obj, m_sel ); - performOptionalSelector( obj, @selector(tearDown) ); + performOptionalSelector(obj, @selector(setUp)); + performOptionalSelector(obj, m_sel); + performOptionalSelector(obj, @selector(tearDown)); - arcSafeRelease( obj ); + arcSafeRelease(obj); } + private: virtual ~OcMethod() {} @@ -4884,43 +5859,53 @@ SEL m_sel; }; - namespace Detail{ + namespace Detail { - inline std::string getAnnotation( Class cls, - std::string const& annotationName, - std::string const& testCaseName ) { - NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()]; - SEL sel = NSSelectorFromString( selStr ); - arcSafeRelease( selStr ); - id value = performOptionalSelector( cls, sel ); - if( value ) + inline std::string getAnnotation(Class cls, + std::string const& annotationName, + std::string const& testCaseName) { + NSString* selStr = + [[NSString alloc] initWithFormat:@"Catch_%s_%s", + annotationName.c_str(), + testCaseName.c_str()]; + SEL sel = NSSelectorFromString(selStr); + arcSafeRelease(selStr); + id value = performOptionalSelector(cls, sel); + if (value) return [(NSString*)value UTF8String]; return ""; } - } + } // namespace Detail inline std::size_t registerTestMethods() { std::size_t noTestMethods = 0; - int noClasses = objc_getClassList( nullptr, 0 ); + int noClasses = objc_getClassList(nullptr, 0); - Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses); - objc_getClassList( classes, noClasses ); + Class* classes = + (CATCH_UNSAFE_UNRETAINED Class*)malloc(sizeof(Class) * noClasses); + objc_getClassList(classes, noClasses); - for( int c = 0; c < noClasses; c++ ) { + for (int c = 0; c < noClasses; c++) { Class cls = classes[c]; { u_int count; - Method* methods = class_copyMethodList( cls, &count ); - for( u_int m = 0; m < count ; m++ ) { + Method* methods = class_copyMethodList(cls, &count); + for (u_int m = 0; m < count; m++) { SEL selector = method_getName(methods[m]); std::string methodName = sel_getName(selector); - if( startsWith( methodName, "Catch_TestCase_" ) ) { - std::string testCaseName = methodName.substr( 15 ); - std::string name = Detail::getAnnotation( cls, "Name", testCaseName ); - std::string desc = Detail::getAnnotation( cls, "Description", testCaseName ); - const char* className = class_getName( cls ); + if (startsWith(methodName, "Catch_TestCase_")) { + std::string testCaseName = methodName.substr(15); + std::string name = + Detail::getAnnotation(cls, "Name", testCaseName); + std::string desc = Detail::getAnnotation( + cls, "Description", testCaseName); + const char* className = class_getName(cls); - getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) ); + getMutableRegistryHub().registerTest(makeTestCase( + new OcMethod(cls, selector), + className, + NameAndTags(name.c_str(), desc.c_str()), + SourceLineInfo("", 0))); noTestMethods++; } } @@ -4934,87 +5919,94 @@ namespace Matchers { namespace Impl { - namespace NSStringMatchers { + namespace NSStringMatchers { - struct StringHolder : MatcherBase<NSString*>{ - StringHolder( NSString* substr ) : m_substr( [substr copy] ){} - StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){} - StringHolder() { - arcSafeRelease( m_substr ); - } + struct StringHolder : MatcherBase<NSString*> { + StringHolder(NSString* substr) : m_substr([substr copy]) {} + StringHolder(StringHolder const& other) : + m_substr([other.m_substr copy]) {} + StringHolder() { arcSafeRelease(m_substr); } - bool match( NSString* str ) const override { - return false; - } + bool match(NSString* str) const override { return false; } - NSString* CATCH_ARC_STRONG m_substr; - }; + NSString* CATCH_ARC_STRONG m_substr; + }; - struct Equals : StringHolder { - Equals( NSString* substr ) : StringHolder( substr ){} + struct Equals : StringHolder { + Equals(NSString* substr) : StringHolder(substr) {} - bool match( NSString* str ) const override { - return (str != nil || m_substr == nil ) && - [str isEqualToString:m_substr]; - } + bool match(NSString* str) const override { + return (str != nil || m_substr == nil) && + [str isEqualToString:m_substr]; + } - std::string describe() const override { - return "equals string: " + Catch::Detail::stringify( m_substr ); - } - }; + std::string describe() const override { + return "equals string: " + + Catch::Detail::stringify(m_substr); + } + }; - struct Contains : StringHolder { - Contains( NSString* substr ) : StringHolder( substr ){} + struct Contains : StringHolder { + Contains(NSString* substr) : StringHolder(substr) {} - bool match( NSString* str ) const override { - return (str != nil || m_substr == nil ) && - [str rangeOfString:m_substr].location != NSNotFound; - } + bool match(NSString* str) const override { + return (str != nil || m_substr == nil) && + [str rangeOfString:m_substr].location != + NSNotFound; + } - std::string describe() const override { - return "contains string: " + Catch::Detail::stringify( m_substr ); - } - }; + std::string describe() const override { + return "contains string: " + + Catch::Detail::stringify(m_substr); + } + }; - struct StartsWith : StringHolder { - StartsWith( NSString* substr ) : StringHolder( substr ){} + struct StartsWith : StringHolder { + StartsWith(NSString* substr) : StringHolder(substr) {} - bool match( NSString* str ) const override { - return (str != nil || m_substr == nil ) && - [str rangeOfString:m_substr].location == 0; - } + bool match(NSString* str) const override { + return (str != nil || m_substr == nil) && + [str rangeOfString:m_substr].location == 0; + } - std::string describe() const override { - return "starts with: " + Catch::Detail::stringify( m_substr ); - } - }; - struct EndsWith : StringHolder { - EndsWith( NSString* substr ) : StringHolder( substr ){} + std::string describe() const override { + return "starts with: " + + Catch::Detail::stringify(m_substr); + } + }; + struct EndsWith : StringHolder { + EndsWith(NSString* substr) : StringHolder(substr) {} - bool match( NSString* str ) const override { - return (str != nil || m_substr == nil ) && - [str rangeOfString:m_substr].location == [str length] - [m_substr length]; - } + bool match(NSString* str) const override { + return (str != nil || m_substr == nil) && + [str rangeOfString:m_substr].location == + [str length] - [m_substr length]; + } - std::string describe() const override { - return "ends with: " + Catch::Detail::stringify( m_substr ); - } - }; + std::string describe() const override { + return "ends with: " + + Catch::Detail::stringify(m_substr); + } + }; - } // namespace NSStringMatchers - } // namespace Impl + } // namespace NSStringMatchers + } // namespace Impl - inline Impl::NSStringMatchers::Equals - Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); } + inline Impl::NSStringMatchers::Equals Equals(NSString* substr) { + return Impl::NSStringMatchers::Equals(substr); + } - inline Impl::NSStringMatchers::Contains - Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); } + inline Impl::NSStringMatchers::Contains Contains(NSString* substr) { + return Impl::NSStringMatchers::Contains(substr); + } - inline Impl::NSStringMatchers::StartsWith - StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); } + inline Impl::NSStringMatchers::StartsWith StartsWith(NSString* substr) { + return Impl::NSStringMatchers::StartsWith(substr); + } - inline Impl::NSStringMatchers::EndsWith - EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); } + inline Impl::NSStringMatchers::EndsWith EndsWith(NSString* substr) { + return Impl::NSStringMatchers::EndsWith(substr); + } } // namespace Matchers @@ -5025,25 +6017,24 @@ } // namespace Catch /////////////////////////////////////////////////////////////////////////////// -#define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix -#define OC_TEST_CASE2( name, desc, uniqueSuffix ) \ -+(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \ -{ \ -return @ name; \ -} \ -+(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \ -{ \ -return @ desc; \ -} \ --(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix ) +#define OC_MAKE_UNIQUE_NAME(root, uniqueSuffix) root##uniqueSuffix +#define OC_TEST_CASE2(name, desc, uniqueSuffix) \ + +(NSString*)OC_MAKE_UNIQUE_NAME(Catch_Name_test_, uniqueSuffix) { \ + return @name; \ + } \ + +(NSString*)OC_MAKE_UNIQUE_NAME(Catch_Description_test_, uniqueSuffix) { \ + return @desc; \ + } \ + -(void)OC_MAKE_UNIQUE_NAME(Catch_TestCase_test_, uniqueSuffix) -#define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ ) +#define OC_TEST_CASE(name, desc) OC_TEST_CASE2(name, desc, __LINE__) // end catch_objc.hpp #endif // Benchmarking needs the externally-facing parts of reporters to work -#if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING) +#if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || \ + defined(CATCH_CONFIG_ENABLE_BENCHMARKING) // start catch_external_interfaces.h // start catch_reporter_bases.hpp @@ -5068,8 +6059,7 @@ // start catch_wildcard_pattern.h -namespace Catch -{ +namespace Catch { class WildcardPattern { enum WildcardPosition { NoWildcard = 0, @@ -5079,18 +6069,18 @@ }; public: - - WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity ); + WildcardPattern(std::string const& pattern, + CaseSensitive::Choice caseSensitivity); virtual ~WildcardPattern() = default; - virtual bool matches( std::string const& str ) const; + virtual bool matches(std::string const& str) const; private: - std::string normaliseString( std::string const& str ) const; + std::string normaliseString(std::string const& str) const; CaseSensitive::Choice m_caseSensitivity; WildcardPosition m_wildcard = NoWildcard; std::string m_pattern; }; -} +} // namespace Catch // end catch_wildcard_pattern.h #include <string> @@ -5104,10 +6094,11 @@ class TestSpec { class Pattern { public: - explicit Pattern( std::string const& name ); + explicit Pattern(std::string const& name); virtual ~Pattern(); - virtual bool matches( TestCaseInfo const& testCase ) const = 0; + virtual bool matches(TestCaseInfo const& testCase) const = 0; std::string const& name() const; + private: std::string const m_name; }; @@ -5115,24 +6106,29 @@ class NamePattern : public Pattern { public: - explicit NamePattern( std::string const& name, std::string const& filterString ); - bool matches( TestCaseInfo const& testCase ) const override; + explicit NamePattern(std::string const& name, + std::string const& filterString); + bool matches(TestCaseInfo const& testCase) const override; + private: WildcardPattern m_wildcardPattern; }; class TagPattern : public Pattern { public: - explicit TagPattern( std::string const& tag, std::string const& filterString ); - bool matches( TestCaseInfo const& testCase ) const override; + explicit TagPattern(std::string const& tag, + std::string const& filterString); + bool matches(TestCaseInfo const& testCase) const override; + private: std::string m_tag; }; class ExcludedPattern : public Pattern { public: - explicit ExcludedPattern( PatternPtr const& underlyingPattern ); - bool matches( TestCaseInfo const& testCase ) const override; + explicit ExcludedPattern(PatternPtr const& underlyingPattern); + bool matches(TestCaseInfo const& testCase) const override; + private: PatternPtr m_underlyingPattern; }; @@ -5140,7 +6136,7 @@ struct Filter { std::vector<PatternPtr> m_patterns; - bool matches( TestCaseInfo const& testCase ) const; + bool matches(TestCaseInfo const& testCase) const; std::string name() const; }; @@ -5153,16 +6149,17 @@ using vectorStrings = std::vector<std::string>; bool hasFilters() const; - bool matches( TestCaseInfo const& testCase ) const; - Matches matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const; - const vectorStrings & getInvalidArgs() const; + bool matches(TestCaseInfo const& testCase) const; + Matches matchesByFilter(std::vector<TestCase> const& testCases, + IConfig const& config) const; + const vectorStrings& getInvalidArgs() const; private: std::vector<Filter> m_filters; std::vector<std::string> m_invalidArgs; friend class TestSpecParser; }; -} +} // namespace Catch #ifdef __clang__ #pragma clang diagnostic pop @@ -5180,8 +6177,9 @@ struct ITagAliasRegistry { virtual ~ITagAliasRegistry(); // Nullptr if not present - virtual TagAlias const* find( std::string const& alias ) const = 0; - virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0; + virtual TagAlias const* find(std::string const& alias) const = 0; + virtual std::string + expandAliases(std::string const& unexpandedTestSpec) const = 0; static ITagAliasRegistry const& get(); }; @@ -5192,7 +6190,7 @@ namespace Catch { class TestSpecParser { - enum Mode{ None, Name, QuotedName, Tag, EscapedName }; + enum Mode { None, Name, QuotedName, Tag, EscapedName }; Mode m_mode = None; Mode lastMode = None; bool m_exclusion = false; @@ -5207,20 +6205,20 @@ ITagAliasRegistry const* m_tagAliases = nullptr; public: - TestSpecParser( ITagAliasRegistry const& tagAliases ); + TestSpecParser(ITagAliasRegistry const& tagAliases); - TestSpecParser& parse( std::string const& arg ); + TestSpecParser& parse(std::string const& arg); TestSpec testSpec(); private: - bool visitChar( char c ); - void startNewMode( Mode mode ); - bool processNoneChar( char c ); - void processNameChar( char c ); - bool processOtherChar( char c ); + bool visitChar(char c); + void startNewMode(Mode mode); + bool processNoneChar(char c); + void processNameChar(char c); + bool processOtherChar(char c); void endMode(); void escape(); - bool isControlChar( char c ) const; + bool isControlChar(char c) const; void saveLastMode(); void revertBackToLastMode(); void addFilter(); @@ -5238,9 +6236,8 @@ m_patternName += c; m_realPatternPos++; } - }; - TestSpec parseTestSpec( std::string const& arg ); + TestSpec parseTestSpec(std::string const& arg); } // namespace Catch @@ -5309,9 +6306,8 @@ class Config : public IConfig { public: - Config() = default; - Config( ConfigData const& data ); + Config(ConfigData const& data); virtual ~Config() = default; std::string const& getFilename() const; @@ -5355,7 +6351,6 @@ std::chrono::milliseconds benchmarkWarmupTime() const override; private: - IStream const* openStream(); ConfigData m_data; @@ -5373,11 +6368,11 @@ namespace Catch { - struct AssertionResultData - { + struct AssertionResultData { AssertionResultData() = delete; - AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression ); + AssertionResultData(ResultWas::OfType _resultType, + LazyExpression const& _lazyExpression); std::string message; mutable std::string reconstructedExpression; @@ -5390,7 +6385,8 @@ class AssertionResult { public: AssertionResult() = delete; - AssertionResult( AssertionInfo const& info, AssertionResultData const& data ); + AssertionResult(AssertionInfo const& info, + AssertionResultData const& data); bool isOk() const; bool succeeded() const; @@ -5405,7 +6401,7 @@ SourceLineInfo getSourceInfo() const; StringRef getTestMacroName() const; - //protected: + // protected: AssertionInfo m_info; AssertionResultData m_resultData; }; @@ -5416,21 +6412,18 @@ #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) // start catch_estimate.hpp - // Statistics estimates - +// Statistics estimates namespace Catch { namespace Benchmark { - template <typename Duration> - struct Estimate { + template <typename Duration> struct Estimate { Duration point; Duration lower_bound; Duration upper_bound; double confidence_interval; - template <typename Duration2> - operator Estimate<Duration2>() const { - return { point, lower_bound, upper_bound, confidence_interval }; + template <typename Duration2> operator Estimate<Duration2>() const { + return {point, lower_bound, upper_bound, confidence_interval}; } }; } // namespace Benchmark @@ -5445,10 +6438,10 @@ namespace Benchmark { struct OutlierClassification { int samples_seen = 0; - int low_severe = 0; // more than 3 times IQR below Q1 - int low_mild = 0; // 1.5 to 3 times IQR below Q1 - int high_mild = 0; // 1.5 to 3 times IQR above Q3 - int high_severe = 0; // more than 3 times IQR above Q3 + int low_severe = 0; // more than 3 times IQR below Q1 + int low_mild = 0; // 1.5 to 3 times IQR below Q1 + int high_mild = 0; // 1.5 to 3 times IQR above Q3 + int high_severe = 0; // more than 3 times IQR above Q3 int total() const { return low_severe + low_mild + high_mild + high_severe; @@ -5472,9 +6465,9 @@ namespace Catch { struct ReporterConfig { - explicit ReporterConfig( IConfigPtr const& _fullConfig ); + explicit ReporterConfig(IConfigPtr const& _fullConfig); - ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream ); + ReporterConfig(IConfigPtr const& _fullConfig, std::ostream& _stream); std::ostream& stream() const; IConfigPtr fullConfig() const; @@ -5489,10 +6482,9 @@ bool shouldReportAllAssertions = false; }; - template<typename T> - struct LazyStat : Option<T> { - LazyStat& operator=( T const& _value ) { - Option<T>::operator=( _value ); + template <typename T> struct LazyStat : Option<T> { + LazyStat& operator=(T const& _value) { + Option<T>::operator=(_value); used = false; return *this; } @@ -5504,13 +6496,13 @@ }; struct TestRunInfo { - TestRunInfo( std::string const& _name ); + TestRunInfo(std::string const& _name); std::string name; }; struct GroupInfo { - GroupInfo( std::string const& _name, - std::size_t _groupIndex, - std::size_t _groupsCount ); + GroupInfo(std::string const& _name, + std::size_t _groupIndex, + std::size_t _groupsCount); std::string name; std::size_t groupIndex; @@ -5518,14 +6510,14 @@ }; struct AssertionStats { - AssertionStats( AssertionResult const& _assertionResult, - std::vector<MessageInfo> const& _infoMessages, - Totals const& _totals ); + AssertionStats(AssertionResult const& _assertionResult, + std::vector<MessageInfo> const& _infoMessages, + Totals const& _totals); - AssertionStats( AssertionStats const& ) = default; - AssertionStats( AssertionStats && ) = default; - AssertionStats& operator = ( AssertionStats const& ) = delete; - AssertionStats& operator = ( AssertionStats && ) = delete; + AssertionStats(AssertionStats const&) = default; + AssertionStats(AssertionStats&&) = default; + AssertionStats& operator=(AssertionStats const&) = delete; + AssertionStats& operator=(AssertionStats&&) = delete; virtual ~AssertionStats(); AssertionResult assertionResult; @@ -5534,14 +6526,14 @@ }; struct SectionStats { - SectionStats( SectionInfo const& _sectionInfo, - Counts const& _assertions, - double _durationInSeconds, - bool _missingAssertions ); - SectionStats( SectionStats const& ) = default; - SectionStats( SectionStats && ) = default; - SectionStats& operator = ( SectionStats const& ) = default; - SectionStats& operator = ( SectionStats && ) = default; + SectionStats(SectionInfo const& _sectionInfo, + Counts const& _assertions, + double _durationInSeconds, + bool _missingAssertions); + SectionStats(SectionStats const&) = default; + SectionStats(SectionStats&&) = default; + SectionStats& operator=(SectionStats const&) = default; + SectionStats& operator=(SectionStats&&) = default; virtual ~SectionStats(); SectionInfo sectionInfo; @@ -5551,16 +6543,16 @@ }; struct TestCaseStats { - TestCaseStats( TestCaseInfo const& _testInfo, - Totals const& _totals, - std::string const& _stdOut, - std::string const& _stdErr, - bool _aborting ); + TestCaseStats(TestCaseInfo const& _testInfo, + Totals const& _totals, + std::string const& _stdOut, + std::string const& _stdErr, + bool _aborting); - TestCaseStats( TestCaseStats const& ) = default; - TestCaseStats( TestCaseStats && ) = default; - TestCaseStats& operator = ( TestCaseStats const& ) = default; - TestCaseStats& operator = ( TestCaseStats && ) = default; + TestCaseStats(TestCaseStats const&) = default; + TestCaseStats(TestCaseStats&&) = default; + TestCaseStats& operator=(TestCaseStats const&) = default; + TestCaseStats& operator=(TestCaseStats&&) = default; virtual ~TestCaseStats(); TestCaseInfo testInfo; @@ -5571,15 +6563,15 @@ }; struct TestGroupStats { - TestGroupStats( GroupInfo const& _groupInfo, - Totals const& _totals, - bool _aborting ); - TestGroupStats( GroupInfo const& _groupInfo ); + TestGroupStats(GroupInfo const& _groupInfo, + Totals const& _totals, + bool _aborting); + TestGroupStats(GroupInfo const& _groupInfo); - TestGroupStats( TestGroupStats const& ) = default; - TestGroupStats( TestGroupStats && ) = default; - TestGroupStats& operator = ( TestGroupStats const& ) = default; - TestGroupStats& operator = ( TestGroupStats && ) = default; + TestGroupStats(TestGroupStats const&) = default; + TestGroupStats(TestGroupStats&&) = default; + TestGroupStats& operator=(TestGroupStats const&) = default; + TestGroupStats& operator=(TestGroupStats&&) = default; virtual ~TestGroupStats(); GroupInfo groupInfo; @@ -5588,14 +6580,14 @@ }; struct TestRunStats { - TestRunStats( TestRunInfo const& _runInfo, - Totals const& _totals, - bool _aborting ); + TestRunStats(TestRunInfo const& _runInfo, + Totals const& _totals, + bool _aborting); - TestRunStats( TestRunStats const& ) = default; - TestRunStats( TestRunStats && ) = default; - TestRunStats& operator = ( TestRunStats const& ) = default; - TestRunStats& operator = ( TestRunStats && ) = default; + TestRunStats(TestRunStats const&) = default; + TestRunStats(TestRunStats&&) = default; + TestRunStats& operator=(TestRunStats const&) = default; + TestRunStats& operator=(TestRunStats&&) = default; virtual ~TestRunStats(); TestRunInfo runInfo; @@ -5614,8 +6606,7 @@ double clockCost; }; - template <class Duration> - struct BenchmarkStats { + template <class Duration> struct BenchmarkStats { BenchmarkInfo info; std::vector<Duration> samples; @@ -5628,7 +6619,10 @@ operator BenchmarkStats<Duration2>() const { std::vector<Duration2> samples2; samples2.reserve(samples.size()); - std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); }); + std::transform(samples.begin(), + samples.end(), + std::back_inserter(samples2), + [](Duration d) { return Duration2(d); }); return { info, std::move(samples2), @@ -5650,37 +6644,37 @@ virtual ReporterPreferences getPreferences() const = 0; - virtual void noMatchingTestCases( std::string const& spec ) = 0; + virtual void noMatchingTestCases(std::string const& spec) = 0; virtual void reportInvalidArguments(std::string const&) {} - virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0; - virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0; + virtual void testRunStarting(TestRunInfo const& testRunInfo) = 0; + virtual void testGroupStarting(GroupInfo const& groupInfo) = 0; - virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0; - virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0; + virtual void testCaseStarting(TestCaseInfo const& testInfo) = 0; + virtual void sectionStarting(SectionInfo const& sectionInfo) = 0; #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) - virtual void benchmarkPreparing( std::string const& ) {} - virtual void benchmarkStarting( BenchmarkInfo const& ) {} - virtual void benchmarkEnded( BenchmarkStats<> const& ) {} - virtual void benchmarkFailed( std::string const& ) {} + virtual void benchmarkPreparing(std::string const&) {} + virtual void benchmarkStarting(BenchmarkInfo const&) {} + virtual void benchmarkEnded(BenchmarkStats<> const&) {} + virtual void benchmarkFailed(std::string const&) {} #endif // CATCH_CONFIG_ENABLE_BENCHMARKING - virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0; + virtual void assertionStarting(AssertionInfo const& assertionInfo) = 0; // The return value indicates if the messages buffer should be cleared: - virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0; + virtual bool assertionEnded(AssertionStats const& assertionStats) = 0; - virtual void sectionEnded( SectionStats const& sectionStats ) = 0; - virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0; - virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0; - virtual void testRunEnded( TestRunStats const& testRunStats ) = 0; + virtual void sectionEnded(SectionStats const& sectionStats) = 0; + virtual void testCaseEnded(TestCaseStats const& testCaseStats) = 0; + virtual void testGroupEnded(TestGroupStats const& testGroupStats) = 0; + virtual void testRunEnded(TestRunStats const& testRunStats) = 0; - virtual void skipTest( TestCaseInfo const& testInfo ) = 0; + virtual void skipTest(TestCaseInfo const& testInfo) = 0; // Default empty implementation provided - virtual void fatalErrorEncountered( StringRef name ); + virtual void fatalErrorEncountered(StringRef name); virtual bool isMulti() const; }; @@ -5688,7 +6682,8 @@ struct IReporterFactory { virtual ~IReporterFactory(); - virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0; + virtual IStreamingReporterPtr + create(ReporterConfig const& config) const = 0; virtual std::string getDescription() const = 0; }; using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>; @@ -5698,7 +6693,8 @@ using Listeners = std::vector<IReporterFactoryPtr>; virtual ~IReporterRegistry(); - virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0; + virtual IStreamingReporterPtr + create(std::string const& name, IConfigPtr const& config) const = 0; virtual FactoryMap const& getFactories() const = 0; virtual Listeners const& getListeners() const = 0; }; @@ -5718,23 +6714,22 @@ void prepareExpandedExpression(AssertionResult& result); // Returns double formatted as %.3f (format expected on output) - std::string getFormattedDuration( double duration ); + std::string getFormattedDuration(double duration); //! Should the reporter show - bool shouldShowDuration( IConfig const& config, double duration ); + bool shouldShowDuration(IConfig const& config, double duration); - std::string serializeFilters( std::vector<std::string> const& container ); + std::string serializeFilters(std::vector<std::string> const& container); - template<typename DerivedT> + template <typename DerivedT> struct StreamingReporterBase : IStreamingReporter { - StreamingReporterBase( ReporterConfig const& _config ) - : m_config( _config.fullConfig() ), - stream( _config.stream() ) - { + StreamingReporterBase(ReporterConfig const& _config) : + m_config(_config.fullConfig()), stream(_config.stream()) { m_reporterPrefs.shouldRedirectStdOut = false; - if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) ) - CATCH_ERROR( "Verbosity level not supported by this reporter" ); + if (!DerivedT::getSupportedVerbosities().count( + m_config->verbosity())) + CATCH_ERROR("Verbosity level not supported by this reporter"); } ReporterPreferences getPreferences() const override { @@ -5742,7 +6737,7 @@ } static std::set<Verbosity> getSupportedVerbosities() { - return { Verbosity::Normal }; + return {Verbosity::Normal}; } ~StreamingReporterBase() override = default; @@ -5759,7 +6754,7 @@ currentGroupInfo = _groupInfo; } - void testCaseStarting(TestCaseInfo const& _testInfo) override { + void testCaseStarting(TestCaseInfo const& _testInfo) override { currentTestCaseInfo = _testInfo; } void sectionStarting(SectionInfo const& _sectionInfo) override { @@ -5772,7 +6767,8 @@ void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override { currentTestCaseInfo.reset(); } - void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override { + void + testGroupEnded(TestGroupStats const& /* _testGroupStats */) override { currentGroupInfo.reset(); } void testRunEnded(TestRunStats const& /* _testRunStats */) override { @@ -5797,11 +6793,10 @@ ReporterPreferences m_reporterPrefs; }; - template<typename DerivedT> + template <typename DerivedT> struct CumulativeReporterBase : IStreamingReporter { - template<typename T, typename ChildNodeT> - struct Node { - explicit Node( T const& _value ) : value( _value ) {} + template <typename T, typename ChildNodeT> struct Node { + explicit Node(T const& _value) : value(_value) {} virtual ~Node() {} using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>; @@ -5812,10 +6807,11 @@ explicit SectionNode(SectionStats const& _stats) : stats(_stats) {} virtual ~SectionNode() = default; - bool operator == (SectionNode const& other) const { - return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo; + bool operator==(SectionNode const& other) const { + return stats.sectionInfo.lineInfo == + other.stats.sectionInfo.lineInfo; } - bool operator == (std::shared_ptr<SectionNode> const& other) const { + bool operator==(std::shared_ptr<SectionNode> const& other) const { return operator==(*other); } @@ -5829,9 +6825,10 @@ }; struct BySectionInfo { - BySectionInfo( SectionInfo const& other ) : m_other( other ) {} - BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {} - bool operator() (std::shared_ptr<SectionNode> const& node) const { + BySectionInfo(SectionInfo const& other) : m_other(other) {} + BySectionInfo(BySectionInfo const& other) : + m_other(other.m_other) {} + bool operator()(std::shared_ptr<SectionNode> const& node) const { return ((node->stats.sectionInfo.name == m_other.name) && (node->stats.sectionInfo.lineInfo == m_other.lineInfo)); } @@ -5845,13 +6842,12 @@ using TestGroupNode = Node<TestGroupStats, TestCaseNode>; using TestRunNode = Node<TestRunStats, TestGroupNode>; - CumulativeReporterBase( ReporterConfig const& _config ) - : m_config( _config.fullConfig() ), - stream( _config.stream() ) - { + CumulativeReporterBase(ReporterConfig const& _config) : + m_config(_config.fullConfig()), stream(_config.stream()) { m_reporterPrefs.shouldRedirectStdOut = false; - if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) ) - CATCH_ERROR( "Verbosity level not supported by this reporter" ); + if (!DerivedT::getSupportedVerbosities().count( + m_config->verbosity())) + CATCH_ERROR("Verbosity level not supported by this reporter"); } ~CumulativeReporterBase() override = default; @@ -5860,36 +6856,34 @@ } static std::set<Verbosity> getSupportedVerbosities() { - return { Verbosity::Normal }; + return {Verbosity::Normal}; } - void testRunStarting( TestRunInfo const& ) override {} - void testGroupStarting( GroupInfo const& ) override {} + void testRunStarting(TestRunInfo const&) override {} + void testGroupStarting(GroupInfo const&) override {} - void testCaseStarting( TestCaseInfo const& ) override {} + void testCaseStarting(TestCaseInfo const&) override {} - void sectionStarting( SectionInfo const& sectionInfo ) override { - SectionStats incompleteStats( sectionInfo, Counts(), 0, false ); + void sectionStarting(SectionInfo const& sectionInfo) override { + SectionStats incompleteStats(sectionInfo, Counts(), 0, false); std::shared_ptr<SectionNode> node; - if( m_sectionStack.empty() ) { - if( !m_rootSection ) - m_rootSection = std::make_shared<SectionNode>( incompleteStats ); + if (m_sectionStack.empty()) { + if (!m_rootSection) + m_rootSection = + std::make_shared<SectionNode>(incompleteStats); node = m_rootSection; - } - else { + } else { SectionNode& parentNode = *m_sectionStack.back(); - auto it = - std::find_if( parentNode.childSections.begin(), - parentNode.childSections.end(), - BySectionInfo( sectionInfo ) ); - if( it == parentNode.childSections.end() ) { - node = std::make_shared<SectionNode>( incompleteStats ); - parentNode.childSections.push_back( node ); - } - else + auto it = std::find_if(parentNode.childSections.begin(), + parentNode.childSections.end(), + BySectionInfo(sectionInfo)); + if (it == parentNode.childSections.end()) { + node = std::make_shared<SectionNode>(incompleteStats); + parentNode.childSections.push_back(node); + } else node = *it; } - m_sectionStack.push_back( node ); + m_sectionStack.push_back(node); m_deepestSection = std::move(node); } @@ -5897,12 +6891,14 @@ bool assertionEnded(AssertionStats const& assertionStats) override { assert(!m_sectionStack.empty()); - // AssertionResult holds a pointer to a temporary DecomposedExpression, - // which getExpandedExpression() calls to build the expression string. - // Our section stack copy of the assertionResult will likely outlive the - // temporary, so it must be expanded or discarded now to avoid calling - // a destroyed object later. - prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) ); + // AssertionResult holds a pointer to a temporary + // DecomposedExpression, which getExpandedExpression() calls to + // build the expression string. Our section stack copy of the + // assertionResult will likely outlive the temporary, so it must be + // expanded or discarded now to avoid calling a destroyed object + // later. + prepareExpandedExpression( + const_cast<AssertionResult&>(assertionStats.assertionResult)); SectionNode& sectionNode = *m_sectionStack.back(); sectionNode.assertions.push_back(assertionStats); return true; @@ -5954,18 +6950,18 @@ ReporterPreferences m_reporterPrefs; }; - template<char C> - char const* getLineOfChars() { + template <char C> char const* getLineOfChars() { static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0}; - if( !*line ) { - std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 ); - line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0; + if (!*line) { + std::memset(line, C, CATCH_CONFIG_CONSOLE_WIDTH - 1); + line[CATCH_CONFIG_CONSOLE_WIDTH - 1] = 0; } return line; } - struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> { - TestEventListenerBase( ReporterConfig const& _config ); + struct TestEventListenerBase + : StreamingReporterBase<TestEventListenerBase> { + TestEventListenerBase(ReporterConfig const& _config); static std::set<Verbosity> getSupportedVerbosities(); @@ -6018,35 +7014,34 @@ }; // Use constructed object for RAII guard - Colour( Code _colourCode ); - Colour( Colour&& other ) noexcept; - Colour& operator=( Colour&& other ) noexcept; + Colour(Code _colourCode); + Colour(Colour&& other) noexcept; + Colour& operator=(Colour&& other) noexcept; ~Colour(); // Use static method for one-shot changes - static void use( Code _colourCode ); + static void use(Code _colourCode); private: bool m_moved = false; }; - std::ostream& operator << ( std::ostream& os, Colour const& ); + std::ostream& operator<<(std::ostream& os, Colour const&); } // end namespace Catch // end catch_console_colour.h // start catch_reporter_registrars.hpp - namespace Catch { - template<typename T> - class ReporterRegistrar { + template <typename T> class ReporterRegistrar { class ReporterFactory : public IReporterFactory { - IStreamingReporterPtr create( ReporterConfig const& config ) const override { - return std::unique_ptr<T>( new T( config ) ); + IStreamingReporterPtr + create(ReporterConfig const& config) const override { + return std::unique_ptr<T>(new T(config)); } std::string getDescription() const override { @@ -6055,19 +7050,19 @@ }; public: - - explicit ReporterRegistrar( std::string const& name ) { - getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() ); + explicit ReporterRegistrar(std::string const& name) { + getMutableRegistryHub().registerReporter( + name, std::make_shared<ReporterFactory>()); } }; - template<typename T> - class ListenerRegistrar { + template <typename T> class ListenerRegistrar { class ListenerFactory : public IReporterFactory { - IStreamingReporterPtr create( ReporterConfig const& config ) const override { - return std::unique_ptr<T>( new T( config ) ); + IStreamingReporterPtr + create(ReporterConfig const& config) const override { + return std::unique_ptr<T>(new T(config)); } std::string getDescription() const override { return std::string(); @@ -6075,25 +7070,31 @@ }; public: - ListenerRegistrar() { - getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() ); + getMutableRegistryHub().registerListener( + std::make_shared<ListenerFactory>()); } }; -} +} // namespace Catch #if !defined(CATCH_CONFIG_DISABLE) -#define CATCH_REGISTER_REPORTER( name, reporterType ) \ - CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ - CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ - namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \ +#define CATCH_REGISTER_REPORTER(name, reporterType) \ + CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + namespace { \ + Catch::ReporterRegistrar<reporterType> \ + catch_internal_RegistrarFor##reporterType(name); \ + } \ CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION -#define CATCH_REGISTER_LISTENER( listenerType ) \ - CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ - CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ - namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \ +#define CATCH_REGISTER_LISTENER(listenerType) \ + CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + namespace { \ + Catch::ListenerRegistrar<listenerType> \ + catch_internal_RegistrarFor##listenerType; \ + } \ CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION #else // CATCH_CONFIG_DISABLE @@ -6125,7 +7126,6 @@ void sectionEnded(SectionStats const& _sectionStats) override; void testRunEnded(TestRunStats const& _testRunStats) override; - }; } // end namespace Catch @@ -6135,9 +7135,9 @@ #if defined(_MSC_VER) #pragma warning(push) -#pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch - // Note that 4062 (not all labels are handled - // and default is missing) is enabled +#pragma warning(disable : 4061) // Not all labels are EXPLICITLY handled in + // switch Note that 4062 (not all labels are + // handled and default is missing) is enabled #endif namespace Catch { @@ -6154,7 +7154,7 @@ void noMatchingTestCases(std::string const& spec) override; - void reportInvalidArguments(std::string const&arg) override; + void reportInvalidArguments(std::string const& arg) override; void assertionStarting(AssertionInfo const&) override; @@ -6174,8 +7174,8 @@ void testGroupEnded(TestGroupStats const& _testGroupStats) override; void testRunEnded(TestRunStats const& _testRunStats) override; void testRunStarting(TestRunInfo const& _testRunInfo) override; - private: + private: void lazyPrint(); void lazyPrintWithoutClosingBenchmarkTable(); @@ -6188,10 +7188,13 @@ // if string has a : in first line will set indent to follow it on // subsequent lines - void printHeaderString(std::string const& _string, std::size_t indent = 0); + void printHeaderString(std::string const& _string, + std::size_t indent = 0); void printTotals(Totals const& totals); - void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row); + void printSummaryRow(std::string const& label, + std::vector<SummaryColumn> const& cols, + std::size_t row); void printTotalsDivider(Totals const& totals); void printSummaryDivider(); @@ -6221,18 +7224,19 @@ Newline = 0x02, }; - XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs); - XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs); + XmlFormatting operator|(XmlFormatting lhs, XmlFormatting rhs); + XmlFormatting operator&(XmlFormatting lhs, XmlFormatting rhs); class XmlEncode { public: enum ForWhat { ForTextNodes, ForAttributes }; - XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes ); + XmlEncode(std::string const& str, ForWhat forWhat = ForTextNodes); - void encodeTo( std::ostream& os ) const; + void encodeTo(std::ostream& os) const; - friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ); + friend std::ostream& operator<<(std::ostream& os, + XmlEncode const& xmlEncode); private: std::string m_str; @@ -6241,21 +7245,24 @@ class XmlWriter { public: - class ScopedElement { public: - ScopedElement( XmlWriter* writer, XmlFormatting fmt ); + ScopedElement(XmlWriter* writer, XmlFormatting fmt); - ScopedElement( ScopedElement&& other ) noexcept; - ScopedElement& operator=( ScopedElement&& other ) noexcept; + ScopedElement(ScopedElement&& other) noexcept; + ScopedElement& operator=(ScopedElement&& other) noexcept; ~ScopedElement(); - ScopedElement& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent ); + ScopedElement& + writeText(std::string const& text, + XmlFormatting fmt = XmlFormatting::Newline | + XmlFormatting::Indent); - template<typename T> - ScopedElement& writeAttribute( std::string const& name, T const& attribute ) { - m_writer->writeAttribute( name, attribute ); + template <typename T> + ScopedElement& writeAttribute(std::string const& name, + T const& attribute) { + m_writer->writeAttribute(name, attribute); return *this; } @@ -6264,41 +7271,50 @@ XmlFormatting m_fmt; }; - XmlWriter( std::ostream& os = Catch::cout() ); + XmlWriter(std::ostream& os = Catch::cout()); ~XmlWriter(); - XmlWriter( XmlWriter const& ) = delete; - XmlWriter& operator=( XmlWriter const& ) = delete; + XmlWriter(XmlWriter const&) = delete; + XmlWriter& operator=(XmlWriter const&) = delete; - XmlWriter& startElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent); + XmlWriter& startElement(std::string const& name, + XmlFormatting fmt = XmlFormatting::Newline | + XmlFormatting::Indent); - ScopedElement scopedElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent); + ScopedElement scopedElement(std::string const& name, + XmlFormatting fmt = XmlFormatting::Newline | + XmlFormatting::Indent); - XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent); + XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | + XmlFormatting::Indent); - XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ); + XmlWriter& writeAttribute(std::string const& name, + std::string const& attribute); - XmlWriter& writeAttribute( std::string const& name, bool attribute ); + XmlWriter& writeAttribute(std::string const& name, bool attribute); - template<typename T> - XmlWriter& writeAttribute( std::string const& name, T const& attribute ) { + template <typename T> + XmlWriter& writeAttribute(std::string const& name, T const& attribute) { ReusableStringStream rss; rss << attribute; - return writeAttribute( name, rss.str() ); + return writeAttribute(name, rss.str()); } - XmlWriter& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent); + XmlWriter& writeText(std::string const& text, + XmlFormatting fmt = XmlFormatting::Newline | + XmlFormatting::Indent); - XmlWriter& writeComment(std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent); + XmlWriter& writeComment(std::string const& text, + XmlFormatting fmt = XmlFormatting::Newline | + XmlFormatting::Indent); - void writeStylesheetRef( std::string const& url ); + void writeStylesheetRef(std::string const& url); XmlWriter& writeBlankLine(); void ensureTagClosed(); private: - void applyFormatting(XmlFormatting fmt); void writeDeclaration(); @@ -6312,7 +7328,7 @@ std::ostream& m_os; }; -} +} // namespace Catch // end catch_xmlwriter.h namespace Catch { @@ -6344,10 +7360,10 @@ void writeTestCase(TestCaseNode const& testCaseNode); - void writeSection( std::string const& className, - std::string const& rootName, - SectionNode const& sectionNode, - bool testOkToFail ); + void writeSection(std::string const& className, + std::string const& rootName, + SectionNode const& sectionNode, + bool testOkToFail); void writeAssertions(SectionNode const& sectionNode); void writeAssertion(AssertionStats const& stats); @@ -6379,7 +7395,6 @@ void writeSourceInfo(SourceLineInfo const& sourceInfo); public: // StreamingReporterBase - void noMatchingTestCases(std::string const& s) override; void testRunStarting(TestRunInfo const& testInfo) override; @@ -6431,18 +7446,16 @@ // start catch_benchmark.hpp - // Benchmark +// Benchmark // start catch_chronometer.hpp // User-facing chronometer - // start catch_clock.hpp // Clocks - #include <chrono> #include <ratio> @@ -6451,18 +7464,15 @@ template <typename Clock> using ClockDuration = typename Clock::duration; template <typename Clock> - using FloatDuration = std::chrono::duration<double, typename Clock::period>; + using FloatDuration = + std::chrono::duration<double, typename Clock::period>; - template <typename Clock> - using TimePoint = typename Clock::time_point; + template <typename Clock> using TimePoint = typename Clock::time_point; using default_clock = std::chrono::steady_clock; - template <typename Clock> - struct now { - TimePoint<Clock> operator()() const { - return Clock::now(); - } + template <typename Clock> struct now { + TimePoint<Clock> operator()() const { return Clock::now(); } }; using fp_seconds = std::chrono::duration<double, std::ratio<1>>; @@ -6472,23 +7482,19 @@ // end catch_clock.hpp // start catch_optimizer.hpp - // Hinting the optimizer - +// Hinting the optimizer #if defined(_MSC_VER) -# include <atomic> // atomic_thread_fence +#include <atomic> // atomic_thread_fence #endif namespace Catch { namespace Benchmark { #if defined(__GNUC__) || defined(__clang__) - template <typename T> - inline void keep_memory(T* p) { + template <typename T> inline void keep_memory(T* p) { asm volatile("" : : "g"(p) : "memory"); } - inline void keep_memory() { - asm volatile("" : : : "memory"); - } + inline void keep_memory() { asm volatile("" : : : "memory"); } namespace Detail { inline void optimizer_barrier() { keep_memory(); } @@ -6496,10 +7502,10 @@ #elif defined(_MSC_VER) #pragma optimize("", off) - template <typename T> - inline void keep_memory(T* p) { + template <typename T> inline void keep_memory(T* p) { // thanks @milleniumbug - *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p); + *reinterpret_cast<char volatile*>(p) = + *reinterpret_cast<char const volatile*>(p); } // TODO equivalent keep_memory() #pragma optimize("", on) @@ -6512,19 +7518,23 @@ #endif - template <typename T> - inline void deoptimize_value(T&& x) { + template <typename T> inline void deoptimize_value(T&& x) { keep_memory(&x); } template <typename Fn, typename... Args> - inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type { - deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...))); + inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> + typename std::enable_if< + !std::is_same<void, decltype(fn(args...))>::value>::type { + deoptimize_value( + std::forward<Fn>(fn)(std::forward<Args...>(args...))); } template <typename Fn, typename... Args> - inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type { - std::forward<Fn>(fn) (std::forward<Args...>(args...)); + inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> + typename std::enable_if< + std::is_same<void, decltype(fn(args...))>::value>::type { + std::forward<Fn>(fn)(std::forward<Args...>(args...)); } } // namespace Benchmark } // namespace Catch @@ -6534,30 +7544,27 @@ // Invoke with a special case for void - #include <type_traits> #include <utility> namespace Catch { namespace Benchmark { namespace Detail { - template <typename T> - struct CompleteType { using type = T; }; - template <> - struct CompleteType<void> { struct type {}; }; + template <typename T> struct CompleteType { using type = T; }; + template <> struct CompleteType<void> { + struct type {}; + }; template <typename T> using CompleteType_t = typename CompleteType<T>::type; - template <typename Result> - struct CompleteInvoker { + template <typename Result> struct CompleteInvoker { template <typename Fun, typename... Args> static Result invoke(Fun&& fun, Args&&... args) { return std::forward<Fun>(fun)(std::forward<Args>(args)...); } }; - template <> - struct CompleteInvoker<void> { + template <> struct CompleteInvoker<void> { template <typename Fun, typename... Args> static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) { std::forward<Fun>(fun)(std::forward<Args>(args)...); @@ -6567,18 +7574,22 @@ // invoke and not return void :( template <typename Fun, typename... Args> - CompleteType_t<FunctionReturnType<Fun, Args...>> complete_invoke(Fun&& fun, Args&&... args) { - return CompleteInvoker<FunctionReturnType<Fun, Args...>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...); + CompleteType_t<FunctionReturnType<Fun, Args...>> + complete_invoke(Fun&& fun, Args&&... args) { + return CompleteInvoker<FunctionReturnType<Fun, Args...>>:: + invoke(std::forward<Fun>(fun), std::forward<Args>(args)...); } - const std::string benchmarkErrorMsg = "a benchmark failed to run successfully"; + const std::string benchmarkErrorMsg = + "a benchmark failed to run successfully"; } // namespace Detail template <typename Fun> Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun&& fun) { - CATCH_TRY{ + CATCH_TRY { return Detail::complete_invoke(std::forward<Fun>(fun)); - } CATCH_CATCH_ALL{ + } + CATCH_CATCH_ALL { getResultCapture().benchmarkFailed(translateActiveException()); CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg); } @@ -6600,7 +7611,9 @@ void start() override { started = Clock::now(); } void finish() override { finished = Clock::now(); } - ClockDuration<Clock> elapsed() const { return finished - started; } + ClockDuration<Clock> elapsed() const { + return finished - started; + } TimePoint<Clock> started; TimePoint<Clock> finished; @@ -6609,26 +7622,25 @@ struct Chronometer { public: - template <typename Fun> - void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(int)>()); } + template <typename Fun> void measure(Fun&& fun) { + measure(std::forward<Fun>(fun), is_callable<Fun(int)>()); + } int runs() const { return k; } - Chronometer(Detail::ChronometerConcept& meter, int k) - : impl(&meter) - , k(k) {} + Chronometer(Detail::ChronometerConcept& meter, int k) : + impl(&meter), k(k) {} private: - template <typename Fun> - void measure(Fun&& fun, std::false_type) { + template <typename Fun> void measure(Fun&& fun, std::false_type) { measure([&fun](int) { return fun(); }, std::true_type()); } - template <typename Fun> - void measure(Fun&& fun, std::true_type) { + template <typename Fun> void measure(Fun&& fun, std::true_type) { Detail::optimizer_barrier(); impl->start(); - for (int i = 0; i < k; ++i) invoke_deoptimized(fun, i); + for (int i = 0; i < k; ++i) + invoke_deoptimized(fun, i); impl->finish(); Detail::optimizer_barrier(); } @@ -6644,21 +7656,18 @@ // Environment information - namespace Catch { namespace Benchmark { - template <typename Duration> - struct EnvironmentEstimate { + template <typename Duration> struct EnvironmentEstimate { Duration mean; OutlierClassification outliers; template <typename Duration2> operator EnvironmentEstimate<Duration2>() const { - return { mean, outliers }; + return {mean, outliers}; } }; - template <typename Clock> - struct Environment { + template <typename Clock> struct Environment { using clock_type = Clock; EnvironmentEstimate<FloatDuration<Clock>> clock_resolution; EnvironmentEstimate<FloatDuration<Clock>> clock_cost; @@ -6669,13 +7678,11 @@ // end catch_environment.hpp // start catch_execution_plan.hpp - // Execution plan - +// Execution plan // start catch_benchmark_function.hpp - // Dumb std::function implementation for consistent call overhead - +// Dumb std::function implementation for consistent call overhead #include <cassert> #include <type_traits> @@ -6685,18 +7692,17 @@ namespace Catch { namespace Benchmark { namespace Detail { - template <typename T> - using Decay = typename std::decay<T>::type; + template <typename T> using Decay = typename std::decay<T>::type; template <typename T, typename U> - struct is_related - : std::is_same<Decay<T>, Decay<U>> {}; + struct is_related : std::is_same<Decay<T>, Decay<U>> {}; - /// We need to reinvent std::function because every piece of code that might add overhead - /// in a measurement context needs to have consistent performance characteristics so that we - /// can account for it in the measurement. - /// Implementations of std::function with optimizations that aren't always applicable, like - /// small buffer optimizations, are not uncommon. - /// This is effectively an implementation of std::function without any such optimizations; + /// We need to reinvent std::function because every piece of code + /// that might add overhead in a measurement context needs to have + /// consistent performance characteristics so that we can account + /// for it in the measurement. Implementations of std::function with + /// optimizations that aren't always applicable, like small buffer + /// optimizations, are not uncommon. This is effectively an + /// implementation of std::function without any such optimizations; /// it may be slow, but it is consistently slow. struct BenchmarkFunction { private: @@ -6705,12 +7711,13 @@ virtual callable* clone() const = 0; virtual ~callable() = default; }; - template <typename Fun> - struct model : public callable { + template <typename Fun> struct model : public callable { model(Fun&& fun) : fun(std::move(fun)) {} model(Fun const& fun) : fun(fun) {} - model<Fun>* clone() const override { return new model<Fun>(*this); } + model<Fun>* clone() const override { + return new model<Fun>(*this); + } void call(Chronometer meter) const override { call(meter, is_callable<Fun(Chronometer)>()); @@ -6725,25 +7732,28 @@ Fun fun; }; - struct do_nothing { void operator()() const {} }; + struct do_nothing { + void operator()() const {} + }; - template <typename T> - BenchmarkFunction(model<T>* c) : f(c) {} + template <typename T> BenchmarkFunction(model<T>* c) : f(c) {} public: - BenchmarkFunction() - : f(new model<do_nothing>{ {} }) {} + BenchmarkFunction() : f(new model<do_nothing>{{}}) {} template <typename Fun, - typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value, int>::type = 0> - BenchmarkFunction(Fun&& fun) - : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {} + typename std::enable_if< + !is_related<Fun, BenchmarkFunction>::value, + int>::type = 0> + BenchmarkFunction(Fun&& fun) : + f(new model<typename std::decay<Fun>::type>( + std::forward<Fun>(fun))) {} - BenchmarkFunction(BenchmarkFunction&& that) - : f(std::move(that.f)) {} + BenchmarkFunction(BenchmarkFunction&& that) : + f(std::move(that.f)) {} - BenchmarkFunction(BenchmarkFunction const& that) - : f(that.f->clone()) {} + BenchmarkFunction(BenchmarkFunction const& that) : + f(that.f->clone()) {} BenchmarkFunction& operator=(BenchmarkFunction&& that) { f = std::move(that.f); @@ -6761,7 +7771,7 @@ std::unique_ptr<callable> f; }; } // namespace Detail - } // namespace Benchmark + } // namespace Benchmark } // namespace Catch // end catch_benchmark_function.hpp @@ -6769,15 +7779,13 @@ // repeat algorithm - #include <type_traits> #include <utility> namespace Catch { namespace Benchmark { namespace Detail { - template <typename Fun> - struct repeater { + template <typename Fun> struct repeater { void operator()(int k) const { for (int i = 0; i < k; ++i) { fun(); @@ -6787,10 +7795,10 @@ }; template <typename Fun> repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) { - return { std::forward<Fun>(fun) }; + return {std::forward<Fun>(fun)}; } } // namespace Detail - } // namespace Benchmark + } // namespace Benchmark } // namespace Catch // end catch_repeat.hpp @@ -6798,30 +7806,28 @@ // Run a function for a minimum amount of time - // start catch_measure.hpp // Measure - // start catch_timing.hpp // Timing - #include <tuple> #include <type_traits> namespace Catch { namespace Benchmark { - template <typename Duration, typename Result> - struct Timing { + template <typename Duration, typename Result> struct Timing { Duration elapsed; Result result; int iterations; }; template <typename Clock, typename Func, typename... Args> - using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<FunctionReturnType<Func, Args...>>>; + using TimingOf = + Timing<ClockDuration<Clock>, + Detail::CompleteType_t<FunctionReturnType<Func, Args...>>>; } // namespace Benchmark } // namespace Catch @@ -6834,13 +7840,14 @@ template <typename Clock, typename Fun, typename... Args> TimingOf<Clock, Fun, Args...> measure(Fun&& fun, Args&&... args) { auto start = Clock::now(); - auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...); + auto&& r = + Detail::complete_invoke(fun, std::forward<Args>(args)...); auto end = Clock::now(); auto delta = end - start; - return { delta, std::forward<decltype(r)>(r), 1 }; + return {delta, std::forward<decltype(r)>(r), 1}; } } // namespace Detail - } // namespace Benchmark + } // namespace Benchmark } // namespace Catch // end catch_measure.hpp @@ -6851,41 +7858,53 @@ namespace Benchmark { namespace Detail { template <typename Clock, typename Fun> - TimingOf<Clock, Fun, int> measure_one(Fun&& fun, int iters, std::false_type) { + TimingOf<Clock, Fun, int> + measure_one(Fun&& fun, int iters, std::false_type) { return Detail::measure<Clock>(fun, iters); } template <typename Clock, typename Fun> - TimingOf<Clock, Fun, Chronometer> measure_one(Fun&& fun, int iters, std::true_type) { + TimingOf<Clock, Fun, Chronometer> + measure_one(Fun&& fun, int iters, std::true_type) { Detail::ChronometerModel<Clock> meter; - auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters)); + auto&& result = + Detail::complete_invoke(fun, Chronometer(meter, iters)); - return { meter.elapsed(), std::move(result), iters }; + return {meter.elapsed(), std::move(result), iters}; } template <typename Clock, typename Fun> - using run_for_at_least_argument_t = typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type; + using run_for_at_least_argument_t = + typename std::conditional<is_callable<Fun(Chronometer)>::value, + Chronometer, + int>::type; struct optimized_away_error : std::exception { const char* what() const noexcept override { - return "could not measure benchmark, maybe it was optimized away"; + return "could not measure benchmark, maybe it was " + "optimized away"; } }; template <typename Clock, typename Fun> - TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>> run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) { + TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>> + run_for_at_least(ClockDuration<Clock> how_long, + int seed, + Fun&& fun) { auto iters = seed; while (iters < (1 << 30)) { - auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>()); + auto&& Timing = measure_one<Clock>( + fun, iters, is_callable<Fun(Chronometer)>()); if (Timing.elapsed >= how_long) { - return { Timing.elapsed, std::move(Timing.result), iters }; + return { + Timing.elapsed, std::move(Timing.result), iters}; } iters *= 2; } Catch::throw_exception(optimized_away_error{}); } } // namespace Detail - } // namespace Benchmark + } // namespace Benchmark } // namespace Catch // end catch_run_for_at_least.hpp @@ -6894,8 +7913,7 @@ namespace Catch { namespace Benchmark { - template <typename Duration> - struct ExecutionPlan { + template <typename Duration> struct ExecutionPlan { int iterations_per_sample; Duration estimated_duration; Detail::BenchmarkFunction benchmark; @@ -6904,23 +7922,39 @@ template <typename Duration2> operator ExecutionPlan<Duration2>() const { - return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations }; + return {iterations_per_sample, + estimated_duration, + benchmark, + warmup_time, + warmup_iterations}; } template <typename Clock> - std::vector<FloatDuration<Clock>> run(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const { + std::vector<FloatDuration<Clock>> + run(const IConfig& cfg, + Environment<FloatDuration<Clock>> env) const { // warmup a bit - Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{})); + Detail::run_for_at_least<Clock>( + std::chrono::duration_cast<ClockDuration<Clock>>( + warmup_time), + warmup_iterations, + Detail::repeat(now<Clock>{})); std::vector<FloatDuration<Clock>> times; times.reserve(cfg.benchmarkSamples()); - std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] { - Detail::ChronometerModel<Clock> model; - this->benchmark(Chronometer(model, iterations_per_sample)); - auto sample_time = model.elapsed() - env.clock_cost.mean; - if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero(); - return sample_time / iterations_per_sample; - }); + std::generate_n( + std::back_inserter(times), + cfg.benchmarkSamples(), + [this, env] { + Detail::ChronometerModel<Clock> model; + this->benchmark( + Chronometer(model, iterations_per_sample)); + auto sample_time = + model.elapsed() - env.clock_cost.mean; + if (sample_time < FloatDuration<Clock>::zero()) + sample_time = FloatDuration<Clock>::zero(); + return sample_time / iterations_per_sample; + }); return times; } }; @@ -6930,14 +7964,12 @@ // end catch_execution_plan.hpp // start catch_estimate_clock.hpp - // Environment measurement - +// Environment measurement // start catch_stats.hpp // Statistical analysis tools - #include <algorithm> #include <functional> #include <vector> @@ -6954,14 +7986,21 @@ namespace Detail { using sample = std::vector<double>; - double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last); + double + weighted_average_quantile(int k, + int q, + std::vector<double>::iterator first, + std::vector<double>::iterator last); template <typename Iterator> - OutlierClassification classify_outliers(Iterator first, Iterator last) { + OutlierClassification classify_outliers(Iterator first, + Iterator last) { std::vector<double> copy(first, last); - auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end()); - auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end()); + auto q1 = + weighted_average_quantile(1, 4, copy.begin(), copy.end()); + auto q3 = + weighted_average_quantile(3, 4, copy.begin(), copy.end()); auto iqr = q3 - q1; auto los = q1 - (iqr * 3.); auto lom = q1 - (iqr * 1.5); @@ -6971,10 +8010,14 @@ OutlierClassification o; for (; first != last; ++first) { auto&& t = *first; - if (t < los) ++o.low_severe; - else if (t < lom) ++o.low_mild; - else if (t > his) ++o.high_severe; - else if (t > him) ++o.high_mild; + if (t < los) + ++o.low_severe; + else if (t < lom) + ++o.low_mild; + else if (t > his) + ++o.high_severe; + else if (t > him) + ++o.high_mild; ++o.samples_seen; } return o; @@ -6988,24 +8031,35 @@ } template <typename URng, typename Iterator, typename Estimator> - sample resample(URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) { + sample resample(URng& rng, + int resamples, + Iterator first, + Iterator last, + Estimator& estimator) { auto n = last - first; std::uniform_int_distribution<decltype(n)> dist(0, n - 1); sample out; out.reserve(resamples); - std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] { - std::vector<double> resampled; - resampled.reserve(n); - std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] { return first[dist(rng)]; }); - return estimator(resampled.begin(), resampled.end()); - }); + std::generate_n( + std::back_inserter(out), + resamples, + [n, first, &estimator, &dist, &rng] { + std::vector<double> resampled; + resampled.reserve(n); + std::generate_n( + std::back_inserter(resampled), + n, + [first, &dist, &rng] { return first[dist(rng)]; }); + return estimator(resampled.begin(), resampled.end()); + }); std::sort(out.begin(), out.end()); return out; } template <typename Estimator, typename Iterator> - sample jackknife(Estimator&& estimator, Iterator first, Iterator last) { + sample + jackknife(Estimator&& estimator, Iterator first, Iterator last) { auto n = last - first; auto second = std::next(first); sample results; @@ -7028,35 +8082,53 @@ double normal_quantile(double p); template <typename Iterator, typename Estimator> - Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last, sample const& resample, Estimator&& estimator) { + Estimate<double> bootstrap(double confidence_level, + Iterator first, + Iterator last, + sample const& resample, + Estimator&& estimator) { auto n_samples = last - first; double point = estimator(first, last); // Degenerate case with a single sample - if (n_samples == 1) return { point, point, point, confidence_level }; + if (n_samples == 1) + return {point, point, point, confidence_level}; sample jack = jackknife(estimator, first, last); double jack_mean = mean(jack.begin(), jack.end()); double sum_squares, sum_cubes; - std::tie(sum_squares, sum_cubes) = std::accumulate(jack.begin(), jack.end(), std::make_pair(0., 0.), [jack_mean](std::pair<double, double> sqcb, double x) -> std::pair<double, double> { - auto d = jack_mean - x; - auto d2 = d * d; - auto d3 = d2 * d; - return { sqcb.first + d2, sqcb.second + d3 }; - }); + std::tie(sum_squares, sum_cubes) = std::accumulate( + jack.begin(), + jack.end(), + std::make_pair(0., 0.), + [jack_mean](std::pair<double, double> sqcb, + double x) -> std::pair<double, double> { + auto d = jack_mean - x; + auto d2 = d * d; + auto d3 = d2 * d; + return {sqcb.first + d2, sqcb.second + d3}; + }); double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5)); int n = static_cast<int>(resample.size()); - double prob_n = std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) / (double)n; + double prob_n = + std::count_if(resample.begin(), + resample.end(), + [point](double x) { return x < point; }) / + (double)n; // degenerate case with uniform samples - if (prob_n == 0) return { point, point, point, confidence_level }; + if (prob_n == 0) + return {point, point, point, confidence_level}; double bias = normal_quantile(prob_n); double z1 = normal_quantile((1. - confidence_level) / 2.); auto cumn = [n](double x) -> int { - return std::lround(normal_cdf(x) * n); }; - auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); }; + return std::lround(normal_cdf(x) * n); + }; + auto a = [bias, accel](double b) { + return bias + b / (1. - accel * b); + }; double b1 = bias + z1; double b2 = bias - z1; double a1 = a(b1); @@ -7064,10 +8136,12 @@ auto lo = (std::max)(cumn(a1), 0); auto hi = (std::min)(cumn(a2), n - 1); - return { point, resample[lo], resample[hi], confidence_level }; + return {point, resample[lo], resample[hi], confidence_level}; } - double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n); + double outlier_variance(Estimate<double> mean, + Estimate<double> stddev, + int n); struct bootstrap_analysis { Estimate<double> mean; @@ -7075,9 +8149,13 @@ double outlier_variance; }; - bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last); + bootstrap_analysis + analyse_samples(double confidence_level, + int n_resamples, + std::vector<double>::iterator first, + std::vector<double>::iterator last); } // namespace Detail - } // namespace Benchmark + } // namespace Benchmark } // namespace Catch // end catch_stats.hpp @@ -7090,17 +8168,20 @@ namespace Catch { namespace Benchmark { namespace Detail { - template <typename Clock> - std::vector<double> resolution(int k) { + template <typename Clock> std::vector<double> resolution(int k) { std::vector<TimePoint<Clock>> times; times.reserve(k + 1); std::generate_n(std::back_inserter(times), k + 1, now<Clock>{}); std::vector<double> deltas; deltas.reserve(k); - std::transform(std::next(times.begin()), times.end(), times.begin(), - std::back_inserter(deltas), - [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); }); + std::transform(std::next(times.begin()), + times.end(), + times.begin(), + std::back_inserter(deltas), + [](TimePoint<Clock> a, TimePoint<Clock> b) { + return static_cast<double>((a - b).count()); + }); return deltas; } @@ -7109,48 +8190,68 @@ const auto warmup_time = std::chrono::milliseconds(100); const auto minimum_ticks = 1000; const auto warmup_seed = 10000; - const auto clock_resolution_estimation_time = std::chrono::milliseconds(500); - const auto clock_cost_estimation_time_limit = std::chrono::seconds(1); + const auto clock_resolution_estimation_time = + std::chrono::milliseconds(500); + const auto clock_cost_estimation_time_limit = + std::chrono::seconds(1); const auto clock_cost_estimation_tick_limit = 100000; - const auto clock_cost_estimation_time = std::chrono::milliseconds(10); + const auto clock_cost_estimation_time = + std::chrono::milliseconds(10); const auto clock_cost_estimation_iterations = 10000; - template <typename Clock> - int warmup() { - return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>) + template <typename Clock> int warmup() { + return run_for_at_least<Clock>( + std::chrono::duration_cast<ClockDuration<Clock>>( + warmup_time), + warmup_seed, + &resolution<Clock>) .iterations; } template <typename Clock> - EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) { - auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>) - .result; + EnvironmentEstimate<FloatDuration<Clock>> + estimate_clock_resolution(int iterations) { + auto r = run_for_at_least<Clock>( + std::chrono::duration_cast<ClockDuration<Clock>>( + clock_resolution_estimation_time), + iterations, + &resolution<Clock>) + .result; return { FloatDuration<Clock>(mean(r.begin(), r.end())), classify_outliers(r.begin(), r.end()), }; } template <typename Clock> - EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) { + EnvironmentEstimate<FloatDuration<Clock>> + estimate_clock_cost(FloatDuration<Clock> resolution) { auto time_limit = (std::min)( resolution * clock_cost_estimation_tick_limit, FloatDuration<Clock>(clock_cost_estimation_time_limit)); auto time_clock = [](int k) { return Detail::measure<Clock>([k] { - for (int i = 0; i < k; ++i) { - volatile auto ignored = Clock::now(); - (void)ignored; - } - }).elapsed; + for (int i = 0; i < k; ++i) { + volatile auto ignored = Clock::now(); + (void)ignored; + } + }) + .elapsed; }; time_clock(1); int iters = clock_cost_estimation_iterations; - auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock); + auto&& r = run_for_at_least<Clock>( + std::chrono::duration_cast<ClockDuration<Clock>>( + clock_cost_estimation_time), + iters, + time_clock); std::vector<double> times; - int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed)); + int nsamples = + static_cast<int>(std::ceil(time_limit / r.elapsed)); times.reserve(nsamples); - std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] { - return static_cast<double>((time_clock(r.iterations) / r.iterations).count()); - }); + std::generate_n( + std::back_inserter(times), nsamples, [time_clock, &r] { + return static_cast<double>( + (time_clock(r.iterations) / r.iterations).count()); + }); return { FloatDuration<Clock>(mean(times.begin(), times.end())), classify_outliers(times.begin(), times.end()), @@ -7165,27 +8266,26 @@ } auto iters = Detail::warmup<Clock>(); - auto resolution = Detail::estimate_clock_resolution<Clock>(iters); + auto resolution = + Detail::estimate_clock_resolution<Clock>(iters); auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean); - env = new Environment<FloatDuration<Clock>>{ resolution, cost }; + env = new Environment<FloatDuration<Clock>>{resolution, cost}; return *env; } } // namespace Detail - } // namespace Benchmark + } // namespace Benchmark } // namespace Catch // end catch_estimate_clock.hpp // start catch_analyse.hpp - // Run and analyse one benchmark - +// Run and analyse one benchmark // start catch_sample_analysis.hpp // Benchmark results - #include <algorithm> #include <vector> #include <string> @@ -7193,8 +8293,7 @@ namespace Catch { namespace Benchmark { - template <typename Duration> - struct SampleAnalysis { + template <typename Duration> struct SampleAnalysis { std::vector<Duration> samples; Estimate<Duration> mean; Estimate<Duration> standard_deviation; @@ -7205,7 +8304,10 @@ operator SampleAnalysis<Duration2>() const { std::vector<Duration2> samples2; samples2.reserve(samples.size()); - std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); }); + std::transform(samples.begin(), + samples.end(), + std::back_inserter(samples2), + [](Duration d) { return Duration2(d); }); return { std::move(samples2), mean, @@ -7227,26 +8329,40 @@ namespace Benchmark { namespace Detail { template <typename Duration, typename Iterator> - SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) { + SampleAnalysis<Duration> analyse(const IConfig& cfg, + Environment<Duration>, + Iterator first, + Iterator last) { if (!cfg.benchmarkNoAnalysis()) { std::vector<double> samples; samples.reserve(last - first); - std::transform(first, last, std::back_inserter(samples), [](Duration d) { return d.count(); }); + std::transform(first, + last, + std::back_inserter(samples), + [](Duration d) { return d.count(); }); - auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end()); - auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end()); + auto analysis = Catch::Benchmark::Detail::analyse_samples( + cfg.benchmarkConfidenceInterval(), + cfg.benchmarkResamples(), + samples.begin(), + samples.end()); + auto outliers = Catch::Benchmark::Detail::classify_outliers( + samples.begin(), samples.end()); auto wrap_estimate = [](Estimate<double> e) { - return Estimate<Duration> { + return Estimate<Duration>{ Duration(e.point), - Duration(e.lower_bound), - Duration(e.upper_bound), - e.confidence_interval, + Duration(e.lower_bound), + Duration(e.upper_bound), + e.confidence_interval, }; }; std::vector<Duration> samples2; samples2.reserve(samples.size()); - std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](double d) { return Duration(d); }); + std::transform(samples.begin(), + samples.end(), + std::back_inserter(samples2), + [](double d) { return Duration(d); }); return { std::move(samples2), wrap_estimate(analysis.mean), @@ -7266,17 +8382,16 @@ } mean /= i; - return { - std::move(samples), - Estimate<Duration>{mean, mean, mean, 0.0}, - Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0}, - OutlierClassification{}, - 0.0 - }; + return {std::move(samples), + Estimate<Duration>{mean, mean, mean, 0.0}, + Estimate<Duration>{ + Duration(0), Duration(0), Duration(0), 0.0}, + OutlierClassification{}, + 0.0}; } } } // namespace Detail - } // namespace Benchmark + } // namespace Benchmark } // namespace Catch // end catch_analyse.hpp @@ -7289,140 +8404,160 @@ namespace Catch { namespace Benchmark { struct Benchmark { - Benchmark(std::string &&name) - : name(std::move(name)) {} + Benchmark(std::string&& name) : name(std::move(name)) {} template <class FUN> - Benchmark(std::string &&name, FUN &&func) - : fun(std::move(func)), name(std::move(name)) {} + Benchmark(std::string&& name, FUN&& func) : + fun(std::move(func)), name(std::move(name)) {} template <typename Clock> - ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const { - auto min_time = env.clock_resolution.mean * Detail::minimum_ticks; - auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(cfg.benchmarkWarmupTime())); - auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun); - int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed)); - return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(cfg.benchmarkWarmupTime()), Detail::warmup_iterations }; + ExecutionPlan<FloatDuration<Clock>> + prepare(const IConfig& cfg, + Environment<FloatDuration<Clock>> env) const { + auto min_time = + env.clock_resolution.mean * Detail::minimum_ticks; + auto run_time = + std::max(min_time, + std::chrono::duration_cast<decltype(min_time)>( + cfg.benchmarkWarmupTime())); + auto&& test = Detail::run_for_at_least<Clock>( + std::chrono::duration_cast<ClockDuration<Clock>>(run_time), + 1, + fun); + int new_iters = static_cast<int>( + std::ceil(min_time * test.iterations / test.elapsed)); + return {new_iters, + test.elapsed / test.iterations * new_iters * + cfg.benchmarkSamples(), + fun, + std::chrono::duration_cast<FloatDuration<Clock>>( + cfg.benchmarkWarmupTime()), + Detail::warmup_iterations}; } - template <typename Clock = default_clock> - void run() { + template <typename Clock = default_clock> void run() { IConfigPtr cfg = getCurrentContext().getConfig(); auto env = Detail::measure_environment<Clock>(); getResultCapture().benchmarkPreparing(name); - CATCH_TRY{ - auto plan = user_code([&] { - return prepare<Clock>(*cfg, env); - }); + CATCH_TRY { + auto plan = + user_code([&] { return prepare<Clock>(*cfg, env); }); - BenchmarkInfo info { - name, - plan.estimated_duration.count(), - plan.iterations_per_sample, - cfg->benchmarkSamples(), - cfg->benchmarkResamples(), - env.clock_resolution.mean.count(), - env.clock_cost.mean.count() - }; + BenchmarkInfo info{name, + plan.estimated_duration.count(), + plan.iterations_per_sample, + cfg->benchmarkSamples(), + cfg->benchmarkResamples(), + env.clock_resolution.mean.count(), + env.clock_cost.mean.count()}; getResultCapture().benchmarkStarting(info); - auto samples = user_code([&] { - return plan.template run<Clock>(*cfg, env); - }); + auto samples = user_code( + [&] { return plan.template run<Clock>(*cfg, env); }); - auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end()); - BenchmarkStats<FloatDuration<Clock>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance }; + auto analysis = Detail::analyse( + *cfg, env, samples.begin(), samples.end()); + BenchmarkStats<FloatDuration<Clock>> stats{ + info, + analysis.samples, + analysis.mean, + analysis.standard_deviation, + analysis.outliers, + analysis.outlier_variance}; getResultCapture().benchmarkEnded(stats); - - } CATCH_CATCH_ALL{ - if (translateActiveException() != Detail::benchmarkErrorMsg) // benchmark errors have been reported, otherwise rethrow. + } + CATCH_CATCH_ALL { + if (translateActiveException() != + Detail::benchmarkErrorMsg) // benchmark errors have been + // reported, otherwise + // rethrow. std::rethrow_exception(std::current_exception()); } } // sets lambda to be used in fun *and* executes benchmark! template <typename Fun, - typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0> - Benchmark & operator=(Fun func) { + typename std::enable_if< + !Detail::is_related<Fun, Benchmark>::value, + int>::type = 0> + Benchmark& operator=(Fun func) { fun = Detail::BenchmarkFunction(func); run(); return *this; } - explicit operator bool() { - return true; - } + explicit operator bool() { return true; } private: Detail::BenchmarkFunction fun; std::string name; }; - } + } // namespace Benchmark } // namespace Catch #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1 #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2 -#define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\ - if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \ - BenchmarkName = [&](int benchmarkIndex) +#define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex) \ + if (Catch::Benchmark::Benchmark BenchmarkName{name}) \ + BenchmarkName = [&](int benchmarkIndex) -#define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\ - if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \ - BenchmarkName = [&] +#define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name) \ + if (Catch::Benchmark::Benchmark BenchmarkName{name}) \ + BenchmarkName = [&] // end catch_benchmark.hpp // start catch_constructor.hpp // Constructor and destructor helpers - #include <type_traits> namespace Catch { namespace Benchmark { namespace Detail { - template <typename T, bool Destruct> - struct ObjectStorage - { - using TStorage = typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type; + template <typename T, bool Destruct> struct ObjectStorage { + using TStorage = typename std::aligned_storage< + sizeof(T), + std::alignment_of<T>::value>::type; ObjectStorage() : data() {} - ObjectStorage(const ObjectStorage& other) - { - new(&data) T(other.stored_object()); + ObjectStorage(const ObjectStorage& other) { + new (&data) T(other.stored_object()); } - ObjectStorage(ObjectStorage&& other) - { - new(&data) T(std::move(other.stored_object())); + ObjectStorage(ObjectStorage&& other) { + new (&data) T(std::move(other.stored_object())); } ~ObjectStorage() { destruct_on_exit<T>(); } - template <typename... Args> - void construct(Args&&... args) - { + template <typename... Args> void construct(Args&&... args) { new (&data) T(std::forward<Args>(args)...); } template <bool AllowManualDestruction = !Destruct> - typename std::enable_if<AllowManualDestruction>::type destruct() - { + typename std::enable_if<AllowManualDestruction>::type + destruct() { stored_object().~T(); } private: - // If this is a constructor benchmark, destruct the underlying object + // If this is a constructor benchmark, destruct the underlying + // object template <typename U> - void destruct_on_exit(typename std::enable_if<Destruct, U>::type* = 0) { destruct<true>(); } + void destruct_on_exit( + typename std::enable_if<Destruct, U>::type* = 0) { + destruct<true>(); + } // Otherwise, don't template <typename U> - void destruct_on_exit(typename std::enable_if<!Destruct, U>::type* = 0) { } + void destruct_on_exit( + typename std::enable_if<!Destruct, U>::type* = 0) {} T& stored_object() { return *static_cast<T*>(static_cast<void*>(&data)); @@ -7434,15 +8569,15 @@ TStorage data; }; - } + } // namespace Detail template <typename T> using storage_for = Detail::ObjectStorage<T, true>; template <typename T> using destructable_object = Detail::ObjectStorage<T, false>; - } -} + } // namespace Benchmark +} // namespace Catch // end catch_constructor.hpp // end catch_benchmarking_all.hpp @@ -7466,162 +8601,167 @@ #include <memory> namespace Catch { -namespace TestCaseTracking { + namespace TestCaseTracking { - struct NameAndLocation { - std::string name; - SourceLineInfo location; + struct NameAndLocation { + std::string name; + SourceLineInfo location; - NameAndLocation( std::string const& _name, SourceLineInfo const& _location ); - friend bool operator==(NameAndLocation const& lhs, NameAndLocation const& rhs) { - return lhs.name == rhs.name - && lhs.location == rhs.location; - } - }; - - class ITracker; - - using ITrackerPtr = std::shared_ptr<ITracker>; - - class ITracker { - NameAndLocation m_nameAndLocation; - - public: - ITracker(NameAndLocation const& nameAndLoc) : - m_nameAndLocation(nameAndLoc) - {} - - // static queries - NameAndLocation const& nameAndLocation() const { - return m_nameAndLocation; - } - - virtual ~ITracker(); - - // dynamic queries - virtual bool isComplete() const = 0; // Successfully completed or failed - virtual bool isSuccessfullyCompleted() const = 0; - virtual bool isOpen() const = 0; // Started but not complete - virtual bool hasChildren() const = 0; - virtual bool hasStarted() const = 0; - - virtual ITracker& parent() = 0; - - // actions - virtual void close() = 0; // Successfully complete - virtual void fail() = 0; - virtual void markAsNeedingAnotherRun() = 0; - - virtual void addChild( ITrackerPtr const& child ) = 0; - virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0; - virtual void openChild() = 0; - - // Debug/ checking - virtual bool isSectionTracker() const = 0; - virtual bool isGeneratorTracker() const = 0; - }; - - class TrackerContext { - - enum RunState { - NotStarted, - Executing, - CompletedCycle + NameAndLocation(std::string const& _name, + SourceLineInfo const& _location); + friend bool operator==(NameAndLocation const& lhs, + NameAndLocation const& rhs) { + return lhs.name == rhs.name && lhs.location == rhs.location; + } }; - ITrackerPtr m_rootTracker; - ITracker* m_currentTracker = nullptr; - RunState m_runState = NotStarted; + class ITracker; - public: + using ITrackerPtr = std::shared_ptr<ITracker>; - ITracker& startRun(); - void endRun(); + class ITracker { + NameAndLocation m_nameAndLocation; - void startCycle(); - void completeCycle(); + public: + ITracker(NameAndLocation const& nameAndLoc) : + m_nameAndLocation(nameAndLoc) {} - bool completedCycle() const; - ITracker& currentTracker(); - void setCurrentTracker( ITracker* tracker ); - }; + // static queries + NameAndLocation const& nameAndLocation() const { + return m_nameAndLocation; + } - class TrackerBase : public ITracker { - protected: - enum CycleState { - NotStarted, - Executing, - ExecutingChildren, - NeedsAnotherRun, - CompletedSuccessfully, - Failed + virtual ~ITracker(); + + // dynamic queries + virtual bool + isComplete() const = 0; // Successfully completed or failed + virtual bool isSuccessfullyCompleted() const = 0; + virtual bool isOpen() const = 0; // Started but not complete + virtual bool hasChildren() const = 0; + virtual bool hasStarted() const = 0; + + virtual ITracker& parent() = 0; + + // actions + virtual void close() = 0; // Successfully complete + virtual void fail() = 0; + virtual void markAsNeedingAnotherRun() = 0; + + virtual void addChild(ITrackerPtr const& child) = 0; + virtual ITrackerPtr + findChild(NameAndLocation const& nameAndLocation) = 0; + virtual void openChild() = 0; + + // Debug/ checking + virtual bool isSectionTracker() const = 0; + virtual bool isGeneratorTracker() const = 0; }; - using Children = std::vector<ITrackerPtr>; - TrackerContext& m_ctx; - ITracker* m_parent; - Children m_children; - CycleState m_runState = NotStarted; + class TrackerContext { - public: - TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ); + enum RunState { NotStarted, Executing, CompletedCycle }; - bool isComplete() const override; - bool isSuccessfullyCompleted() const override; - bool isOpen() const override; - bool hasChildren() const override; - bool hasStarted() const override { - return m_runState != NotStarted; - } + ITrackerPtr m_rootTracker; + ITracker* m_currentTracker = nullptr; + RunState m_runState = NotStarted; - void addChild( ITrackerPtr const& child ) override; + public: + ITracker& startRun(); + void endRun(); - ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override; - ITracker& parent() override; + void startCycle(); + void completeCycle(); - void openChild() override; + bool completedCycle() const; + ITracker& currentTracker(); + void setCurrentTracker(ITracker* tracker); + }; - bool isSectionTracker() const override; - bool isGeneratorTracker() const override; + class TrackerBase : public ITracker { + protected: + enum CycleState { + NotStarted, + Executing, + ExecutingChildren, + NeedsAnotherRun, + CompletedSuccessfully, + Failed + }; - void open(); + using Children = std::vector<ITrackerPtr>; + TrackerContext& m_ctx; + ITracker* m_parent; + Children m_children; + CycleState m_runState = NotStarted; - void close() override; - void fail() override; - void markAsNeedingAnotherRun() override; + public: + TrackerBase(NameAndLocation const& nameAndLocation, + TrackerContext& ctx, + ITracker* parent); - private: - void moveToParent(); - void moveToThis(); - }; + bool isComplete() const override; + bool isSuccessfullyCompleted() const override; + bool isOpen() const override; + bool hasChildren() const override; + bool hasStarted() const override { + return m_runState != NotStarted; + } - class SectionTracker : public TrackerBase { - std::vector<std::string> m_filters; - std::string m_trimmed_name; - public: - SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ); + void addChild(ITrackerPtr const& child) override; - bool isSectionTracker() const override; + ITrackerPtr + findChild(NameAndLocation const& nameAndLocation) override; + ITracker& parent() override; - bool isComplete() const override; + void openChild() override; - static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ); + bool isSectionTracker() const override; + bool isGeneratorTracker() const override; - void tryOpen(); + void open(); - void addInitialFilters( std::vector<std::string> const& filters ); - void addNextFilters( std::vector<std::string> const& filters ); - //! Returns filters active in this tracker - std::vector<std::string> const& getFilters() const; - //! Returns whitespace-trimmed name of the tracked section - std::string const& trimmedName() const; - }; + void close() override; + void fail() override; + void markAsNeedingAnotherRun() override; -} // namespace TestCaseTracking + private: + void moveToParent(); + void moveToThis(); + }; -using TestCaseTracking::ITracker; -using TestCaseTracking::TrackerContext; -using TestCaseTracking::SectionTracker; + class SectionTracker : public TrackerBase { + std::vector<std::string> m_filters; + std::string m_trimmed_name; + + public: + SectionTracker(NameAndLocation const& nameAndLocation, + TrackerContext& ctx, + ITracker* parent); + + bool isSectionTracker() const override; + + bool isComplete() const override; + + static SectionTracker& + acquire(TrackerContext& ctx, + NameAndLocation const& nameAndLocation); + + void tryOpen(); + + void addInitialFilters(std::vector<std::string> const& filters); + void addNextFilters(std::vector<std::string> const& filters); + //! Returns filters active in this tracker + std::vector<std::string> const& getFilters() const; + //! Returns whitespace-trimmed name of the tracked section + std::string const& trimmedName() const; + }; + + } // namespace TestCaseTracking + + using TestCaseTracking::ITracker; + using TestCaseTracking::SectionTracker; + using TestCaseTracking::TrackerContext; } // namespace Catch @@ -7636,7 +8776,7 @@ ~LeakDetector(); }; -} +} // namespace Catch // end catch_leak_detector.h // Cpp files will be included in the single-header file here // start catch_stats.cpp @@ -7654,7 +8794,8 @@ namespace { double erf_inv(double x) { - // Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems, Volume 2 + // Code accompanying the article "Approximating the erfinv function" in + // GPU Computing Gems, Volume 2 double w, p; w = -log((1.0 - x) * (1.0 + x)); @@ -7728,37 +8869,45 @@ return p * x; } - double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) { + double standard_deviation(std::vector<double>::iterator first, + std::vector<double>::iterator last) { auto m = Catch::Benchmark::Detail::mean(first, last); - double variance = std::accumulate(first, last, 0., [m](double a, double b) { - double diff = b - m; - return a + diff * diff; - }) / (last - first); - return std::sqrt(variance); + double variance = std::accumulate(first, + last, + 0., + [m](double a, double b) { + double diff = b - m; + return a + diff * diff; + }) / + (last - first); + return std::sqrt(variance); } -} +} // namespace namespace Catch { namespace Benchmark { namespace Detail { - double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) { + double + weighted_average_quantile(int k, + int q, + std::vector<double>::iterator first, + std::vector<double>::iterator last) { auto count = last - first; double idx = (count - 1) * k / static_cast<double>(q); int j = static_cast<int>(idx); double g = idx - j; std::nth_element(first, first + j, last); auto xj = first[j]; - if (g == 0) return xj; + if (g == 0) + return xj; auto xj1 = *std::min_element(first + (j + 1), last); return xj + g * (xj1 - xj); } - double erfc_inv(double x) { - return erf_inv(1.0 - x); - } + double erfc_inv(double x) { return erf_inv(1.0 - x); } double normal_quantile(double p) { static const double ROOT_TWO = std::sqrt(2.0); @@ -7770,13 +8919,16 @@ } result = -erfc_inv(2.0 * p); - // result *= normal distribution standard deviation (1.0) * sqrt(2) + // result *= normal distribution standard deviation (1.0) * + // sqrt(2) result *= /*sd * */ ROOT_TWO; // result += normal disttribution mean (0) return result; } - double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) { + double outlier_variance(Estimate<double> mean, + Estimate<double> stddev, + int n) { double sb = stddev.point; double mn = mean.point / n; double mg_min = mn / 2.; @@ -7799,29 +8951,42 @@ return (nc / n) * (sb2 - nc * sg2); }; - return (std::min)(var_out(1), var_out((std::min)(c_max(0.), c_max(mg_min)))) / sb2; + return (std::min)( + var_out(1), + var_out((std::min)(c_max(0.), c_max(mg_min)))) / + sb2; } - bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) { + bootstrap_analysis + analyse_samples(double confidence_level, + int n_resamples, + std::vector<double>::iterator first, + std::vector<double>::iterator last) { CATCH_INTERNAL_START_WARNINGS_SUPPRESSION CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS static std::random_device entropy; CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION - auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++ + auto n = static_cast<int>( + last - first); // seriously, one can't use integral types + // without hell in C++ auto mean = &Detail::mean<std::vector<double>::iterator>; auto stddev = &standard_deviation; #if defined(CATCH_CONFIG_USE_ASYNC) - auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) { - auto seed = entropy(); - return std::async(std::launch::async, [=] { - std::mt19937 rng(seed); - auto resampled = resample(rng, n_resamples, first, last, f); - return bootstrap(confidence_level, first, last, resampled, f); - }); - }; + auto Estimate = + [=](double (*f)(std::vector<double>::iterator, + std::vector<double>::iterator)) { + auto seed = entropy(); + return std::async(std::launch::async, [=] { + std::mt19937 rng(seed); + auto resampled = + resample(rng, n_resamples, first, last, f); + return bootstrap( + confidence_level, first, last, resampled, f); + }); + }; auto mean_future = Estimate(mean); auto stddev_future = Estimate(stddev); @@ -7829,23 +8994,27 @@ auto mean_estimate = mean_future.get(); auto stddev_estimate = stddev_future.get(); #else - auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) { + auto Estimate = [=](double (*f)( + std::vector<double>::iterator, + std::vector<double>::iterator)) { auto seed = entropy(); std::mt19937 rng(seed); auto resampled = resample(rng, n_resamples, first, last, f); - return bootstrap(confidence_level, first, last, resampled, f); + return bootstrap( + confidence_level, first, last, resampled, f); }; auto mean_estimate = Estimate(mean); auto stddev_estimate = Estimate(stddev); #endif // CATCH_USE_ASYNC - double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n); + double outlier_variance = + Detail::outlier_variance(mean_estimate, stddev_estimate, n); - return { mean_estimate, stddev_estimate, outlier_variance }; + return {mean_estimate, stddev_estimate, outlier_variance}; } } // namespace Detail - } // namespace Benchmark + } // namespace Benchmark } // namespace Catch #endif // CATCH_CONFIG_ENABLE_BENCHMARKING @@ -7857,76 +9026,82 @@ namespace { -// Performs equivalent check of std::fabs(lhs - rhs) <= margin -// But without the subtraction to allow for INFINITY in comparison -bool marginComparison(double lhs, double rhs, double margin) { - return (lhs + margin >= rhs) && (rhs + margin >= lhs); -} + // Performs equivalent check of std::fabs(lhs - rhs) <= margin + // But without the subtraction to allow for INFINITY in comparison + bool marginComparison(double lhs, double rhs, double margin) { + return (lhs + margin >= rhs) && (rhs + margin >= lhs); + } -} +} // namespace namespace Catch { -namespace Detail { + namespace Detail { - Approx::Approx ( double value ) - : m_epsilon( std::numeric_limits<float>::epsilon()*100 ), - m_margin( 0.0 ), - m_scale( 0.0 ), - m_value( value ) - {} + Approx::Approx(double value) : + m_epsilon(std::numeric_limits<float>::epsilon() * 100), + m_margin(0.0), + m_scale(0.0), + m_value(value) {} - Approx Approx::custom() { - return Approx( 0 ); + Approx Approx::custom() { return Approx(0); } + + Approx Approx::operator-() const { + auto temp(*this); + temp.m_value = -temp.m_value; + return temp; + } + + std::string Approx::toString() const { + ReusableStringStream rss; + rss << "Approx( " << ::Catch::Detail::stringify(m_value) << " )"; + return rss.str(); + } + + bool Approx::equalityComparisonImpl(const double other) const { + // First try with fixed margin, then compute margin based on + // epsilon, scale and Approx's value Thanks to Richard Harris for + // his help refining the scaled margin value + return marginComparison(m_value, other, m_margin) || + marginComparison( + m_value, + other, + m_epsilon * + (m_scale + + std::fabs(std::isinf(m_value) ? 0 : m_value))); + } + + void Approx::setMargin(double newMargin) { + CATCH_ENFORCE(newMargin >= 0, + "Invalid Approx::margin: " + << newMargin << '.' + << " Approx::Margin has to be non-negative."); + m_margin = newMargin; + } + + void Approx::setEpsilon(double newEpsilon) { + CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0, + "Invalid Approx::epsilon: " + << newEpsilon << '.' + << " Approx::epsilon has to be in [0, 1]"); + m_epsilon = newEpsilon; + } + + } // end namespace Detail + + namespace literals { + Detail::Approx operator"" _a(long double val) { + return Detail::Approx(val); + } + Detail::Approx operator"" _a(unsigned long long val) { + return Detail::Approx(val); + } + } // end namespace literals + + std::string StringMaker<Catch::Detail::Approx>::convert( + Catch::Detail::Approx const& value) { + return value.toString(); } - Approx Approx::operator-() const { - auto temp(*this); - temp.m_value = -temp.m_value; - return temp; - } - - std::string Approx::toString() const { - ReusableStringStream rss; - rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )"; - return rss.str(); - } - - bool Approx::equalityComparisonImpl(const double other) const { - // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value - // Thanks to Richard Harris for his help refining the scaled margin value - return marginComparison(m_value, other, m_margin) - || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value))); - } - - void Approx::setMargin(double newMargin) { - CATCH_ENFORCE(newMargin >= 0, - "Invalid Approx::margin: " << newMargin << '.' - << " Approx::Margin has to be non-negative."); - m_margin = newMargin; - } - - void Approx::setEpsilon(double newEpsilon) { - CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0, - "Invalid Approx::epsilon: " << newEpsilon << '.' - << " Approx::epsilon has to be in [0, 1]"); - m_epsilon = newEpsilon; - } - -} // end namespace Detail - -namespace literals { - Detail::Approx operator "" _a(long double val) { - return Detail::Approx(val); - } - Detail::Approx operator "" _a(unsigned long long val) { - return Detail::Approx(val); - } -} // end namespace literals - -std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) { - return value.toString(); -} - } // end namespace Catch // end catch_approx.cpp // start catch_assertionhandler.cpp @@ -7939,49 +9114,54 @@ #ifdef CATCH_PLATFORM_MAC - #if defined(__i386__) || defined(__x86_64__) - #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */ - #elif defined(__aarch64__) - #define CATCH_TRAP() __asm__(".inst 0xd4200000") - #endif +#if defined(__i386__) || defined(__x86_64__) +#define CATCH_TRAP() __asm__("int $3\n" : :) /* NOLINT */ +#elif defined(__aarch64__) +#define CATCH_TRAP() __asm__(".inst 0xd4200000") +#endif #elif defined(CATCH_PLATFORM_IPHONE) - // use inline assembler - #if defined(__i386__) || defined(__x86_64__) - #define CATCH_TRAP() __asm__("int $3") - #elif defined(__aarch64__) - #define CATCH_TRAP() __asm__(".inst 0xd4200000") - #elif defined(__arm__) && !defined(__thumb__) - #define CATCH_TRAP() __asm__(".inst 0xe7f001f0") - #elif defined(__arm__) && defined(__thumb__) - #define CATCH_TRAP() __asm__(".inst 0xde01") - #endif +// use inline assembler +#if defined(__i386__) || defined(__x86_64__) +#define CATCH_TRAP() __asm__("int $3") +#elif defined(__aarch64__) +#define CATCH_TRAP() __asm__(".inst 0xd4200000") +#elif defined(__arm__) && !defined(__thumb__) +#define CATCH_TRAP() __asm__(".inst 0xe7f001f0") +#elif defined(__arm__) && defined(__thumb__) +#define CATCH_TRAP() __asm__(".inst 0xde01") +#endif #elif defined(CATCH_PLATFORM_LINUX) - // If we can use inline assembler, do it because this allows us to break - // directly at the location of the failing check instead of breaking inside - // raise() called from it, i.e. one stack frame below. - #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64)) - #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */ - #else // Fall back to the generic way. - #include <signal.h> +// If we can use inline assembler, do it because this allows us to break +// directly at the location of the failing check instead of breaking inside +// raise() called from it, i.e. one stack frame below. +#if defined(__GNUC__) && (defined(__i386) || defined(__x86_64)) +#define CATCH_TRAP() asm volatile("int $3") /* NOLINT */ +#else // Fall back to the generic way. +#include <signal.h> - #define CATCH_TRAP() raise(SIGTRAP) - #endif +#define CATCH_TRAP() raise(SIGTRAP) +#endif #elif defined(_MSC_VER) - #define CATCH_TRAP() __debugbreak() +#define CATCH_TRAP() __debugbreak() #elif defined(__MINGW32__) - extern "C" __declspec(dllimport) void __stdcall DebugBreak(); - #define CATCH_TRAP() DebugBreak() +extern "C" __declspec(dllimport) void __stdcall DebugBreak(); +#define CATCH_TRAP() DebugBreak() #endif #ifndef CATCH_BREAK_INTO_DEBUGGER - #ifdef CATCH_TRAP - #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }() - #else - #define CATCH_BREAK_INTO_DEBUGGER() []{}() - #endif +#ifdef CATCH_TRAP +#define CATCH_BREAK_INTO_DEBUGGER() \ + [] { \ + if (Catch::isDebuggerActive()) { \ + CATCH_TRAP(); \ + } \ + }() +#else +#define CATCH_BREAK_INTO_DEBUGGER() [] {}() +#endif #endif // end catch_debugger.h @@ -8009,6 +9189,7 @@ // engage-disengage 1:1 pairing. void engage_platform(); void disengage_platform(); + public: // Should also have platform-specific implementations as needed FatalConditionHandler(); @@ -8021,7 +9202,9 @@ } void disengage() { - assert(m_started && "Handler cannot be uninstalled without being installed first"); + assert( + m_started && + "Handler cannot be uninstalled without being installed first"); m_started = false; disengage_platform(); } @@ -8030,14 +9213,13 @@ //! Simple RAII guard for (dis)engaging the FatalConditionHandler class FatalConditionHandlerGuard { FatalConditionHandler* m_handler; + public: - FatalConditionHandlerGuard(FatalConditionHandler* handler): + FatalConditionHandlerGuard(FatalConditionHandler* handler) : m_handler(handler) { m_handler->engage(); } - ~FatalConditionHandlerGuard() { - m_handler->disengage(); - } + ~FatalConditionHandlerGuard() { m_handler->disengage(); } }; } // end namespace Catch @@ -8054,15 +9236,21 @@ class RunContext : public IResultCapture, public IRunner { public: - RunContext( RunContext const& ) = delete; - RunContext& operator =( RunContext const& ) = delete; + RunContext(RunContext const&) = delete; + RunContext& operator=(RunContext const&) = delete; - explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter ); + explicit RunContext(IConfigPtr const& _config, + IStreamingReporterPtr&& reporter); ~RunContext() override; - void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount ); - void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount ); + void testGroupStarting(std::string const& testSpec, + std::size_t groupIndex, + std::size_t groupsCount); + void testGroupEnded(std::string const& testSpec, + Totals const& totals, + std::size_t groupIndex, + std::size_t groupsCount); Totals runTest(TestCase const& testCase); @@ -8070,49 +9258,46 @@ IStreamingReporter& reporter() const; public: // IResultCapture - // Assertion handlers - void handleExpr - ( AssertionInfo const& info, - ITransientExpression const& expr, - AssertionReaction& reaction ) override; - void handleMessage - ( AssertionInfo const& info, - ResultWas::OfType resultType, - StringRef const& message, - AssertionReaction& reaction ) override; - void handleUnexpectedExceptionNotThrown - ( AssertionInfo const& info, - AssertionReaction& reaction ) override; - void handleUnexpectedInflightException - ( AssertionInfo const& info, - std::string const& message, - AssertionReaction& reaction ) override; - void handleIncomplete - ( AssertionInfo const& info ) override; - void handleNonExpr - ( AssertionInfo const &info, - ResultWas::OfType resultType, - AssertionReaction &reaction ) override; + void handleExpr(AssertionInfo const& info, + ITransientExpression const& expr, + AssertionReaction& reaction) override; + void handleMessage(AssertionInfo const& info, + ResultWas::OfType resultType, + StringRef const& message, + AssertionReaction& reaction) override; + void handleUnexpectedExceptionNotThrown( + AssertionInfo const& info, AssertionReaction& reaction) override; + void + handleUnexpectedInflightException(AssertionInfo const& info, + std::string const& message, + AssertionReaction& reaction) override; + void handleIncomplete(AssertionInfo const& info) override; + void handleNonExpr(AssertionInfo const& info, + ResultWas::OfType resultType, + AssertionReaction& reaction) override; - bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override; + bool sectionStarted(SectionInfo const& sectionInfo, + Counts& assertions) override; - void sectionEnded( SectionEndInfo const& endInfo ) override; - void sectionEndedEarly( SectionEndInfo const& endInfo ) override; + void sectionEnded(SectionEndInfo const& endInfo) override; + void sectionEndedEarly(SectionEndInfo const& endInfo) override; - auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override; + auto acquireGeneratorTracker(StringRef generatorName, + SourceLineInfo const& lineInfo) + -> IGeneratorTracker& override; #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) - void benchmarkPreparing( std::string const& name ) override; - void benchmarkStarting( BenchmarkInfo const& info ) override; - void benchmarkEnded( BenchmarkStats<> const& stats ) override; - void benchmarkFailed( std::string const& error ) override; + void benchmarkPreparing(std::string const& name) override; + void benchmarkStarting(BenchmarkInfo const& info) override; + void benchmarkEnded(BenchmarkStats<> const& stats) override; + void benchmarkFailed(std::string const& error) override; #endif // CATCH_CONFIG_ENABLE_BENCHMARKING - void pushScopedMessage( MessageInfo const& message ) override; - void popScopedMessage( MessageInfo const& message ) override; + void pushScopedMessage(MessageInfo const& message) override; + void popScopedMessage(MessageInfo const& message) override; - void emplaceUnscopedMessage( MessageBuilder const& builder ) override; + void emplaceUnscopedMessage(MessageBuilder const& builder) override; std::string getCurrentTestName() const override; @@ -8120,7 +9305,7 @@ void exceptionEarlyReported() override; - void handleFatalErrorCondition( StringRef message ) override; + void handleFatalErrorCondition(StringRef message) override; bool lastAssertionPassed() override; @@ -8131,24 +9316,22 @@ bool aborting() const final; private: - - void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr ); + void runCurrentTest(std::string& redirectedCout, + std::string& redirectedCerr); void invokeActiveTestCase(); void resetAssertionInfo(); - bool testForMissingAssertions( Counts& assertions ); + bool testForMissingAssertions(Counts& assertions); - void assertionEnded( AssertionResult const& result ); - void reportExpr - ( AssertionInfo const &info, - ResultWas::OfType resultType, - ITransientExpression const *expr, - bool negated ); + void assertionEnded(AssertionResult const& result); + void reportExpr(AssertionInfo const& info, + ResultWas::OfType resultType, + ITransientExpression const* expr, + bool negated); - void populateReaction( AssertionReaction& reaction ); + void populateReaction(AssertionReaction& reaction); private: - void handleUnfinishedSections(); TestRunInfo m_runInfo; @@ -8161,7 +9344,8 @@ Totals m_totals; IStreamingReporterPtr m_reporter; std::vector<MessageInfo> m_messages; - std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */ + std::vector<ScopedMessage> + m_messageScopes; /* Keeps owners of so-called unscoped messages. */ AssertionInfo m_lastAssertionInfo; std::vector<SectionEndInfo> m_unfinishedSections; std::vector<ITracker*> m_activeSections; @@ -8180,52 +9364,55 @@ namespace Catch { namespace { - auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& { - expr.streamReconstructedExpression( os ); + auto operator<<(std::ostream& os, ITransientExpression const& expr) + -> std::ostream& { + expr.streamReconstructedExpression(os); return os; } - } + } // namespace - LazyExpression::LazyExpression( bool isNegated ) - : m_isNegated( isNegated ) - {} + LazyExpression::LazyExpression(bool isNegated) : m_isNegated(isNegated) {} - LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {} + LazyExpression::LazyExpression(LazyExpression const& other) : + m_isNegated(other.m_isNegated) {} LazyExpression::operator bool() const { return m_transientExpression != nullptr; } - auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& { - if( lazyExpr.m_isNegated ) + auto operator<<(std::ostream& os, LazyExpression const& lazyExpr) + -> std::ostream& { + if (lazyExpr.m_isNegated) os << "!"; - if( lazyExpr ) { - if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() ) + if (lazyExpr) { + if (lazyExpr.m_isNegated && + lazyExpr.m_transientExpression->isBinaryExpression()) os << "(" << *lazyExpr.m_transientExpression << ")"; else os << *lazyExpr.m_transientExpression; - } - else { + } else { os << "{** error - unchecked empty expression requested **}"; } return os; } - AssertionHandler::AssertionHandler - ( StringRef const& macroName, - SourceLineInfo const& lineInfo, - StringRef capturedExpression, - ResultDisposition::Flags resultDisposition ) - : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition }, - m_resultCapture( getResultCapture() ) - {} + AssertionHandler::AssertionHandler( + StringRef const& macroName, + SourceLineInfo const& lineInfo, + StringRef capturedExpression, + ResultDisposition::Flags resultDisposition) : + m_assertionInfo{ + macroName, lineInfo, capturedExpression, resultDisposition}, + m_resultCapture(getResultCapture()) {} - void AssertionHandler::handleExpr( ITransientExpression const& expr ) { - m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction ); + void AssertionHandler::handleExpr(ITransientExpression const& expr) { + m_resultCapture.handleExpr(m_assertionInfo, expr, m_reaction); } - void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) { - m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction ); + void AssertionHandler::handleMessage(ResultWas::OfType resultType, + StringRef const& message) { + m_resultCapture.handleMessage( + m_assertionInfo, resultType, message, m_reaction); } auto AssertionHandler::allowThrows() const -> bool { @@ -8234,49 +9421,57 @@ void AssertionHandler::complete() { setCompleted(); - if( m_reaction.shouldDebugBreak ) { + if (m_reaction.shouldDebugBreak) { - // If you find your debugger stopping you here then go one level up on the - // call-stack for the code that caused it (typically a failed assertion) + // If you find your debugger stopping you here then go one level up + // on the call-stack for the code that caused it (typically a failed + // assertion) - // (To go back to the test and change execution, jump over the throw, next) + // (To go back to the test and change execution, jump over the + // throw, next) CATCH_BREAK_INTO_DEBUGGER(); } if (m_reaction.shouldThrow) { #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) throw Catch::TestFailureException(); #else - CATCH_ERROR( "Test failure requires aborting test!" ); + CATCH_ERROR("Test failure requires aborting test!"); #endif } } - void AssertionHandler::setCompleted() { - m_completed = true; - } + void AssertionHandler::setCompleted() { m_completed = true; } void AssertionHandler::handleUnexpectedInflightException() { - m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction ); + m_resultCapture.handleUnexpectedInflightException( + m_assertionInfo, Catch::translateActiveException(), m_reaction); } void AssertionHandler::handleExceptionThrownAsExpected() { - m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction); + m_resultCapture.handleNonExpr( + m_assertionInfo, ResultWas::Ok, m_reaction); } void AssertionHandler::handleExceptionNotThrownAsExpected() { - m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction); + m_resultCapture.handleNonExpr( + m_assertionInfo, ResultWas::Ok, m_reaction); } void AssertionHandler::handleUnexpectedExceptionNotThrown() { - m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction ); + m_resultCapture.handleUnexpectedExceptionNotThrown(m_assertionInfo, + m_reaction); } void AssertionHandler::handleThrowingCallSkipped() { - m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction); + m_resultCapture.handleNonExpr( + m_assertionInfo, ResultWas::Ok, m_reaction); } - // This is the overload that takes a string and infers the Equals matcher from it - // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp - void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) { - handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString ); + // This is the overload that takes a string and infers the Equals matcher + // from it The more general overload, that takes any string matcher, is in + // catch_capture_matchers.cpp + void handleExceptionMatchExpr(AssertionHandler& handler, + std::string const& str, + StringRef const& matcherString) { + handleExceptionMatchExpr(handler, Matchers::Equals(str), matcherString); } } // namespace Catch @@ -8284,14 +9479,14 @@ // start catch_assertionresult.cpp namespace Catch { - AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression): - lazyExpression(_lazyExpression), - resultType(_resultType) {} + AssertionResultData::AssertionResultData( + ResultWas::OfType _resultType, LazyExpression const& _lazyExpression) : + lazyExpression(_lazyExpression), resultType(_resultType) {} std::string AssertionResultData::reconstructExpression() const { - if( reconstructedExpression.empty() ) { - if( lazyExpression ) { + if (reconstructedExpression.empty()) { + if (lazyExpression) { ReusableStringStream rss; rss << lazyExpression; reconstructedExpression = rss.str(); @@ -8300,19 +9495,19 @@ return reconstructedExpression; } - AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data ) - : m_info( info ), - m_resultData( data ) - {} + AssertionResult::AssertionResult(AssertionInfo const& info, + AssertionResultData const& data) : + m_info(info), m_resultData(data) {} // Result was a success bool AssertionResult::succeeded() const { - return Catch::isOk( m_resultData.resultType ); + return Catch::isOk(m_resultData.resultType); } // Result was a success, or failure is suppressed bool AssertionResult::isOk() const { - return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition ); + return Catch::isOk(m_resultData.resultType) || + shouldSuppressFailure(m_info.resultDisposition); } ResultWas::OfType AssertionResult::getResultType() const { @@ -8329,7 +9524,8 @@ std::string AssertionResult::getExpression() const { // Possibly overallocating by 3 characters should be basically free - std::string expr; expr.reserve(m_info.capturedExpression.size() + 3); + std::string expr; + expr.reserve(m_info.capturedExpression.size() + 3); if (isFalseTest(m_info.resultDisposition)) { expr += "!("; } @@ -8342,10 +9538,11 @@ std::string AssertionResult::getExpressionInMacro() const { std::string expr; - if( m_info.macroName.empty() ) + if (m_info.macroName.empty()) expr = static_cast<std::string>(m_info.capturedExpression); else { - expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 ); + expr.reserve(m_info.macroName.size() + + m_info.capturedExpression.size() + 4); expr += m_info.macroName; expr += "( "; expr += m_info.capturedExpression; @@ -8360,9 +9557,7 @@ std::string AssertionResult::getExpandedExpression() const { std::string expr = m_resultData.reconstructExpression(); - return expr.empty() - ? getExpression() - : expr; + return expr.empty() ? getExpression() : expr; } std::string AssertionResult::getMessage() const { @@ -8385,12 +9580,16 @@ using StringMatcher = Matchers::Impl::MatcherBase<std::string>; // This is the general overload that takes a any string matcher - // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers - // the Equals matcher (so the header does not mention matchers) - void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) { + // There is another overload, in catch_assertionhandler.h/.cpp, that only + // takes a string and infers the Equals matcher (so the header does not + // mention matchers) + void handleExceptionMatchExpr(AssertionHandler& handler, + StringMatcher const& matcher, + StringRef const& matcherString) { std::string exceptionMessage = Catch::translateActiveException(); - MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString ); - handler.handleExpr( expr ); + MatchExpr<std::string, StringMatcher const&> expr( + exceptionMessage, matcher, matcherString); + handler.handleExpr(expr); } } // namespace Catch @@ -8401,12 +9600,14 @@ // start catch_clara.h -// Use Catch's value for console width (store Clara's off to the side, if present) +// Use Catch's value for console width (store Clara's off to the side, if +// present) #ifdef CLARA_CONFIG_CONSOLE_WIDTH -#define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH +#define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH \ + CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH #endif -#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1 +#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH - 1 #ifdef __clang__ #pragma clang diagnostic push @@ -8425,13 +9626,13 @@ // Clara v1.1.5 - #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80 #endif #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH -#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH +#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH \ + CATCH_CLARA_CONFIG_CONSOLE_WIDTH #endif #ifndef CLARA_CONFIG_OPTIONAL_TYPE @@ -8454,7 +9655,6 @@ // // This project is hosted at https://github.com/philsquared/textflowcpp - #include <cassert> #include <ostream> #include <sstream> @@ -8465,321 +9665,337 @@ #endif namespace Catch { -namespace clara { -namespace TextFlow { + namespace clara { + namespace TextFlow { -inline auto isWhitespace(char c) -> bool { - static std::string chars = " \t\n\r"; - return chars.find(c) != std::string::npos; -} -inline auto isBreakableBefore(char c) -> bool { - static std::string chars = "[({<|"; - return chars.find(c) != std::string::npos; -} -inline auto isBreakableAfter(char c) -> bool { - static std::string chars = "])}>.,:;*+-=&/\\"; - return chars.find(c) != std::string::npos; -} + inline auto isWhitespace(char c) -> bool { + static std::string chars = " \t\n\r"; + return chars.find(c) != std::string::npos; + } + inline auto isBreakableBefore(char c) -> bool { + static std::string chars = "[({<|"; + return chars.find(c) != std::string::npos; + } + inline auto isBreakableAfter(char c) -> bool { + static std::string chars = "])}>.,:;*+-=&/\\"; + return chars.find(c) != std::string::npos; + } -class Columns; + class Columns; -class Column { - std::vector<std::string> m_strings; - size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH; - size_t m_indent = 0; - size_t m_initialIndent = std::string::npos; + class Column { + std::vector<std::string> m_strings; + size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH; + size_t m_indent = 0; + size_t m_initialIndent = std::string::npos; -public: - class iterator { - friend Column; + public: + class iterator { + friend Column; - Column const& m_column; - size_t m_stringIndex = 0; - size_t m_pos = 0; + Column const& m_column; + size_t m_stringIndex = 0; + size_t m_pos = 0; - size_t m_len = 0; - size_t m_end = 0; - bool m_suffix = false; + size_t m_len = 0; + size_t m_end = 0; + bool m_suffix = false; - iterator(Column const& column, size_t stringIndex) - : m_column(column), - m_stringIndex(stringIndex) {} + iterator(Column const& column, size_t stringIndex) : + m_column(column), m_stringIndex(stringIndex) {} - auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; } + auto line() const -> std::string const& { + return m_column.m_strings[m_stringIndex]; + } - auto isBoundary(size_t at) const -> bool { - assert(at > 0); - assert(at <= line().size()); + auto isBoundary(size_t at) const -> bool { + assert(at > 0); + assert(at <= line().size()); - return at == line().size() || - (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) || - isBreakableBefore(line()[at]) || - isBreakableAfter(line()[at - 1]); - } + return at == line().size() || + (isWhitespace(line()[at]) && + !isWhitespace(line()[at - 1])) || + isBreakableBefore(line()[at]) || + isBreakableAfter(line()[at - 1]); + } - void calcLength() { - assert(m_stringIndex < m_column.m_strings.size()); + void calcLength() { + assert(m_stringIndex < m_column.m_strings.size()); - m_suffix = false; - auto width = m_column.m_width - indent(); - m_end = m_pos; - if (line()[m_pos] == '\n') { - ++m_end; - } - while (m_end < line().size() && line()[m_end] != '\n') - ++m_end; + m_suffix = false; + auto width = m_column.m_width - indent(); + m_end = m_pos; + if (line()[m_pos] == '\n') { + ++m_end; + } + while (m_end < line().size() && line()[m_end] != '\n') + ++m_end; - if (m_end < m_pos + width) { - m_len = m_end - m_pos; - } else { - size_t len = width; - while (len > 0 && !isBoundary(m_pos + len)) - --len; - while (len > 0 && isWhitespace(line()[m_pos + len - 1])) - --len; + if (m_end < m_pos + width) { + m_len = m_end - m_pos; + } else { + size_t len = width; + while (len > 0 && !isBoundary(m_pos + len)) + --len; + while (len > 0 && + isWhitespace(line()[m_pos + len - 1])) + --len; - if (len > 0) { - m_len = len; - } else { - m_suffix = true; - m_len = width - 1; - } - } - } + if (len > 0) { + m_len = len; + } else { + m_suffix = true; + m_len = width - 1; + } + } + } - auto indent() const -> size_t { - auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos; - return initial == std::string::npos ? m_column.m_indent : initial; - } + auto indent() const -> size_t { + auto initial = m_pos == 0 && m_stringIndex == 0 + ? m_column.m_initialIndent + : std::string::npos; + return initial == std::string::npos ? m_column.m_indent + : initial; + } - auto addIndentAndSuffix(std::string const &plain) const -> std::string { - return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain); - } + auto addIndentAndSuffix(std::string const& plain) const + -> std::string { + return std::string(indent(), ' ') + + (m_suffix ? plain + "-" : plain); + } - public: - using difference_type = std::ptrdiff_t; - using value_type = std::string; - using pointer = value_type * ; - using reference = value_type & ; - using iterator_category = std::forward_iterator_tag; + public: + using difference_type = std::ptrdiff_t; + using value_type = std::string; + using pointer = value_type*; + using reference = value_type&; + using iterator_category = std::forward_iterator_tag; - explicit iterator(Column const& column) : m_column(column) { - assert(m_column.m_width > m_column.m_indent); - assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent); - calcLength(); - if (m_len == 0) - m_stringIndex++; // Empty string - } + explicit iterator(Column const& column) : m_column(column) { + assert(m_column.m_width > m_column.m_indent); + assert(m_column.m_initialIndent == std::string::npos || + m_column.m_width > m_column.m_initialIndent); + calcLength(); + if (m_len == 0) + m_stringIndex++; // Empty string + } - auto operator *() const -> std::string { - assert(m_stringIndex < m_column.m_strings.size()); - assert(m_pos <= m_end); - return addIndentAndSuffix(line().substr(m_pos, m_len)); - } + auto operator*() const -> std::string { + assert(m_stringIndex < m_column.m_strings.size()); + assert(m_pos <= m_end); + return addIndentAndSuffix(line().substr(m_pos, m_len)); + } - auto operator ++() -> iterator& { - m_pos += m_len; - if (m_pos < line().size() && line()[m_pos] == '\n') - m_pos += 1; - else - while (m_pos < line().size() && isWhitespace(line()[m_pos])) - ++m_pos; + auto operator++() -> iterator& { + m_pos += m_len; + if (m_pos < line().size() && line()[m_pos] == '\n') + m_pos += 1; + else + while (m_pos < line().size() && + isWhitespace(line()[m_pos])) + ++m_pos; - if (m_pos == line().size()) { - m_pos = 0; - ++m_stringIndex; - } - if (m_stringIndex < m_column.m_strings.size()) - calcLength(); - return *this; - } - auto operator ++(int) -> iterator { - iterator prev(*this); - operator++(); - return prev; - } + if (m_pos == line().size()) { + m_pos = 0; + ++m_stringIndex; + } + if (m_stringIndex < m_column.m_strings.size()) + calcLength(); + return *this; + } + auto operator++(int) -> iterator { + iterator prev(*this); + operator++(); + return prev; + } - auto operator ==(iterator const& other) const -> bool { - return - m_pos == other.m_pos && - m_stringIndex == other.m_stringIndex && - &m_column == &other.m_column; - } - auto operator !=(iterator const& other) const -> bool { - return !operator==(other); - } - }; - using const_iterator = iterator; + auto operator==(iterator const& other) const -> bool { + return m_pos == other.m_pos && + m_stringIndex == other.m_stringIndex && + &m_column == &other.m_column; + } + auto operator!=(iterator const& other) const -> bool { + return !operator==(other); + } + }; + using const_iterator = iterator; - explicit Column(std::string const& text) { m_strings.push_back(text); } + explicit Column(std::string const& text) { + m_strings.push_back(text); + } - auto width(size_t newWidth) -> Column& { - assert(newWidth > 0); - m_width = newWidth; - return *this; - } - auto indent(size_t newIndent) -> Column& { - m_indent = newIndent; - return *this; - } - auto initialIndent(size_t newIndent) -> Column& { - m_initialIndent = newIndent; - return *this; - } + auto width(size_t newWidth) -> Column& { + assert(newWidth > 0); + m_width = newWidth; + return *this; + } + auto indent(size_t newIndent) -> Column& { + m_indent = newIndent; + return *this; + } + auto initialIndent(size_t newIndent) -> Column& { + m_initialIndent = newIndent; + return *this; + } - auto width() const -> size_t { return m_width; } - auto begin() const -> iterator { return iterator(*this); } - auto end() const -> iterator { return { *this, m_strings.size() }; } + auto width() const -> size_t { return m_width; } + auto begin() const -> iterator { return iterator(*this); } + auto end() const -> iterator { + return {*this, m_strings.size()}; + } - inline friend std::ostream& operator << (std::ostream& os, Column const& col) { - bool first = true; - for (auto line : col) { - if (first) - first = false; - else - os << "\n"; - os << line; - } - return os; - } + inline friend std::ostream& operator<<(std::ostream& os, + Column const& col) { + bool first = true; + for (auto line : col) { + if (first) + first = false; + else + os << "\n"; + os << line; + } + return os; + } - auto operator + (Column const& other)->Columns; + auto operator+(Column const& other) -> Columns; - auto toString() const -> std::string { - std::ostringstream oss; - oss << *this; - return oss.str(); - } -}; + auto toString() const -> std::string { + std::ostringstream oss; + oss << *this; + return oss.str(); + } + }; -class Spacer : public Column { + class Spacer : public Column { -public: - explicit Spacer(size_t spaceWidth) : Column("") { - width(spaceWidth); - } -}; + public: + explicit Spacer(size_t spaceWidth) : Column("") { + width(spaceWidth); + } + }; -class Columns { - std::vector<Column> m_columns; + class Columns { + std::vector<Column> m_columns; -public: + public: + class iterator { + friend Columns; + struct EndTag {}; - class iterator { - friend Columns; - struct EndTag {}; + std::vector<Column> const& m_columns; + std::vector<Column::iterator> m_iterators; + size_t m_activeIterators; - std::vector<Column> const& m_columns; - std::vector<Column::iterator> m_iterators; - size_t m_activeIterators; + iterator(Columns const& columns, EndTag) : + m_columns(columns.m_columns), m_activeIterators(0) { + m_iterators.reserve(m_columns.size()); - iterator(Columns const& columns, EndTag) - : m_columns(columns.m_columns), - m_activeIterators(0) { - m_iterators.reserve(m_columns.size()); + for (auto const& col : m_columns) + m_iterators.push_back(col.end()); + } - for (auto const& col : m_columns) - m_iterators.push_back(col.end()); - } + public: + using difference_type = std::ptrdiff_t; + using value_type = std::string; + using pointer = value_type*; + using reference = value_type&; + using iterator_category = std::forward_iterator_tag; - public: - using difference_type = std::ptrdiff_t; - using value_type = std::string; - using pointer = value_type * ; - using reference = value_type & ; - using iterator_category = std::forward_iterator_tag; + explicit iterator(Columns const& columns) : + m_columns(columns.m_columns), + m_activeIterators(m_columns.size()) { + m_iterators.reserve(m_columns.size()); - explicit iterator(Columns const& columns) - : m_columns(columns.m_columns), - m_activeIterators(m_columns.size()) { - m_iterators.reserve(m_columns.size()); + for (auto const& col : m_columns) + m_iterators.push_back(col.begin()); + } - for (auto const& col : m_columns) - m_iterators.push_back(col.begin()); - } + auto operator==(iterator const& other) const -> bool { + return m_iterators == other.m_iterators; + } + auto operator!=(iterator const& other) const -> bool { + return m_iterators != other.m_iterators; + } + auto operator*() const -> std::string { + std::string row, padding; - auto operator ==(iterator const& other) const -> bool { - return m_iterators == other.m_iterators; - } - auto operator !=(iterator const& other) const -> bool { - return m_iterators != other.m_iterators; - } - auto operator *() const -> std::string { - std::string row, padding; + for (size_t i = 0; i < m_columns.size(); ++i) { + auto width = m_columns[i].width(); + if (m_iterators[i] != m_columns[i].end()) { + std::string col = *m_iterators[i]; + row += padding + col; + if (col.size() < width) + padding = + std::string(width - col.size(), ' '); + else + padding = ""; + } else { + padding += std::string(width, ' '); + } + } + return row; + } + auto operator++() -> iterator& { + for (size_t i = 0; i < m_columns.size(); ++i) { + if (m_iterators[i] != m_columns[i].end()) + ++m_iterators[i]; + } + return *this; + } + auto operator++(int) -> iterator { + iterator prev(*this); + operator++(); + return prev; + } + }; + using const_iterator = iterator; - for (size_t i = 0; i < m_columns.size(); ++i) { - auto width = m_columns[i].width(); - if (m_iterators[i] != m_columns[i].end()) { - std::string col = *m_iterators[i]; - row += padding + col; - if (col.size() < width) - padding = std::string(width - col.size(), ' '); - else - padding = ""; - } else { - padding += std::string(width, ' '); - } - } - return row; - } - auto operator ++() -> iterator& { - for (size_t i = 0; i < m_columns.size(); ++i) { - if (m_iterators[i] != m_columns[i].end()) - ++m_iterators[i]; - } - return *this; - } - auto operator ++(int) -> iterator { - iterator prev(*this); - operator++(); - return prev; - } - }; - using const_iterator = iterator; + auto begin() const -> iterator { return iterator(*this); } + auto end() const -> iterator { + return {*this, iterator::EndTag()}; + } - auto begin() const -> iterator { return iterator(*this); } - auto end() const -> iterator { return { *this, iterator::EndTag() }; } + auto operator+=(Column const& col) -> Columns& { + m_columns.push_back(col); + return *this; + } + auto operator+(Column const& col) -> Columns { + Columns combined = *this; + combined += col; + return combined; + } - auto operator += (Column const& col) -> Columns& { - m_columns.push_back(col); - return *this; - } - auto operator + (Column const& col) -> Columns { - Columns combined = *this; - combined += col; - return combined; - } + inline friend std::ostream& operator<<(std::ostream& os, + Columns const& cols) { - inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) { + bool first = true; + for (auto line : cols) { + if (first) + first = false; + else + os << "\n"; + os << line; + } + return os; + } - bool first = true; - for (auto line : cols) { - if (first) - first = false; - else - os << "\n"; - os << line; - } - return os; - } + auto toString() const -> std::string { + std::ostringstream oss; + oss << *this; + return oss.str(); + } + }; - auto toString() const -> std::string { - std::ostringstream oss; - oss << *this; - return oss.str(); - } -}; + inline auto Column::operator+(Column const& other) -> Columns { + Columns cols; + cols += *this; + cols += other; + return cols; + } + } // namespace TextFlow -inline auto Column::operator + (Column const& other) -> Columns { - Columns cols; - cols += *this; - cols += other; - return cols; -} -} - -} -} + } // namespace clara +} // namespace Catch // ----------- end of #include from clara_textflow.hpp ----------- // ........... back in clara.hpp @@ -8790,885 +10006,997 @@ #include <set> #include <algorithm> -#if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) ) +#if !defined(CATCH_PLATFORM_WINDOWS) && \ + (defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || \ + defined(_MSC_VER)) #define CATCH_PLATFORM_WINDOWS #endif -namespace Catch { namespace clara { -namespace detail { +namespace Catch { + namespace clara { + namespace detail { - // Traits for extracting arg and return type of lambdas (for single argument lambdas) - template<typename L> - struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {}; + // Traits for extracting arg and return type of lambdas (for single + // argument lambdas) + template <typename L> + struct UnaryLambdaTraits + : UnaryLambdaTraits<decltype(&L::operator())> {}; - template<typename ClassT, typename ReturnT, typename... Args> - struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> { - static const bool isValid = false; - }; + template <typename ClassT, typename ReturnT, typename... Args> + struct UnaryLambdaTraits<ReturnT (ClassT::*)(Args...) const> { + static const bool isValid = false; + }; - template<typename ClassT, typename ReturnT, typename ArgT> - struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> { - static const bool isValid = true; - using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type; - using ReturnType = ReturnT; - }; + template <typename ClassT, typename ReturnT, typename ArgT> + struct UnaryLambdaTraits<ReturnT (ClassT::*)(ArgT) const> { + static const bool isValid = true; + using ArgType = typename std::remove_const< + typename std::remove_reference<ArgT>::type>::type; + using ReturnType = ReturnT; + }; - class TokenStream; + class TokenStream; - // Transport for raw args (copied from main args, or supplied via init list for testing) - class Args { - friend TokenStream; - std::string m_exeName; - std::vector<std::string> m_args; + // Transport for raw args (copied from main args, or supplied via + // init list for testing) + class Args { + friend TokenStream; + std::string m_exeName; + std::vector<std::string> m_args; - public: - Args( int argc, char const* const* argv ) - : m_exeName(argv[0]), - m_args(argv + 1, argv + argc) {} + public: + Args(int argc, char const* const* argv) : + m_exeName(argv[0]), m_args(argv + 1, argv + argc) {} - Args( std::initializer_list<std::string> args ) - : m_exeName( *args.begin() ), - m_args( args.begin()+1, args.end() ) - {} + Args(std::initializer_list<std::string> args) : + m_exeName(*args.begin()), + m_args(args.begin() + 1, args.end()) {} - auto exeName() const -> std::string { - return m_exeName; - } - }; + auto exeName() const -> std::string { return m_exeName; } + }; - // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string - // may encode an option + its argument if the : or = form is used - enum class TokenType { - Option, Argument - }; - struct Token { - TokenType type; - std::string token; - }; + // Wraps a token coming from a token stream. These may not directly + // correspond to strings as a single string may encode an option + + // its argument if the : or = form is used + enum class TokenType { Option, Argument }; + struct Token { + TokenType type; + std::string token; + }; - inline auto isOptPrefix( char c ) -> bool { - return c == '-' + inline auto isOptPrefix(char c) -> bool { + return c == '-' #ifdef CATCH_PLATFORM_WINDOWS - || c == '/' + || c == '/' #endif - ; - } + ; + } - // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled - class TokenStream { - using Iterator = std::vector<std::string>::const_iterator; - Iterator it; - Iterator itEnd; - std::vector<Token> m_tokenBuffer; + // Abstracts iterators into args as a stream of tokens, with option + // arguments uniformly handled + class TokenStream { + using Iterator = std::vector<std::string>::const_iterator; + Iterator it; + Iterator itEnd; + std::vector<Token> m_tokenBuffer; - void loadBuffer() { - m_tokenBuffer.resize( 0 ); + void loadBuffer() { + m_tokenBuffer.resize(0); - // Skip any empty strings - while( it != itEnd && it->empty() ) - ++it; + // Skip any empty strings + while (it != itEnd && it->empty()) + ++it; - if( it != itEnd ) { - auto const &next = *it; - if( isOptPrefix( next[0] ) ) { - auto delimiterPos = next.find_first_of( " :=" ); - if( delimiterPos != std::string::npos ) { - m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } ); - m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } ); - } else { - if( next[1] != '-' && next.size() > 2 ) { - std::string opt = "- "; - for( size_t i = 1; i < next.size(); ++i ) { - opt[1] = next[i]; - m_tokenBuffer.push_back( { TokenType::Option, opt } ); + if (it != itEnd) { + auto const& next = *it; + if (isOptPrefix(next[0])) { + auto delimiterPos = next.find_first_of(" :="); + if (delimiterPos != std::string::npos) { + m_tokenBuffer.push_back( + {TokenType::Option, + next.substr(0, delimiterPos)}); + m_tokenBuffer.push_back( + {TokenType::Argument, + next.substr(delimiterPos + 1)}); + } else { + if (next[1] != '-' && next.size() > 2) { + std::string opt = "- "; + for (size_t i = 1; i < next.size(); ++i) { + opt[1] = next[i]; + m_tokenBuffer.push_back( + {TokenType::Option, opt}); + } + } else { + m_tokenBuffer.push_back( + {TokenType::Option, next}); + } } } else { - m_tokenBuffer.push_back( { TokenType::Option, next } ); + m_tokenBuffer.push_back( + {TokenType::Argument, next}); } } - } else { - m_tokenBuffer.push_back( { TokenType::Argument, next } ); } + + public: + explicit TokenStream(Args const& args) : + TokenStream(args.m_args.begin(), args.m_args.end()) {} + + TokenStream(Iterator it, Iterator itEnd) : + it(it), itEnd(itEnd) { + loadBuffer(); + } + + explicit operator bool() const { + return !m_tokenBuffer.empty() || it != itEnd; + } + + auto count() const -> size_t { + return m_tokenBuffer.size() + (itEnd - it); + } + + auto operator*() const -> Token { + assert(!m_tokenBuffer.empty()); + return m_tokenBuffer.front(); + } + + auto operator->() const -> Token const* { + assert(!m_tokenBuffer.empty()); + return &m_tokenBuffer.front(); + } + + auto operator++() -> TokenStream& { + if (m_tokenBuffer.size() >= 2) { + m_tokenBuffer.erase(m_tokenBuffer.begin()); + } else { + if (it != itEnd) + ++it; + loadBuffer(); + } + return *this; + } + }; + + class ResultBase { + public: + enum Type { Ok, LogicError, RuntimeError }; + + protected: + ResultBase(Type type) : m_type(type) {} + virtual ~ResultBase() = default; + + virtual void enforceOk() const = 0; + + Type m_type; + }; + + template <typename T> class ResultValueBase : public ResultBase { + public: + auto value() const -> T const& { + enforceOk(); + return m_value; + } + + protected: + ResultValueBase(Type type) : ResultBase(type) {} + + ResultValueBase(ResultValueBase const& other) : + ResultBase(other) { + if (m_type == ResultBase::Ok) + new (&m_value) T(other.m_value); + } + + ResultValueBase(Type, T const& value) : ResultBase(Ok) { + new (&m_value) T(value); + } + + auto operator=(ResultValueBase const& other) + -> ResultValueBase& { + if (m_type == ResultBase::Ok) + m_value.~T(); + ResultBase::operator=(other); + if (m_type == ResultBase::Ok) + new (&m_value) T(other.m_value); + return *this; + } + + ~ResultValueBase() override { + if (m_type == Ok) + m_value.~T(); + } + + union { + T m_value; + }; + }; + + template <> class ResultValueBase<void> : public ResultBase { + protected: + using ResultBase::ResultBase; + }; + + template <typename T = void> + class BasicResult : public ResultValueBase<T> { + public: + template <typename U> + explicit BasicResult(BasicResult<U> const& other) : + ResultValueBase<T>(other.type()), + m_errorMessage(other.errorMessage()) { + assert(type() != ResultBase::Ok); + } + + template <typename U> + static auto ok(U const& value) -> BasicResult { + return {ResultBase::Ok, value}; + } + static auto ok() -> BasicResult { return {ResultBase::Ok}; } + static auto logicError(std::string const& message) + -> BasicResult { + return {ResultBase::LogicError, message}; + } + static auto runtimeError(std::string const& message) + -> BasicResult { + return {ResultBase::RuntimeError, message}; + } + + explicit operator bool() const { + return m_type == ResultBase::Ok; + } + auto type() const -> ResultBase::Type { return m_type; } + auto errorMessage() const -> std::string { + return m_errorMessage; + } + + protected: + void enforceOk() const override { + + // Errors shouldn't reach this point, but if they do + // the actual error message will be in m_errorMessage + assert(m_type != ResultBase::LogicError); + assert(m_type != ResultBase::RuntimeError); + if (m_type != ResultBase::Ok) + std::abort(); + } + + std::string + m_errorMessage; // Only populated if resultType is an error + + BasicResult(ResultBase::Type type, std::string const& message) : + ResultValueBase<T>(type), m_errorMessage(message) { + assert(m_type != ResultBase::Ok); + } + + using ResultValueBase<T>::ResultValueBase; + using ResultBase::m_type; + }; + + enum class ParseResultType { + Matched, + NoMatch, + ShortCircuitAll, + ShortCircuitSame + }; + + class ParseState { + public: + ParseState(ParseResultType type, + TokenStream const& remainingTokens) : + m_type(type), m_remainingTokens(remainingTokens) {} + + auto type() const -> ParseResultType { return m_type; } + auto remainingTokens() const -> TokenStream { + return m_remainingTokens; + } + + private: + ParseResultType m_type; + TokenStream m_remainingTokens; + }; + + using Result = BasicResult<void>; + using ParserResult = BasicResult<ParseResultType>; + using InternalParseResult = BasicResult<ParseState>; + + struct HelpColumns { + std::string left; + std::string right; + }; + + template <typename T> + inline auto convertInto(std::string const& source, T& target) + -> ParserResult { + std::stringstream ss; + ss << source; + ss >> target; + if (ss.fail()) + return ParserResult::runtimeError("Unable to convert '" + + source + + "' to destination type"); + else + return ParserResult::ok(ParseResultType::Matched); } - } - - public: - explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {} - - TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) { - loadBuffer(); - } - - explicit operator bool() const { - return !m_tokenBuffer.empty() || it != itEnd; - } - - auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); } - - auto operator*() const -> Token { - assert( !m_tokenBuffer.empty() ); - return m_tokenBuffer.front(); - } - - auto operator->() const -> Token const * { - assert( !m_tokenBuffer.empty() ); - return &m_tokenBuffer.front(); - } - - auto operator++() -> TokenStream & { - if( m_tokenBuffer.size() >= 2 ) { - m_tokenBuffer.erase( m_tokenBuffer.begin() ); - } else { - if( it != itEnd ) - ++it; - loadBuffer(); + inline auto convertInto(std::string const& source, + std::string& target) -> ParserResult { + target = source; + return ParserResult::ok(ParseResultType::Matched); } - return *this; - } - }; - - class ResultBase { - public: - enum Type { - Ok, LogicError, RuntimeError - }; - - protected: - ResultBase( Type type ) : m_type( type ) {} - virtual ~ResultBase() = default; - - virtual void enforceOk() const = 0; - - Type m_type; - }; - - template<typename T> - class ResultValueBase : public ResultBase { - public: - auto value() const -> T const & { - enforceOk(); - return m_value; - } - - protected: - ResultValueBase( Type type ) : ResultBase( type ) {} - - ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) { - if( m_type == ResultBase::Ok ) - new( &m_value ) T( other.m_value ); - } - - ResultValueBase( Type, T const &value ) : ResultBase( Ok ) { - new( &m_value ) T( value ); - } - - auto operator=( ResultValueBase const &other ) -> ResultValueBase & { - if( m_type == ResultBase::Ok ) - m_value.~T(); - ResultBase::operator=(other); - if( m_type == ResultBase::Ok ) - new( &m_value ) T( other.m_value ); - return *this; - } - - ~ResultValueBase() override { - if( m_type == Ok ) - m_value.~T(); - } - - union { - T m_value; - }; - }; - - template<> - class ResultValueBase<void> : public ResultBase { - protected: - using ResultBase::ResultBase; - }; - - template<typename T = void> - class BasicResult : public ResultValueBase<T> { - public: - template<typename U> - explicit BasicResult( BasicResult<U> const &other ) - : ResultValueBase<T>( other.type() ), - m_errorMessage( other.errorMessage() ) - { - assert( type() != ResultBase::Ok ); - } - - template<typename U> - static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; } - static auto ok() -> BasicResult { return { ResultBase::Ok }; } - static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; } - static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; } - - explicit operator bool() const { return m_type == ResultBase::Ok; } - auto type() const -> ResultBase::Type { return m_type; } - auto errorMessage() const -> std::string { return m_errorMessage; } - - protected: - void enforceOk() const override { - - // Errors shouldn't reach this point, but if they do - // the actual error message will be in m_errorMessage - assert( m_type != ResultBase::LogicError ); - assert( m_type != ResultBase::RuntimeError ); - if( m_type != ResultBase::Ok ) - std::abort(); - } - - std::string m_errorMessage; // Only populated if resultType is an error - - BasicResult( ResultBase::Type type, std::string const &message ) - : ResultValueBase<T>(type), - m_errorMessage(message) - { - assert( m_type != ResultBase::Ok ); - } - - using ResultValueBase<T>::ResultValueBase; - using ResultBase::m_type; - }; - - enum class ParseResultType { - Matched, NoMatch, ShortCircuitAll, ShortCircuitSame - }; - - class ParseState { - public: - - ParseState( ParseResultType type, TokenStream const &remainingTokens ) - : m_type(type), - m_remainingTokens( remainingTokens ) - {} - - auto type() const -> ParseResultType { return m_type; } - auto remainingTokens() const -> TokenStream { return m_remainingTokens; } - - private: - ParseResultType m_type; - TokenStream m_remainingTokens; - }; - - using Result = BasicResult<void>; - using ParserResult = BasicResult<ParseResultType>; - using InternalParseResult = BasicResult<ParseState>; - - struct HelpColumns { - std::string left; - std::string right; - }; - - template<typename T> - inline auto convertInto( std::string const &source, T& target ) -> ParserResult { - std::stringstream ss; - ss << source; - ss >> target; - if( ss.fail() ) - return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" ); - else - return ParserResult::ok( ParseResultType::Matched ); - } - inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult { - target = source; - return ParserResult::ok( ParseResultType::Matched ); - } - inline auto convertInto( std::string const &source, bool &target ) -> ParserResult { - std::string srcLC = source; - std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( unsigned char c ) { return static_cast<char>( std::tolower(c) ); } ); - if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on") - target = true; - else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off") - target = false; - else - return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" ); - return ParserResult::ok( ParseResultType::Matched ); - } + inline auto convertInto(std::string const& source, bool& target) + -> ParserResult { + std::string srcLC = source; + std::transform(srcLC.begin(), + srcLC.end(), + srcLC.begin(), + [](unsigned char c) { + return static_cast<char>(std::tolower(c)); + }); + if (srcLC == "y" || srcLC == "1" || srcLC == "true" || + srcLC == "yes" || srcLC == "on") + target = true; + else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || + srcLC == "no" || srcLC == "off") + target = false; + else + return ParserResult::runtimeError( + "Expected a boolean value but did not recognise: '" + + source + "'"); + return ParserResult::ok(ParseResultType::Matched); + } #ifdef CLARA_CONFIG_OPTIONAL_TYPE - template<typename T> - inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult { - T temp; - auto result = convertInto( source, temp ); - if( result ) - target = std::move(temp); - return result; - } + template <typename T> + inline auto convertInto(std::string const& source, + CLARA_CONFIG_OPTIONAL_TYPE<T>& target) + -> ParserResult { + T temp; + auto result = convertInto(source, temp); + if (result) + target = std::move(temp); + return result; + } #endif // CLARA_CONFIG_OPTIONAL_TYPE - struct NonCopyable { - NonCopyable() = default; - NonCopyable( NonCopyable const & ) = delete; - NonCopyable( NonCopyable && ) = delete; - NonCopyable &operator=( NonCopyable const & ) = delete; - NonCopyable &operator=( NonCopyable && ) = delete; - }; - - struct BoundRef : NonCopyable { - virtual ~BoundRef() = default; - virtual auto isContainer() const -> bool { return false; } - virtual auto isFlag() const -> bool { return false; } - }; - struct BoundValueRefBase : BoundRef { - virtual auto setValue( std::string const &arg ) -> ParserResult = 0; - }; - struct BoundFlagRefBase : BoundRef { - virtual auto setFlag( bool flag ) -> ParserResult = 0; - virtual auto isFlag() const -> bool { return true; } - }; - - template<typename T> - struct BoundValueRef : BoundValueRefBase { - T &m_ref; - - explicit BoundValueRef( T &ref ) : m_ref( ref ) {} - - auto setValue( std::string const &arg ) -> ParserResult override { - return convertInto( arg, m_ref ); - } - }; - - template<typename T> - struct BoundValueRef<std::vector<T>> : BoundValueRefBase { - std::vector<T> &m_ref; - - explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {} - - auto isContainer() const -> bool override { return true; } - - auto setValue( std::string const &arg ) -> ParserResult override { - T temp; - auto result = convertInto( arg, temp ); - if( result ) - m_ref.push_back( temp ); - return result; - } - }; - - struct BoundFlagRef : BoundFlagRefBase { - bool &m_ref; - - explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {} - - auto setFlag( bool flag ) -> ParserResult override { - m_ref = flag; - return ParserResult::ok( ParseResultType::Matched ); - } - }; - - template<typename ReturnType> - struct LambdaInvoker { - static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" ); - - template<typename L, typename ArgType> - static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult { - return lambda( arg ); - } - }; - - template<> - struct LambdaInvoker<void> { - template<typename L, typename ArgType> - static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult { - lambda( arg ); - return ParserResult::ok( ParseResultType::Matched ); - } - }; - - template<typename ArgType, typename L> - inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult { - ArgType temp{}; - auto result = convertInto( arg, temp ); - return !result - ? result - : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp ); - } - - template<typename L> - struct BoundLambda : BoundValueRefBase { - L m_lambda; - - static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" ); - explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {} - - auto setValue( std::string const &arg ) -> ParserResult override { - return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg ); - } - }; - - template<typename L> - struct BoundFlagLambda : BoundFlagRefBase { - L m_lambda; - - static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" ); - static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" ); - - explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {} - - auto setFlag( bool flag ) -> ParserResult override { - return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag ); - } - }; - - enum class Optionality { Optional, Required }; - - struct Parser; - - class ParserBase { - public: - virtual ~ParserBase() = default; - virtual auto validate() const -> Result { return Result::ok(); } - virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0; - virtual auto cardinality() const -> size_t { return 1; } - - auto parse( Args const &args ) const -> InternalParseResult { - return parse( args.exeName(), TokenStream( args ) ); - } - }; - - template<typename DerivedT> - class ComposableParserImpl : public ParserBase { - public: - template<typename T> - auto operator|( T const &other ) const -> Parser; - - template<typename T> - auto operator+( T const &other ) const -> Parser; - }; - - // Common code and state for Args and Opts - template<typename DerivedT> - class ParserRefImpl : public ComposableParserImpl<DerivedT> { - protected: - Optionality m_optionality = Optionality::Optional; - std::shared_ptr<BoundRef> m_ref; - std::string m_hint; - std::string m_description; - - explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {} - - public: - template<typename T> - ParserRefImpl( T &ref, std::string const &hint ) - : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ), - m_hint( hint ) - {} - - template<typename LambdaT> - ParserRefImpl( LambdaT const &ref, std::string const &hint ) - : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ), - m_hint(hint) - {} - - auto operator()( std::string const &description ) -> DerivedT & { - m_description = description; - return static_cast<DerivedT &>( *this ); - } - - auto optional() -> DerivedT & { - m_optionality = Optionality::Optional; - return static_cast<DerivedT &>( *this ); - }; - - auto required() -> DerivedT & { - m_optionality = Optionality::Required; - return static_cast<DerivedT &>( *this ); - }; - - auto isOptional() const -> bool { - return m_optionality == Optionality::Optional; - } - - auto cardinality() const -> size_t override { - if( m_ref->isContainer() ) - return 0; - else - return 1; - } - - auto hint() const -> std::string { return m_hint; } - }; - - class ExeName : public ComposableParserImpl<ExeName> { - std::shared_ptr<std::string> m_name; - std::shared_ptr<BoundValueRefBase> m_ref; - - template<typename LambdaT> - static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> { - return std::make_shared<BoundLambda<LambdaT>>( lambda) ; - } - - public: - ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {} - - explicit ExeName( std::string &ref ) : ExeName() { - m_ref = std::make_shared<BoundValueRef<std::string>>( ref ); - } - - template<typename LambdaT> - explicit ExeName( LambdaT const& lambda ) : ExeName() { - m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda ); - } - - // The exe name is not parsed out of the normal tokens, but is handled specially - auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override { - return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) ); - } - - auto name() const -> std::string { return *m_name; } - auto set( std::string const& newName ) -> ParserResult { - - auto lastSlash = newName.find_last_of( "\\/" ); - auto filename = ( lastSlash == std::string::npos ) - ? newName - : newName.substr( lastSlash+1 ); - - *m_name = filename; - if( m_ref ) - return m_ref->setValue( filename ); - else - return ParserResult::ok( ParseResultType::Matched ); - } - }; - - class Arg : public ParserRefImpl<Arg> { - public: - using ParserRefImpl::ParserRefImpl; - - auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override { - auto validationResult = validate(); - if( !validationResult ) - return InternalParseResult( validationResult ); - - auto remainingTokens = tokens; - auto const &token = *remainingTokens; - if( token.type != TokenType::Argument ) - return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) ); - - assert( !m_ref->isFlag() ); - auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() ); - - auto result = valueRef->setValue( remainingTokens->token ); - if( !result ) - return InternalParseResult( result ); - else - return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) ); - } - }; - - inline auto normaliseOpt( std::string const &optName ) -> std::string { -#ifdef CATCH_PLATFORM_WINDOWS - if( optName[0] == '/' ) - return "-" + optName.substr( 1 ); - else -#endif - return optName; - } - - class Opt : public ParserRefImpl<Opt> { - protected: - std::vector<std::string> m_optNames; - - public: - template<typename LambdaT> - explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {} - - explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {} - - template<typename LambdaT> - Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {} - - template<typename T> - Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {} - - auto operator[]( std::string const &optName ) -> Opt & { - m_optNames.push_back( optName ); - return *this; - } - - auto getHelpColumns() const -> std::vector<HelpColumns> { - std::ostringstream oss; - bool first = true; - for( auto const &opt : m_optNames ) { - if (first) - first = false; - else - oss << ", "; - oss << opt; - } - if( !m_hint.empty() ) - oss << " <" << m_hint << ">"; - return { { oss.str(), m_description } }; - } - - auto isMatch( std::string const &optToken ) const -> bool { - auto normalisedToken = normaliseOpt( optToken ); - for( auto const &name : m_optNames ) { - if( normaliseOpt( name ) == normalisedToken ) - return true; - } - return false; - } - - using ParserBase::parse; - - auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override { - auto validationResult = validate(); - if( !validationResult ) - return InternalParseResult( validationResult ); - - auto remainingTokens = tokens; - if( remainingTokens && remainingTokens->type == TokenType::Option ) { - auto const &token = *remainingTokens; - if( isMatch(token.token ) ) { - if( m_ref->isFlag() ) { - auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() ); - auto result = flagRef->setFlag( true ); - if( !result ) - return InternalParseResult( result ); - if( result.value() == ParseResultType::ShortCircuitAll ) - return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) ); - } else { - auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() ); - ++remainingTokens; - if( !remainingTokens ) - return InternalParseResult::runtimeError( "Expected argument following " + token.token ); - auto const &argToken = *remainingTokens; - if( argToken.type != TokenType::Argument ) - return InternalParseResult::runtimeError( "Expected argument following " + token.token ); - auto result = valueRef->setValue( argToken.token ); - if( !result ) - return InternalParseResult( result ); - if( result.value() == ParseResultType::ShortCircuitAll ) - return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) ); - } - return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) ); - } - } - return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) ); - } - - auto validate() const -> Result override { - if( m_optNames.empty() ) - return Result::logicError( "No options supplied to Opt" ); - for( auto const &name : m_optNames ) { - if( name.empty() ) - return Result::logicError( "Option name cannot be empty" ); -#ifdef CATCH_PLATFORM_WINDOWS - if( name[0] != '-' && name[0] != '/' ) - return Result::logicError( "Option name must begin with '-' or '/'" ); -#else - if( name[0] != '-' ) - return Result::logicError( "Option name must begin with '-'" ); -#endif - } - return ParserRefImpl::validate(); - } - }; - - struct Help : Opt { - Help( bool &showHelpFlag ) - : Opt([&]( bool flag ) { - showHelpFlag = flag; - return ParserResult::ok( ParseResultType::ShortCircuitAll ); - }) - { - static_cast<Opt &>( *this ) - ("display usage information") - ["-?"]["-h"]["--help"] - .optional(); - } - }; - - struct Parser : ParserBase { - - mutable ExeName m_exeName; - std::vector<Opt> m_options; - std::vector<Arg> m_args; - - auto operator|=( ExeName const &exeName ) -> Parser & { - m_exeName = exeName; - return *this; - } - - auto operator|=( Arg const &arg ) -> Parser & { - m_args.push_back(arg); - return *this; - } - - auto operator|=( Opt const &opt ) -> Parser & { - m_options.push_back(opt); - return *this; - } - - auto operator|=( Parser const &other ) -> Parser & { - m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end()); - m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end()); - return *this; - } - - template<typename T> - auto operator|( T const &other ) const -> Parser { - return Parser( *this ) |= other; - } - - // Forward deprecated interface with '+' instead of '|' - template<typename T> - auto operator+=( T const &other ) -> Parser & { return operator|=( other ); } - template<typename T> - auto operator+( T const &other ) const -> Parser { return operator|( other ); } - - auto getHelpColumns() const -> std::vector<HelpColumns> { - std::vector<HelpColumns> cols; - for (auto const &o : m_options) { - auto childCols = o.getHelpColumns(); - cols.insert( cols.end(), childCols.begin(), childCols.end() ); - } - return cols; - } - - void writeToStream( std::ostream &os ) const { - if (!m_exeName.name().empty()) { - os << "usage:\n" << " " << m_exeName.name() << " "; - bool required = true, first = true; - for( auto const &arg : m_args ) { - if (first) - first = false; - else - os << " "; - if( arg.isOptional() && required ) { - os << "["; - required = false; - } - os << "<" << arg.hint() << ">"; - if( arg.cardinality() == 0 ) - os << " ... "; - } - if( !required ) - os << "]"; - if( !m_options.empty() ) - os << " options"; - os << "\n\nwhere options are:" << std::endl; - } - - auto rows = getHelpColumns(); - size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH; - size_t optWidth = 0; - for( auto const &cols : rows ) - optWidth = (std::max)(optWidth, cols.left.size() + 2); - - optWidth = (std::min)(optWidth, consoleWidth/2); - - for( auto const &cols : rows ) { - auto row = - TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) + - TextFlow::Spacer(4) + - TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth ); - os << row << std::endl; - } - } - - friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& { - parser.writeToStream( os ); - return os; - } - - auto validate() const -> Result override { - for( auto const &opt : m_options ) { - auto result = opt.validate(); - if( !result ) - return result; - } - for( auto const &arg : m_args ) { - auto result = arg.validate(); - if( !result ) - return result; - } - return Result::ok(); - } - - using ParserBase::parse; - - auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override { - - struct ParserInfo { - ParserBase const* parser = nullptr; - size_t count = 0; + struct NonCopyable { + NonCopyable() = default; + NonCopyable(NonCopyable const&) = delete; + NonCopyable(NonCopyable&&) = delete; + NonCopyable& operator=(NonCopyable const&) = delete; + NonCopyable& operator=(NonCopyable&&) = delete; }; - const size_t totalParsers = m_options.size() + m_args.size(); - assert( totalParsers < 512 ); - // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do - ParserInfo parseInfos[512]; - { - size_t i = 0; - for (auto const &opt : m_options) parseInfos[i++].parser = &opt; - for (auto const &arg : m_args) parseInfos[i++].parser = &arg; + struct BoundRef : NonCopyable { + virtual ~BoundRef() = default; + virtual auto isContainer() const -> bool { return false; } + virtual auto isFlag() const -> bool { return false; } + }; + struct BoundValueRefBase : BoundRef { + virtual auto setValue(std::string const& arg) + -> ParserResult = 0; + }; + struct BoundFlagRefBase : BoundRef { + virtual auto setFlag(bool flag) -> ParserResult = 0; + virtual auto isFlag() const -> bool { return true; } + }; + + template <typename T> struct BoundValueRef : BoundValueRefBase { + T& m_ref; + + explicit BoundValueRef(T& ref) : m_ref(ref) {} + + auto setValue(std::string const& arg) -> ParserResult override { + return convertInto(arg, m_ref); + } + }; + + template <typename T> + struct BoundValueRef<std::vector<T>> : BoundValueRefBase { + std::vector<T>& m_ref; + + explicit BoundValueRef(std::vector<T>& ref) : m_ref(ref) {} + + auto isContainer() const -> bool override { return true; } + + auto setValue(std::string const& arg) -> ParserResult override { + T temp; + auto result = convertInto(arg, temp); + if (result) + m_ref.push_back(temp); + return result; + } + }; + + struct BoundFlagRef : BoundFlagRefBase { + bool& m_ref; + + explicit BoundFlagRef(bool& ref) : m_ref(ref) {} + + auto setFlag(bool flag) -> ParserResult override { + m_ref = flag; + return ParserResult::ok(ParseResultType::Matched); + } + }; + + template <typename ReturnType> struct LambdaInvoker { + static_assert(std::is_same<ReturnType, ParserResult>::value, + "Lambda must return void or clara::ParserResult"); + + template <typename L, typename ArgType> + static auto invoke(L const& lambda, ArgType const& arg) + -> ParserResult { + return lambda(arg); + } + }; + + template <> struct LambdaInvoker<void> { + template <typename L, typename ArgType> + static auto invoke(L const& lambda, ArgType const& arg) + -> ParserResult { + lambda(arg); + return ParserResult::ok(ParseResultType::Matched); + } + }; + + template <typename ArgType, typename L> + inline auto invokeLambda(L const& lambda, std::string const& arg) + -> ParserResult { + ArgType temp{}; + auto result = convertInto(arg, temp); + return !result ? result + : LambdaInvoker<typename UnaryLambdaTraits< + L>::ReturnType>::invoke(lambda, temp); } - m_exeName.set( exeName ); + template <typename L> struct BoundLambda : BoundValueRefBase { + L m_lambda; - auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) ); - while( result.value().remainingTokens() ) { - bool tokenParsed = false; + static_assert(UnaryLambdaTraits<L>::isValid, + "Supplied lambda must take exactly one argument"); + explicit BoundLambda(L const& lambda) : m_lambda(lambda) {} - for( size_t i = 0; i < totalParsers; ++i ) { - auto& parseInfo = parseInfos[i]; - if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) { - result = parseInfo.parser->parse(exeName, result.value().remainingTokens()); - if (!result) - return result; - if (result.value().type() != ParseResultType::NoMatch) { - tokenParsed = true; - ++parseInfo.count; - break; + auto setValue(std::string const& arg) -> ParserResult override { + return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( + m_lambda, arg); + } + }; + + template <typename L> struct BoundFlagLambda : BoundFlagRefBase { + L m_lambda; + + static_assert(UnaryLambdaTraits<L>::isValid, + "Supplied lambda must take exactly one argument"); + static_assert( + std::is_same<typename UnaryLambdaTraits<L>::ArgType, + bool>::value, + "flags must be boolean"); + + explicit BoundFlagLambda(L const& lambda) : m_lambda(lambda) {} + + auto setFlag(bool flag) -> ParserResult override { + return LambdaInvoker<typename UnaryLambdaTraits< + L>::ReturnType>::invoke(m_lambda, flag); + } + }; + + enum class Optionality { Optional, Required }; + + struct Parser; + + class ParserBase { + public: + virtual ~ParserBase() = default; + virtual auto validate() const -> Result { return Result::ok(); } + virtual auto parse(std::string const& exeName, + TokenStream const& tokens) const + -> InternalParseResult = 0; + virtual auto cardinality() const -> size_t { return 1; } + + auto parse(Args const& args) const -> InternalParseResult { + return parse(args.exeName(), TokenStream(args)); + } + }; + + template <typename DerivedT> + class ComposableParserImpl : public ParserBase { + public: + template <typename T> + auto operator|(T const& other) const -> Parser; + + template <typename T> + auto operator+(T const& other) const -> Parser; + }; + + // Common code and state for Args and Opts + template <typename DerivedT> + class ParserRefImpl : public ComposableParserImpl<DerivedT> { + protected: + Optionality m_optionality = Optionality::Optional; + std::shared_ptr<BoundRef> m_ref; + std::string m_hint; + std::string m_description; + + explicit ParserRefImpl(std::shared_ptr<BoundRef> const& ref) : + m_ref(ref) {} + + public: + template <typename T> + ParserRefImpl(T& ref, std::string const& hint) : + m_ref(std::make_shared<BoundValueRef<T>>(ref)), + m_hint(hint) {} + + template <typename LambdaT> + ParserRefImpl(LambdaT const& ref, std::string const& hint) : + m_ref(std::make_shared<BoundLambda<LambdaT>>(ref)), + m_hint(hint) {} + + auto operator()(std::string const& description) -> DerivedT& { + m_description = description; + return static_cast<DerivedT&>(*this); + } + + auto optional() -> DerivedT& { + m_optionality = Optionality::Optional; + return static_cast<DerivedT&>(*this); + }; + + auto required() -> DerivedT& { + m_optionality = Optionality::Required; + return static_cast<DerivedT&>(*this); + }; + + auto isOptional() const -> bool { + return m_optionality == Optionality::Optional; + } + + auto cardinality() const -> size_t override { + if (m_ref->isContainer()) + return 0; + else + return 1; + } + + auto hint() const -> std::string { return m_hint; } + }; + + class ExeName : public ComposableParserImpl<ExeName> { + std::shared_ptr<std::string> m_name; + std::shared_ptr<BoundValueRefBase> m_ref; + + template <typename LambdaT> + static auto makeRef(LambdaT const& lambda) + -> std::shared_ptr<BoundValueRefBase> { + return std::make_shared<BoundLambda<LambdaT>>(lambda); + } + + public: + ExeName() : + m_name(std::make_shared<std::string>("<executable>")) {} + + explicit ExeName(std::string& ref) : ExeName() { + m_ref = std::make_shared<BoundValueRef<std::string>>(ref); + } + + template <typename LambdaT> + explicit ExeName(LambdaT const& lambda) : ExeName() { + m_ref = std::make_shared<BoundLambda<LambdaT>>(lambda); + } + + // The exe name is not parsed out of the normal tokens, but is + // handled specially + auto parse(std::string const&, TokenStream const& tokens) const + -> InternalParseResult override { + return InternalParseResult::ok( + ParseState(ParseResultType::NoMatch, tokens)); + } + + auto name() const -> std::string { return *m_name; } + auto set(std::string const& newName) -> ParserResult { + + auto lastSlash = newName.find_last_of("\\/"); + auto filename = (lastSlash == std::string::npos) + ? newName + : newName.substr(lastSlash + 1); + + *m_name = filename; + if (m_ref) + return m_ref->setValue(filename); + else + return ParserResult::ok(ParseResultType::Matched); + } + }; + + class Arg : public ParserRefImpl<Arg> { + public: + using ParserRefImpl::ParserRefImpl; + + auto parse(std::string const&, TokenStream const& tokens) const + -> InternalParseResult override { + auto validationResult = validate(); + if (!validationResult) + return InternalParseResult(validationResult); + + auto remainingTokens = tokens; + auto const& token = *remainingTokens; + if (token.type != TokenType::Argument) + return InternalParseResult::ok(ParseState( + ParseResultType::NoMatch, remainingTokens)); + + assert(!m_ref->isFlag()); + auto valueRef = + static_cast<detail::BoundValueRefBase*>(m_ref.get()); + + auto result = valueRef->setValue(remainingTokens->token); + if (!result) + return InternalParseResult(result); + else + return InternalParseResult::ok(ParseState( + ParseResultType::Matched, ++remainingTokens)); + } + }; + + inline auto normaliseOpt(std::string const& optName) + -> std::string { +#ifdef CATCH_PLATFORM_WINDOWS + if (optName[0] == '/') + return "-" + optName.substr(1); + else +#endif + return optName; + } + + class Opt : public ParserRefImpl<Opt> { + protected: + std::vector<std::string> m_optNames; + + public: + template <typename LambdaT> + explicit Opt(LambdaT const& ref) : + ParserRefImpl( + std::make_shared<BoundFlagLambda<LambdaT>>(ref)) {} + + explicit Opt(bool& ref) : + ParserRefImpl(std::make_shared<BoundFlagRef>(ref)) {} + + template <typename LambdaT> + Opt(LambdaT const& ref, std::string const& hint) : + ParserRefImpl(ref, hint) {} + + template <typename T> + Opt(T& ref, std::string const& hint) : + ParserRefImpl(ref, hint) {} + + auto operator[](std::string const& optName) -> Opt& { + m_optNames.push_back(optName); + return *this; + } + + auto getHelpColumns() const -> std::vector<HelpColumns> { + std::ostringstream oss; + bool first = true; + for (auto const& opt : m_optNames) { + if (first) + first = false; + else + oss << ", "; + oss << opt; + } + if (!m_hint.empty()) + oss << " <" << m_hint << ">"; + return {{oss.str(), m_description}}; + } + + auto isMatch(std::string const& optToken) const -> bool { + auto normalisedToken = normaliseOpt(optToken); + for (auto const& name : m_optNames) { + if (normaliseOpt(name) == normalisedToken) + return true; + } + return false; + } + + using ParserBase::parse; + + auto parse(std::string const&, TokenStream const& tokens) const + -> InternalParseResult override { + auto validationResult = validate(); + if (!validationResult) + return InternalParseResult(validationResult); + + auto remainingTokens = tokens; + if (remainingTokens && + remainingTokens->type == TokenType::Option) { + auto const& token = *remainingTokens; + if (isMatch(token.token)) { + if (m_ref->isFlag()) { + auto flagRef = + static_cast<detail::BoundFlagRefBase*>( + m_ref.get()); + auto result = flagRef->setFlag(true); + if (!result) + return InternalParseResult(result); + if (result.value() == + ParseResultType::ShortCircuitAll) + return InternalParseResult::ok(ParseState( + result.value(), remainingTokens)); + } else { + auto valueRef = + static_cast<detail::BoundValueRefBase*>( + m_ref.get()); + ++remainingTokens; + if (!remainingTokens) + return InternalParseResult::runtimeError( + "Expected argument following " + + token.token); + auto const& argToken = *remainingTokens; + if (argToken.type != TokenType::Argument) + return InternalParseResult::runtimeError( + "Expected argument following " + + token.token); + auto result = + valueRef->setValue(argToken.token); + if (!result) + return InternalParseResult(result); + if (result.value() == + ParseResultType::ShortCircuitAll) + return InternalParseResult::ok(ParseState( + result.value(), remainingTokens)); + } + return InternalParseResult::ok(ParseState( + ParseResultType::Matched, ++remainingTokens)); } } + return InternalParseResult::ok( + ParseState(ParseResultType::NoMatch, remainingTokens)); } - if( result.value().type() == ParseResultType::ShortCircuitAll ) + auto validate() const -> Result override { + if (m_optNames.empty()) + return Result::logicError("No options supplied to Opt"); + for (auto const& name : m_optNames) { + if (name.empty()) + return Result::logicError( + "Option name cannot be empty"); +#ifdef CATCH_PLATFORM_WINDOWS + if (name[0] != '-' && name[0] != '/') + return Result::logicError( + "Option name must begin with '-' or '/'"); +#else + if (name[0] != '-') + return Result::logicError( + "Option name must begin with '-'"); +#endif + } + return ParserRefImpl::validate(); + } + }; + + struct Help : Opt { + Help(bool& showHelpFlag) : + Opt([&](bool flag) { + showHelpFlag = flag; + return ParserResult::ok( + ParseResultType::ShortCircuitAll); + }) { + static_cast<Opt&> (*this)( + "display usage information")["-?"]["-h"]["--help"] + .optional(); + } + }; + + struct Parser : ParserBase { + + mutable ExeName m_exeName; + std::vector<Opt> m_options; + std::vector<Arg> m_args; + + auto operator|=(ExeName const& exeName) -> Parser& { + m_exeName = exeName; + return *this; + } + + auto operator|=(Arg const& arg) -> Parser& { + m_args.push_back(arg); + return *this; + } + + auto operator|=(Opt const& opt) -> Parser& { + m_options.push_back(opt); + return *this; + } + + auto operator|=(Parser const& other) -> Parser& { + m_options.insert(m_options.end(), + other.m_options.begin(), + other.m_options.end()); + m_args.insert( + m_args.end(), other.m_args.begin(), other.m_args.end()); + return *this; + } + + template <typename T> + auto operator|(T const& other) const -> Parser { + return Parser(*this) |= other; + } + + // Forward deprecated interface with '+' instead of '|' + template <typename T> + auto operator+=(T const& other) -> Parser& { + return operator|=(other); + } + template <typename T> + auto operator+(T const& other) const -> Parser { + return operator|(other); + } + + auto getHelpColumns() const -> std::vector<HelpColumns> { + std::vector<HelpColumns> cols; + for (auto const& o : m_options) { + auto childCols = o.getHelpColumns(); + cols.insert( + cols.end(), childCols.begin(), childCols.end()); + } + return cols; + } + + void writeToStream(std::ostream& os) const { + if (!m_exeName.name().empty()) { + os << "usage:\n" + << " " << m_exeName.name() << " "; + bool required = true, first = true; + for (auto const& arg : m_args) { + if (first) + first = false; + else + os << " "; + if (arg.isOptional() && required) { + os << "["; + required = false; + } + os << "<" << arg.hint() << ">"; + if (arg.cardinality() == 0) + os << " ... "; + } + if (!required) + os << "]"; + if (!m_options.empty()) + os << " options"; + os << "\n\nwhere options are:" << std::endl; + } + + auto rows = getHelpColumns(); + size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH; + size_t optWidth = 0; + for (auto const& cols : rows) + optWidth = (std::max)(optWidth, cols.left.size() + 2); + + optWidth = (std::min)(optWidth, consoleWidth / 2); + + for (auto const& cols : rows) { + auto row = + TextFlow::Column(cols.left).width(optWidth).indent( + 2) + + TextFlow::Spacer(4) + + TextFlow::Column(cols.right) + .width(consoleWidth - 7 - optWidth); + os << row << std::endl; + } + } + + friend auto operator<<(std::ostream& os, Parser const& parser) + -> std::ostream& { + parser.writeToStream(os); + return os; + } + + auto validate() const -> Result override { + for (auto const& opt : m_options) { + auto result = opt.validate(); + if (!result) + return result; + } + for (auto const& arg : m_args) { + auto result = arg.validate(); + if (!result) + return result; + } + return Result::ok(); + } + + using ParserBase::parse; + + auto parse(std::string const& exeName, + TokenStream const& tokens) const + -> InternalParseResult override { + + struct ParserInfo { + ParserBase const* parser = nullptr; + size_t count = 0; + }; + const size_t totalParsers = + m_options.size() + m_args.size(); + assert(totalParsers < 512); + // ParserInfo parseInfos[totalParsers]; // <-- this is what + // we really want to do + ParserInfo parseInfos[512]; + + { + size_t i = 0; + for (auto const& opt : m_options) + parseInfos[i++].parser = &opt; + for (auto const& arg : m_args) + parseInfos[i++].parser = &arg; + } + + m_exeName.set(exeName); + + auto result = InternalParseResult::ok( + ParseState(ParseResultType::NoMatch, tokens)); + while (result.value().remainingTokens()) { + bool tokenParsed = false; + + for (size_t i = 0; i < totalParsers; ++i) { + auto& parseInfo = parseInfos[i]; + if (parseInfo.parser->cardinality() == 0 || + parseInfo.count < + parseInfo.parser->cardinality()) + { + result = parseInfo.parser->parse( + exeName, result.value().remainingTokens()); + if (!result) + return result; + if (result.value().type() != + ParseResultType::NoMatch) { + tokenParsed = true; + ++parseInfo.count; + break; + } + } + } + + if (result.value().type() == + ParseResultType::ShortCircuitAll) + return result; + if (!tokenParsed) + return InternalParseResult::runtimeError( + "Unrecognised token: " + + result.value().remainingTokens()->token); + } + // !TBD Check missing required options return result; - if( !tokenParsed ) - return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token ); + } + }; + + template <typename DerivedT> + template <typename T> + auto ComposableParserImpl<DerivedT>::operator|(T const& other) const + -> Parser { + return Parser() | static_cast<DerivedT const&>(*this) | other; } - // !TBD Check missing required options - return result; - } - }; + } // namespace detail - template<typename DerivedT> - template<typename T> - auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser { - return Parser() | static_cast<DerivedT const &>( *this ) | other; - } -} // namespace detail + // A Combined parser + using detail::Parser; -// A Combined parser -using detail::Parser; + // A parser for options + using detail::Opt; -// A parser for options -using detail::Opt; + // A parser for arguments + using detail::Arg; -// A parser for arguments -using detail::Arg; + // Wrapper for argc, argv from main() + using detail::Args; -// Wrapper for argc, argv from main() -using detail::Args; + // Specifies the name of the executable + using detail::ExeName; -// Specifies the name of the executable -using detail::ExeName; + // Convenience wrapper for option parser that specifies the help option + using detail::Help; -// Convenience wrapper for option parser that specifies the help option -using detail::Help; + // enum of result types from a parse + using detail::ParseResultType; -// enum of result types from a parse -using detail::ParseResultType; + // Result type for parser operation + using detail::ParserResult; -// Result type for parser operation -using detail::ParserResult; - -}} // namespace Catch::clara + } // namespace clara +} // namespace Catch // end clara.hpp #ifdef __clang__ @@ -9677,14 +11005,15 @@ // Restore Clara's value for console width, if present #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH -#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH +#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH \ + CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH #endif // end catch_clara.h namespace Catch { - clara::Parser makeCommandLineParser( ConfigData& config ); + clara::Parser makeCommandLineParser(ConfigData& config); } // end namespace Catch @@ -9694,211 +11023,201 @@ namespace Catch { - clara::Parser makeCommandLineParser( ConfigData& config ) { + clara::Parser makeCommandLineParser(ConfigData& config) { using namespace clara; - auto const setWarning = [&]( std::string const& warning ) { - auto warningSet = [&]() { - if( warning == "NoAssertions" ) - return WarnAbout::NoAssertions; + auto const setWarning = [&](std::string const& warning) { + auto warningSet = [&]() { + if (warning == "NoAssertions") + return WarnAbout::NoAssertions; - if ( warning == "NoTests" ) - return WarnAbout::NoTests; + if (warning == "NoTests") + return WarnAbout::NoTests; - return WarnAbout::Nothing; - }(); + return WarnAbout::Nothing; + }(); - if (warningSet == WarnAbout::Nothing) - return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" ); - config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet ); - return ParserResult::ok( ParseResultType::Matched ); - }; - auto const loadTestNamesFromFile = [&]( std::string const& filename ) { - std::ifstream f( filename.c_str() ); - if( !f.is_open() ) - return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" ); + if (warningSet == WarnAbout::Nothing) + return ParserResult::runtimeError("Unrecognised warning: '" + + warning + "'"); + config.warnings = + static_cast<WarnAbout::What>(config.warnings | warningSet); + return ParserResult::ok(ParseResultType::Matched); + }; + auto const loadTestNamesFromFile = [&](std::string const& filename) { + std::ifstream f(filename.c_str()); + if (!f.is_open()) + return ParserResult::runtimeError( + "Unable to load input file: '" + filename + "'"); - std::string line; - while( std::getline( f, line ) ) { - line = trim(line); - if( !line.empty() && !startsWith( line, '#' ) ) { - if( !startsWith( line, '"' ) ) - line = '"' + line + '"'; - config.testsOrTags.push_back( line ); - config.testsOrTags.emplace_back( "," ); - } + std::string line; + while (std::getline(f, line)) { + line = trim(line); + if (!line.empty() && !startsWith(line, '#')) { + if (!startsWith(line, '"')) + line = '"' + line + '"'; + config.testsOrTags.push_back(line); + config.testsOrTags.emplace_back(","); } - //Remove comma in the end - if(!config.testsOrTags.empty()) - config.testsOrTags.erase( config.testsOrTags.end()-1 ); + } + // Remove comma in the end + if (!config.testsOrTags.empty()) + config.testsOrTags.erase(config.testsOrTags.end() - 1); - return ParserResult::ok( ParseResultType::Matched ); - }; - auto const setTestOrder = [&]( std::string const& order ) { - if( startsWith( "declared", order ) ) - config.runOrder = RunTests::InDeclarationOrder; - else if( startsWith( "lexical", order ) ) - config.runOrder = RunTests::InLexicographicalOrder; - else if( startsWith( "random", order ) ) - config.runOrder = RunTests::InRandomOrder; - else - return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" ); - return ParserResult::ok( ParseResultType::Matched ); - }; - auto const setRngSeed = [&]( std::string const& seed ) { - if( seed != "time" ) - return clara::detail::convertInto( seed, config.rngSeed ); - config.rngSeed = static_cast<unsigned int>( std::time(nullptr) ); - return ParserResult::ok( ParseResultType::Matched ); - }; - auto const setColourUsage = [&]( std::string const& useColour ) { - auto mode = toLower( useColour ); + return ParserResult::ok(ParseResultType::Matched); + }; + auto const setTestOrder = [&](std::string const& order) { + if (startsWith("declared", order)) + config.runOrder = RunTests::InDeclarationOrder; + else if (startsWith("lexical", order)) + config.runOrder = RunTests::InLexicographicalOrder; + else if (startsWith("random", order)) + config.runOrder = RunTests::InRandomOrder; + else + return clara::ParserResult::runtimeError( + "Unrecognised ordering: '" + order + "'"); + return ParserResult::ok(ParseResultType::Matched); + }; + auto const setRngSeed = [&](std::string const& seed) { + if (seed != "time") + return clara::detail::convertInto(seed, config.rngSeed); + config.rngSeed = static_cast<unsigned int>(std::time(nullptr)); + return ParserResult::ok(ParseResultType::Matched); + }; + auto const setColourUsage = [&](std::string const& useColour) { + auto mode = toLower(useColour); - if( mode == "yes" ) - config.useColour = UseColour::Yes; - else if( mode == "no" ) - config.useColour = UseColour::No; - else if( mode == "auto" ) - config.useColour = UseColour::Auto; - else - return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" ); - return ParserResult::ok( ParseResultType::Matched ); - }; - auto const setWaitForKeypress = [&]( std::string const& keypress ) { - auto keypressLc = toLower( keypress ); - if (keypressLc == "never") - config.waitForKeypress = WaitForKeypress::Never; - else if( keypressLc == "start" ) - config.waitForKeypress = WaitForKeypress::BeforeStart; - else if( keypressLc == "exit" ) - config.waitForKeypress = WaitForKeypress::BeforeExit; - else if( keypressLc == "both" ) - config.waitForKeypress = WaitForKeypress::BeforeStartAndExit; - else - return ParserResult::runtimeError( "keypress argument must be one of: never, start, exit or both. '" + keypress + "' not recognised" ); - return ParserResult::ok( ParseResultType::Matched ); - }; - auto const setVerbosity = [&]( std::string const& verbosity ) { - auto lcVerbosity = toLower( verbosity ); - if( lcVerbosity == "quiet" ) + if (mode == "yes") + config.useColour = UseColour::Yes; + else if (mode == "no") + config.useColour = UseColour::No; + else if (mode == "auto") + config.useColour = UseColour::Auto; + else + return ParserResult::runtimeError( + "colour mode must be one of: auto, yes or no. '" + + useColour + "' not recognised"); + return ParserResult::ok(ParseResultType::Matched); + }; + auto const setWaitForKeypress = [&](std::string const& keypress) { + auto keypressLc = toLower(keypress); + if (keypressLc == "never") + config.waitForKeypress = WaitForKeypress::Never; + else if (keypressLc == "start") + config.waitForKeypress = WaitForKeypress::BeforeStart; + else if (keypressLc == "exit") + config.waitForKeypress = WaitForKeypress::BeforeExit; + else if (keypressLc == "both") + config.waitForKeypress = WaitForKeypress::BeforeStartAndExit; + else + return ParserResult::runtimeError( + "keypress argument must be one of: never, start, exit or " + "both. '" + + keypress + "' not recognised"); + return ParserResult::ok(ParseResultType::Matched); + }; + auto const setVerbosity = [&](std::string const& verbosity) { + auto lcVerbosity = toLower(verbosity); + if (lcVerbosity == "quiet") config.verbosity = Verbosity::Quiet; - else if( lcVerbosity == "normal" ) + else if (lcVerbosity == "normal") config.verbosity = Verbosity::Normal; - else if( lcVerbosity == "high" ) + else if (lcVerbosity == "high") config.verbosity = Verbosity::High; else - return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" ); - return ParserResult::ok( ParseResultType::Matched ); + return ParserResult::runtimeError("Unrecognised verbosity, '" + + verbosity + "'"); + return ParserResult::ok(ParseResultType::Matched); }; - auto const setReporter = [&]( std::string const& reporter ) { - IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories(); + auto const setReporter = [&](std::string const& reporter) { + IReporterRegistry::FactoryMap const& factories = + getRegistryHub().getReporterRegistry().getFactories(); - auto lcReporter = toLower( reporter ); - auto result = factories.find( lcReporter ); + auto lcReporter = toLower(reporter); + auto result = factories.find(lcReporter); - if( factories.end() != result ) + if (factories.end() != result) config.reporterName = lcReporter; else - return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" ); - return ParserResult::ok( ParseResultType::Matched ); + return ParserResult::runtimeError( + "Unrecognized reporter, '" + reporter + + "'. Check available with --list-reporters"); + return ParserResult::ok(ParseResultType::Matched); }; - auto cli - = ExeName( config.processName ) - | Help( config.showHelp ) - | Opt( config.listTests ) - ["-l"]["--list-tests"] - ( "list all/matching test cases" ) - | Opt( config.listTags ) - ["-t"]["--list-tags"] - ( "list all/matching tags" ) - | Opt( config.showSuccessfulTests ) - ["-s"]["--success"] - ( "include successful tests in output" ) - | Opt( config.shouldDebugBreak ) - ["-b"]["--break"] - ( "break into debugger on failure" ) - | Opt( config.noThrow ) - ["-e"]["--nothrow"] - ( "skip exception tests" ) - | Opt( config.showInvisibles ) - ["-i"]["--invisibles"] - ( "show invisibles (tabs, newlines)" ) - | Opt( config.outputFilename, "filename" ) - ["-o"]["--out"] - ( "output filename" ) - | Opt( setReporter, "name" ) - ["-r"]["--reporter"] - ( "reporter to use (defaults to console)" ) - | Opt( config.name, "name" ) - ["-n"]["--name"] - ( "suite name" ) - | Opt( [&]( bool ){ config.abortAfter = 1; } ) - ["-a"]["--abort"] - ( "abort at first failure" ) - | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" ) - ["-x"]["--abortx"] - ( "abort after x failures" ) - | Opt( setWarning, "warning name" ) - ["-w"]["--warn"] - ( "enable warnings" ) - | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" ) - ["-d"]["--durations"] - ( "show test durations" ) - | Opt( config.minDuration, "seconds" ) - ["-D"]["--min-duration"] - ( "show test durations for tests taking at least the given number of seconds" ) - | Opt( loadTestNamesFromFile, "filename" ) - ["-f"]["--input-file"] - ( "load test names to run from a file" ) - | Opt( config.filenamesAsTags ) - ["-#"]["--filenames-as-tags"] - ( "adds a tag for the filename" ) - | Opt( config.sectionsToRun, "section name" ) - ["-c"]["--section"] - ( "specify section to run" ) - | Opt( setVerbosity, "quiet|normal|high" ) - ["-v"]["--verbosity"] - ( "set output verbosity" ) - | Opt( config.listTestNamesOnly ) - ["--list-test-names-only"] - ( "list all/matching test cases names only" ) - | Opt( config.listReporters ) - ["--list-reporters"] - ( "list all reporters" ) - | Opt( setTestOrder, "decl|lex|rand" ) - ["--order"] - ( "test case order (defaults to decl)" ) - | Opt( setRngSeed, "'time'|number" ) - ["--rng-seed"] - ( "set a specific seed for random numbers" ) - | Opt( setColourUsage, "yes|no" ) - ["--use-colour"] - ( "should output be colourised" ) - | Opt( config.libIdentify ) - ["--libidentify"] - ( "report name and version according to libidentify standard" ) - | Opt( setWaitForKeypress, "never|start|exit|both" ) - ["--wait-for-keypress"] - ( "waits for a keypress before exiting" ) - | Opt( config.benchmarkSamples, "samples" ) - ["--benchmark-samples"] - ( "number of samples to collect (default: 100)" ) - | Opt( config.benchmarkResamples, "resamples" ) - ["--benchmark-resamples"] - ( "number of resamples for the bootstrap (default: 100000)" ) - | Opt( config.benchmarkConfidenceInterval, "confidence interval" ) - ["--benchmark-confidence-interval"] - ( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" ) - | Opt( config.benchmarkNoAnalysis ) - ["--benchmark-no-analysis"] - ( "perform only measurements; do not perform any analysis" ) - | Opt( config.benchmarkWarmupTime, "benchmarkWarmupTime" ) - ["--benchmark-warmup-time"] - ( "amount of time in milliseconds spent on warming up each test (default: 100)" ) - | Arg( config.testsOrTags, "test name|pattern|tags" ) - ( "which test or tests to use" ); + auto cli = + ExeName(config.processName) | Help(config.showHelp) | + Opt(config.listTests)["-l"]["--list-tests"]( + "list all/matching test cases") | + Opt(config.listTags)["-t"]["--list-tags"]( + "list all/matching tags") | + Opt(config.showSuccessfulTests)["-s"]["--success"]( + "include successful tests in output") | + Opt(config.shouldDebugBreak)["-b"]["--break"]( + "break into debugger on failure") | + Opt(config.noThrow)["-e"]["--nothrow"]("skip exception tests") | + Opt(config.showInvisibles)["-i"]["--invisibles"]( + "show invisibles (tabs, newlines)") | + Opt(config.outputFilename, + "filename")["-o"]["--out"]("output filename") | + Opt(setReporter, "name")["-r"]["--reporter"]( + "reporter to use (defaults to console)") | + Opt(config.name, "name")["-n"]["--name"]("suite name") | + Opt([&](bool) { config.abortAfter = 1; })["-a"]["--abort"]( + "abort at first failure") | + Opt([&](int x) { config.abortAfter = x; }, + "no. failures")["-x"]["--abortx"]("abort after x failures") | + Opt(setWarning, "warning name")["-w"]["--warn"]("enable warnings") | + Opt( + [&](bool flag) { + config.showDurations = + flag ? ShowDurations::Always : ShowDurations::Never; + }, + "yes|no")["-d"]["--durations"]("show test durations") | + Opt(config.minDuration, "seconds")["-D"]["--min-duration"]( + "show test durations for tests taking at least the given " + "number of seconds") | + Opt(loadTestNamesFromFile, "filename")["-f"]["--input-file"]( + "load test names to run from a file") | + Opt(config.filenamesAsTags)["-#"]["--filenames-as-tags"]( + "adds a tag for the filename") | + Opt(config.sectionsToRun, + "section name")["-c"]["--section"]("specify section to run") | + Opt(setVerbosity, "quiet|normal|high")["-v"]["--verbosity"]( + "set output verbosity") | + Opt(config.listTestNamesOnly)["--list-test-names-only"]( + "list all/matching test cases names only") | + Opt(config.listReporters)["--list-reporters"]( + "list all reporters") | + Opt(setTestOrder, "decl|lex|rand")["--order"]( + "test case order (defaults to decl)") | + Opt(setRngSeed, "'time'|number")["--rng-seed"]( + "set a specific seed for random numbers") | + Opt(setColourUsage, + "yes|no")["--use-colour"]("should output be colourised") | + Opt(config.libIdentify)["--libidentify"]( + "report name and version according to libidentify standard") | + Opt(setWaitForKeypress, + "never|start|exit|both")["--wait-for-keypress"]( + "waits for a keypress before exiting") | + Opt(config.benchmarkSamples, "samples")["--benchmark-samples"]( + "number of samples to collect (default: 100)") | + Opt(config.benchmarkResamples, + "resamples")["--benchmark-resamples"]( + "number of resamples for the bootstrap (default: 100000)") | + Opt(config.benchmarkConfidenceInterval, + "confidence interval")["--benchmark-confidence-interval"]( + "confidence interval for the bootstrap (between 0 and 1, " + "default: 0.95)") | + Opt(config.benchmarkNoAnalysis)["--benchmark-no-analysis"]( + "perform only measurements; do not perform any analysis") | + Opt(config.benchmarkWarmupTime, + "benchmarkWarmupTime")["--benchmark-warmup-time"]( + "amount of time in milliseconds spent on warming up each test " + "(default: 100)") | + Arg(config.testsOrTags, + "test name|pattern|tags")("which test or tests to use"); return cli; } @@ -9912,16 +11231,20 @@ namespace Catch { - bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept { - return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0); + bool + SourceLineInfo::operator==(SourceLineInfo const& other) const noexcept { + return line == other.line && + (file == other.file || std::strcmp(file, other.file) == 0); } - bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept { + bool SourceLineInfo::operator<(SourceLineInfo const& other) const noexcept { // We can assume that the same file will usually have the same pointer. - // Thus, if the pointers are the same, there is no point in calling the strcmp - return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0)); + // Thus, if the pointers are the same, there is no point in calling the + // strcmp + return line < other.line || (line == other.line && file != other.file && + (std::strcmp(file, other.file) < 0)); } - std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) { + std::ostream& operator<<(std::ostream& os, SourceLineInfo const& info) { #ifndef __GNUG__ os << info.file << '(' << info.line << ')'; #else @@ -9930,23 +11253,19 @@ return os; } - std::string StreamEndStop::operator+() const { - return std::string(); - } + std::string StreamEndStop::operator+() const { return std::string(); } NonCopyable::NonCopyable() = default; NonCopyable::~NonCopyable() = default; -} +} // namespace Catch // end catch_common.cpp // start catch_config.cpp namespace Catch { - Config::Config( ConfigData const& data ) - : m_data( data ), - m_stream( openStream() ) - { + Config::Config(ConfigData const& data) : + m_data(data), m_stream(openStream()) { // We need to trim filter specs to avoid trouble with superfluous // whitespace (esp. important for bdd macros, as those are manually // aligned with whitespace). @@ -9969,19 +11288,25 @@ } std::string const& Config::getFilename() const { - return m_data.outputFilename ; + return m_data.outputFilename; } - bool Config::listTests() const { return m_data.listTests; } - bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; } - bool Config::listTags() const { return m_data.listTags; } - bool Config::listReporters() const { return m_data.listReporters; } + bool Config::listTests() const { return m_data.listTests; } + bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; } + bool Config::listTags() const { return m_data.listTags; } + bool Config::listReporters() const { return m_data.listReporters; } std::string Config::getProcessName() const { return m_data.processName; } - std::string const& Config::getReporterName() const { return m_data.reporterName; } + std::string const& Config::getReporterName() const { + return m_data.reporterName; + } - std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; } - std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; } + std::vector<std::string> const& Config::getTestsOrTags() const { + return m_data.testsOrTags; + } + std::vector<std::string> const& Config::getSectionsToRun() const { + return m_data.sectionsToRun; + } TestSpec const& Config::testSpec() const { return m_testSpec; } bool Config::hasTestFilters() const { return m_hasTestFilters; } @@ -9989,27 +11314,45 @@ bool Config::showHelp() const { return m_data.showHelp; } // IConfig interface - bool Config::allowThrows() const { return !m_data.noThrow; } - std::ostream& Config::stream() const { return m_stream->stream(); } - std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; } - bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; } - bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); } - bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); } - ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; } - double Config::minDuration() const { return m_data.minDuration; } - RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; } - unsigned int Config::rngSeed() const { return m_data.rngSeed; } - UseColour::YesOrNo Config::useColour() const { return m_data.useColour; } - bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; } - int Config::abortAfter() const { return m_data.abortAfter; } - bool Config::showInvisibles() const { return m_data.showInvisibles; } - Verbosity Config::verbosity() const { return m_data.verbosity; } + bool Config::allowThrows() const { return !m_data.noThrow; } + std::ostream& Config::stream() const { return m_stream->stream(); } + std::string Config::name() const { + return m_data.name.empty() ? m_data.processName : m_data.name; + } + bool Config::includeSuccessfulResults() const { + return m_data.showSuccessfulTests; + } + bool Config::warnAboutMissingAssertions() const { + return !!(m_data.warnings & WarnAbout::NoAssertions); + } + bool Config::warnAboutNoTests() const { + return !!(m_data.warnings & WarnAbout::NoTests); + } + ShowDurations::OrNot Config::showDurations() const { + return m_data.showDurations; + } + double Config::minDuration() const { return m_data.minDuration; } + RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; } + unsigned int Config::rngSeed() const { return m_data.rngSeed; } + UseColour::YesOrNo Config::useColour() const { return m_data.useColour; } + bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; } + int Config::abortAfter() const { return m_data.abortAfter; } + bool Config::showInvisibles() const { return m_data.showInvisibles; } + Verbosity Config::verbosity() const { return m_data.verbosity; } - bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; } - int Config::benchmarkSamples() const { return m_data.benchmarkSamples; } - double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; } - unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; } - std::chrono::milliseconds Config::benchmarkWarmupTime() const { return std::chrono::milliseconds(m_data.benchmarkWarmupTime); } + bool Config::benchmarkNoAnalysis() const { + return m_data.benchmarkNoAnalysis; + } + int Config::benchmarkSamples() const { return m_data.benchmarkSamples; } + double Config::benchmarkConfidenceInterval() const { + return m_data.benchmarkConfidenceInterval; + } + unsigned int Config::benchmarkResamples() const { + return m_data.benchmarkResamples; + } + std::chrono::milliseconds Config::benchmarkWarmupTime() const { + return std::chrono::milliseconds(m_data.benchmarkWarmupTime); + } IStream const* Config::openStream() { return Catch::makeStream(m_data.outputFilename); @@ -10020,8 +11363,8 @@ // start catch_console_colour.cpp #if defined(__clang__) -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wexit-time-destructors" +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wexit-time-destructors" #endif // start catch_errno_guard.h @@ -10032,25 +11375,26 @@ public: ErrnoGuard(); ~ErrnoGuard(); + private: int m_oldErrno; }; -} +} // namespace Catch // end catch_errno_guard.h // start catch_windows_h_proxy.h - #if defined(CATCH_PLATFORM_WINDOWS) #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX) -# define CATCH_DEFINED_NOMINMAX -# define NOMINMAX +#define CATCH_DEFINED_NOMINMAX +#define NOMINMAX #endif -#if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN) -# define CATCH_DEFINED_WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN +#if !defined(WIN32_LEAN_AND_MEAN) && \ + !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN) +#define CATCH_DEFINED_WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN #endif #ifdef __AFXDLL @@ -10060,10 +11404,10 @@ #endif #ifdef CATCH_DEFINED_NOMINMAX -# undef NOMINMAX +#undef NOMINMAX #endif #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN -# undef WIN32_LEAN_AND_MEAN +#undef WIN32_LEAN_AND_MEAN #endif #endif // defined(CATCH_PLATFORM_WINDOWS) @@ -10076,11 +11420,11 @@ struct IColourImpl { virtual ~IColourImpl() = default; - virtual void use( Colour::Code _colourCode ) = 0; + virtual void use(Colour::Code _colourCode) = 0; }; struct NoColourImpl : IColourImpl { - void use( Colour::Code ) override {} + void use(Colour::Code) override {} static IColourImpl* instance() { static NoColourImpl s_instance; @@ -10088,163 +11432,208 @@ } }; - } // anon namespace + } // namespace } // namespace Catch -#if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI ) -# ifdef CATCH_PLATFORM_WINDOWS -# define CATCH_CONFIG_COLOUR_WINDOWS -# else -# define CATCH_CONFIG_COLOUR_ANSI -# endif +#if !defined(CATCH_CONFIG_COLOUR_NONE) && \ + !defined(CATCH_CONFIG_COLOUR_WINDOWS) && \ + !defined(CATCH_CONFIG_COLOUR_ANSI) +#ifdef CATCH_PLATFORM_WINDOWS +#define CATCH_CONFIG_COLOUR_WINDOWS +#else +#define CATCH_CONFIG_COLOUR_ANSI +#endif #endif -#if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) ///////////////////////////////////////// +#if defined( \ + CATCH_CONFIG_COLOUR_WINDOWS) ///////////////////////////////////////// namespace Catch { -namespace { + namespace { - class Win32ColourImpl : public IColourImpl { - public: - Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) ) - { - CONSOLE_SCREEN_BUFFER_INFO csbiInfo; - GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo ); - originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY ); - originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY ); - } - - void use( Colour::Code _colourCode ) override { - switch( _colourCode ) { - case Colour::None: return setTextAttribute( originalForegroundAttributes ); - case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); - case Colour::Red: return setTextAttribute( FOREGROUND_RED ); - case Colour::Green: return setTextAttribute( FOREGROUND_GREEN ); - case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE ); - case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN ); - case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN ); - case Colour::Grey: return setTextAttribute( 0 ); - - case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY ); - case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED ); - case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN ); - case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); - case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN ); - - case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" ); - - default: - CATCH_ERROR( "Unknown colour requested" ); + class Win32ColourImpl : public IColourImpl { + public: + Win32ColourImpl() : stdoutHandle(GetStdHandle(STD_OUTPUT_HANDLE)) { + CONSOLE_SCREEN_BUFFER_INFO csbiInfo; + GetConsoleScreenBufferInfo(stdoutHandle, &csbiInfo); + originalForegroundAttributes = + csbiInfo.wAttributes & + ~(BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | + BACKGROUND_INTENSITY); + originalBackgroundAttributes = + csbiInfo.wAttributes & + ~(FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | + FOREGROUND_INTENSITY); } + + void use(Colour::Code _colourCode) override { + switch (_colourCode) { + case Colour::None: + return setTextAttribute(originalForegroundAttributes); + case Colour::White: + return setTextAttribute(FOREGROUND_GREEN | + FOREGROUND_RED | + FOREGROUND_BLUE); + case Colour::Red: + return setTextAttribute(FOREGROUND_RED); + case Colour::Green: + return setTextAttribute(FOREGROUND_GREEN); + case Colour::Blue: + return setTextAttribute(FOREGROUND_BLUE); + case Colour::Cyan: + return setTextAttribute(FOREGROUND_BLUE | + FOREGROUND_GREEN); + case Colour::Yellow: + return setTextAttribute(FOREGROUND_RED | + FOREGROUND_GREEN); + case Colour::Grey: + return setTextAttribute(0); + + case Colour::LightGrey: + return setTextAttribute(FOREGROUND_INTENSITY); + case Colour::BrightRed: + return setTextAttribute(FOREGROUND_INTENSITY | + FOREGROUND_RED); + case Colour::BrightGreen: + return setTextAttribute(FOREGROUND_INTENSITY | + FOREGROUND_GREEN); + case Colour::BrightWhite: + return setTextAttribute( + FOREGROUND_INTENSITY | FOREGROUND_GREEN | + FOREGROUND_RED | FOREGROUND_BLUE); + case Colour::BrightYellow: + return setTextAttribute(FOREGROUND_INTENSITY | + FOREGROUND_RED | + FOREGROUND_GREEN); + + case Colour::Bright: + CATCH_INTERNAL_ERROR("not a colour"); + + default: + CATCH_ERROR("Unknown colour requested"); + } + } + + private: + void setTextAttribute(WORD _textAttribute) { + SetConsoleTextAttribute(stdoutHandle, + _textAttribute | + originalBackgroundAttributes); + } + HANDLE stdoutHandle; + WORD originalForegroundAttributes; + WORD originalBackgroundAttributes; + }; + + IColourImpl* platformColourInstance() { + static Win32ColourImpl s_instance; + + IConfigPtr config = getCurrentContext().getConfig(); + UseColour::YesOrNo colourMode = + config ? config->useColour() : UseColour::Auto; + if (colourMode == UseColour::Auto) + colourMode = UseColour::Yes; + return colourMode == UseColour::Yes ? &s_instance + : NoColourImpl::instance(); } - private: - void setTextAttribute( WORD _textAttribute ) { - SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes ); - } - HANDLE stdoutHandle; - WORD originalForegroundAttributes; - WORD originalBackgroundAttributes; - }; - - IColourImpl* platformColourInstance() { - static Win32ColourImpl s_instance; - - IConfigPtr config = getCurrentContext().getConfig(); - UseColour::YesOrNo colourMode = config - ? config->useColour() - : UseColour::Auto; - if( colourMode == UseColour::Auto ) - colourMode = UseColour::Yes; - return colourMode == UseColour::Yes - ? &s_instance - : NoColourImpl::instance(); - } - -} // end anon namespace + } // namespace } // end namespace Catch -#elif defined( CATCH_CONFIG_COLOUR_ANSI ) ////////////////////////////////////// +#elif defined(CATCH_CONFIG_COLOUR_ANSI) ////////////////////////////////////// #include <unistd.h> namespace Catch { -namespace { + namespace { - // use POSIX/ ANSI console terminal codes - // Thanks to Adam Strzelecki for original contribution - // (http://github.com/nanoant) - // https://github.com/philsquared/Catch/pull/131 - class PosixColourImpl : public IColourImpl { - public: - void use( Colour::Code _colourCode ) override { - switch( _colourCode ) { - case Colour::None: - case Colour::White: return setColour( "[0m" ); - case Colour::Red: return setColour( "[0;31m" ); - case Colour::Green: return setColour( "[0;32m" ); - case Colour::Blue: return setColour( "[0;34m" ); - case Colour::Cyan: return setColour( "[0;36m" ); - case Colour::Yellow: return setColour( "[0;33m" ); - case Colour::Grey: return setColour( "[1;30m" ); + // use POSIX/ ANSI console terminal codes + // Thanks to Adam Strzelecki for original contribution + // (http://github.com/nanoant) + // https://github.com/philsquared/Catch/pull/131 + class PosixColourImpl : public IColourImpl { + public: + void use(Colour::Code _colourCode) override { + switch (_colourCode) { + case Colour::None: + case Colour::White: + return setColour("[0m"); + case Colour::Red: + return setColour("[0;31m"); + case Colour::Green: + return setColour("[0;32m"); + case Colour::Blue: + return setColour("[0;34m"); + case Colour::Cyan: + return setColour("[0;36m"); + case Colour::Yellow: + return setColour("[0;33m"); + case Colour::Grey: + return setColour("[1;30m"); - case Colour::LightGrey: return setColour( "[0;37m" ); - case Colour::BrightRed: return setColour( "[1;31m" ); - case Colour::BrightGreen: return setColour( "[1;32m" ); - case Colour::BrightWhite: return setColour( "[1;37m" ); - case Colour::BrightYellow: return setColour( "[1;33m" ); + case Colour::LightGrey: + return setColour("[0;37m"); + case Colour::BrightRed: + return setColour("[1;31m"); + case Colour::BrightGreen: + return setColour("[1;32m"); + case Colour::BrightWhite: + return setColour("[1;37m"); + case Colour::BrightYellow: + return setColour("[1;33m"); - case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" ); - default: CATCH_INTERNAL_ERROR( "Unknown colour requested" ); + case Colour::Bright: + CATCH_INTERNAL_ERROR("not a colour"); + default: + CATCH_INTERNAL_ERROR("Unknown colour requested"); + } } - } - static IColourImpl* instance() { - static PosixColourImpl s_instance; - return &s_instance; - } + static IColourImpl* instance() { + static PosixColourImpl s_instance; + return &s_instance; + } - private: - void setColour( const char* _escapeCode ) { - getCurrentContext().getConfig()->stream() - << '\033' << _escapeCode; - } - }; + private: + void setColour(const char* _escapeCode) { + getCurrentContext().getConfig()->stream() + << '\033' << _escapeCode; + } + }; - bool useColourOnPlatform() { - return + bool useColourOnPlatform() { + return #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE) - !isDebuggerActive() && + !isDebuggerActive() && #endif #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__)) - isatty(STDOUT_FILENO) + isatty(STDOUT_FILENO) #else - false + false #endif - ; - } - IColourImpl* platformColourInstance() { - ErrnoGuard guard; - IConfigPtr config = getCurrentContext().getConfig(); - UseColour::YesOrNo colourMode = config - ? config->useColour() - : UseColour::Auto; - if( colourMode == UseColour::Auto ) - colourMode = useColourOnPlatform() - ? UseColour::Yes - : UseColour::No; - return colourMode == UseColour::Yes - ? PosixColourImpl::instance() - : NoColourImpl::instance(); - } + ; + } + IColourImpl* platformColourInstance() { + ErrnoGuard guard; + IConfigPtr config = getCurrentContext().getConfig(); + UseColour::YesOrNo colourMode = + config ? config->useColour() : UseColour::Auto; + if (colourMode == UseColour::Auto) + colourMode = + useColourOnPlatform() ? UseColour::Yes : UseColour::No; + return colourMode == UseColour::Yes ? PosixColourImpl::instance() + : NoColourImpl::instance(); + } -} // end anon namespace + } // namespace } // end namespace Catch -#else // not Windows or ANSI /////////////////////////////////////////////// +#else // not Windows or ANSI /////////////////////////////////////////////// namespace Catch { - static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); } + static IColourImpl* platformColourInstance() { + return NoColourImpl::instance(); + } } // end namespace Catch @@ -10252,38 +11641,39 @@ namespace Catch { - Colour::Colour( Code _colourCode ) { use( _colourCode ); } - Colour::Colour( Colour&& other ) noexcept { + Colour::Colour(Code _colourCode) { use(_colourCode); } + Colour::Colour(Colour&& other) noexcept { m_moved = other.m_moved; other.m_moved = true; } - Colour& Colour::operator=( Colour&& other ) noexcept { + Colour& Colour::operator=(Colour&& other) noexcept { m_moved = other.m_moved; - other.m_moved = true; + other.m_moved = true; return *this; } - Colour::~Colour(){ if( !m_moved ) use( None ); } + Colour::~Colour() { + if (!m_moved) + use(None); + } - void Colour::use( Code _colourCode ) { + void Colour::use(Code _colourCode) { static IColourImpl* impl = platformColourInstance(); // Strictly speaking, this cannot possibly happen. // However, under some conditions it does happen (see #1626), // and this change is small enough that we can let practicality // triumph over purity in this case. if (impl != nullptr) { - impl->use( _colourCode ); + impl->use(_colourCode); } } - std::ostream& operator << ( std::ostream& os, Colour const& ) { - return os; - } + std::ostream& operator<<(std::ostream& os, Colour const&) { return os; } } // end namespace Catch #if defined(__clang__) -# pragma clang diagnostic pop +#pragma clang diagnostic pop #endif // end catch_console_colour.cpp @@ -10294,29 +11684,19 @@ class Context : public IMutableContext, NonCopyable { public: // IContext - IResultCapture* getResultCapture() override { - return m_resultCapture; - } - IRunner* getRunner() override { - return m_runner; - } + IResultCapture* getResultCapture() override { return m_resultCapture; } + IRunner* getRunner() override { return m_runner; } - IConfigPtr const& getConfig() const override { - return m_config; - } + IConfigPtr const& getConfig() const override { return m_config; } ~Context() override; public: // IMutableContext - void setResultCapture( IResultCapture* resultCapture ) override { + void setResultCapture(IResultCapture* resultCapture) override { m_resultCapture = resultCapture; } - void setRunner( IRunner* runner ) override { - m_runner = runner; - } - void setConfig( IConfigPtr const& config ) override { - m_config = config; - } + void setRunner(IRunner* runner) override { m_runner = runner; } + void setConfig(IConfigPtr const& config) override { m_config = config; } friend IMutableContext& getCurrentMutableContext(); @@ -10326,12 +11706,9 @@ IResultCapture* m_resultCapture = nullptr; }; - IMutableContext *IMutableContext::currentContext = nullptr; + IMutableContext* IMutableContext::currentContext = nullptr; - void IMutableContext::createContext() - { - currentContext = new Context(); - } + void IMutableContext::createContext() { currentContext = new Context(); } void cleanUpContext() { delete IMutableContext::currentContext; @@ -10346,7 +11723,7 @@ return s_rng; } -} +} // namespace Catch // end catch_context.cpp // start catch_debug_console.cpp @@ -10355,35 +11732,35 @@ #include <string> namespace Catch { - void writeToDebugConsole( std::string const& text ); + void writeToDebugConsole(std::string const& text); } // end catch_debug_console.h #if defined(CATCH_CONFIG_ANDROID_LOGWRITE) #include <android/log.h> - namespace Catch { - void writeToDebugConsole( std::string const& text ) { - __android_log_write( ANDROID_LOG_DEBUG, "Catch", text.c_str() ); - } +namespace Catch { + void writeToDebugConsole(std::string const& text) { + __android_log_write(ANDROID_LOG_DEBUG, "Catch", text.c_str()); } +} // namespace Catch #elif defined(CATCH_PLATFORM_WINDOWS) - namespace Catch { - void writeToDebugConsole( std::string const& text ) { - ::OutputDebugStringA( text.c_str() ); - } +namespace Catch { + void writeToDebugConsole(std::string const& text) { + ::OutputDebugStringA(text.c_str()); } +} // namespace Catch #else - namespace Catch { - void writeToDebugConsole( std::string const& text ) { - // !TBD: Need a version for Mac/ XCode and other IDEs - Catch::cout() << text; - } +namespace Catch { + void writeToDebugConsole(std::string const& text) { + // !TBD: Need a version for Mac/ XCode and other IDEs + Catch::cout() << text; } +} // namespace Catch #endif // Platform // end catch_debug_console.cpp @@ -10391,111 +11768,111 @@ #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE) -# include <cassert> -# include <sys/types.h> -# include <unistd.h> -# include <cstddef> -# include <ostream> +#include <cassert> +#include <sys/types.h> +#include <unistd.h> +#include <cstddef> +#include <ostream> #ifdef __apple_build_version__ - // These headers will only compile with AppleClang (XCode) - // For other compilers (Clang, GCC, ... ) we need to exclude them -# include <sys/sysctl.h> +// These headers will only compile with AppleClang (XCode) +// For other compilers (Clang, GCC, ... ) we need to exclude them +#include <sys/sysctl.h> #endif - namespace Catch { - #ifdef __apple_build_version__ - // The following function is taken directly from the following technical note: - // https://developer.apple.com/library/archive/qa/qa1361/_index.html +namespace Catch { +#ifdef __apple_build_version__ + // The following function is taken directly from the following technical + // note: https://developer.apple.com/library/archive/qa/qa1361/_index.html - // Returns true if the current process is being debugged (either - // running under the debugger or has a debugger attached post facto). - bool isDebuggerActive(){ - int mib[4]; - struct kinfo_proc info; - std::size_t size; + // Returns true if the current process is being debugged (either + // running under the debugger or has a debugger attached post facto). + bool isDebuggerActive() { + int mib[4]; + struct kinfo_proc info; + std::size_t size; - // Initialize the flags so that, if sysctl fails for some bizarre - // reason, we get a predictable result. + // Initialize the flags so that, if sysctl fails for some bizarre + // reason, we get a predictable result. - info.kp_proc.p_flag = 0; + 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. + // 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(); + mib[0] = CTL_KERN; + mib[1] = KERN_PROC; + mib[2] = KERN_PROC_PID; + mib[3] = getpid(); - // Call sysctl. + // Call sysctl. - size = sizeof(info); - if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) { - Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl; - return false; - } - - // We're being debugged if the P_TRACED flag is set. - - return ( (info.kp_proc.p_flag & P_TRACED) != 0 ); - } - #else - bool isDebuggerActive() { - // We need to find another way to determine this for non-appleclang compilers on macOS + size = sizeof(info); + if (sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != + 0) { + Catch::cerr() << "\n** Call to sysctl failed - unable to determine " + "if debugger is active **\n" + << std::endl; return false; } - #endif - } // namespace Catch -#elif defined(CATCH_PLATFORM_LINUX) - #include <fstream> - #include <string> + // We're being debugged if the P_TRACED flag is set. - namespace Catch{ - // The standard POSIX way of detecting a debugger is to attempt to - // ptrace() the process, but this needs to be done from a child and not - // this process itself to still allow attaching to this process later - // if wanted, so is rather heavy. Under Linux we have the PID of the - // "debugger" (which doesn't need to be gdb, of course, it could also - // be strace, for example) in /proc/$PID/status, so just get it from - // there instead. - bool isDebuggerActive(){ - // Libstdc++ has a bug, where std::ifstream sets errno to 0 - // This way our users can properly assert over errno values - ErrnoGuard guard; - std::ifstream in("/proc/self/status"); - for( std::string line; std::getline(in, line); ) { - static const int PREFIX_LEN = 11; - if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) { - // We're traced if the PID is not 0 and no other PID starts - // with 0 digit, so it's enough to check for just a single - // character. - return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0'; - } - } - - return false; - } - } // namespace Catch -#elif defined(_MSC_VER) - extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); - namespace Catch { - bool isDebuggerActive() { - return IsDebuggerPresent() != 0; - } - } -#elif defined(__MINGW32__) - extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); - namespace Catch { - bool isDebuggerActive() { - return IsDebuggerPresent() != 0; - } + return ((info.kp_proc.p_flag & P_TRACED) != 0); } #else - namespace Catch { - bool isDebuggerActive() { return false; } + bool isDebuggerActive() { + // We need to find another way to determine this for non-appleclang + // compilers on macOS + return false; } +#endif +} // namespace Catch + +#elif defined(CATCH_PLATFORM_LINUX) +#include <fstream> +#include <string> + +namespace Catch { + // The standard POSIX way of detecting a debugger is to attempt to + // ptrace() the process, but this needs to be done from a child and not + // this process itself to still allow attaching to this process later + // if wanted, so is rather heavy. Under Linux we have the PID of the + // "debugger" (which doesn't need to be gdb, of course, it could also + // be strace, for example) in /proc/$PID/status, so just get it from + // there instead. + bool isDebuggerActive() { + // Libstdc++ has a bug, where std::ifstream sets errno to 0 + // This way our users can properly assert over errno values + ErrnoGuard guard; + std::ifstream in("/proc/self/status"); + for (std::string line; std::getline(in, line);) { + static const int PREFIX_LEN = 11; + if (line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0) { + // We're traced if the PID is not 0 and no other PID starts + // with 0 digit, so it's enough to check for just a single + // character. + return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0'; + } + } + + return false; + } +} // namespace Catch +#elif defined(_MSC_VER) +extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); +namespace Catch { + bool isDebuggerActive() { return IsDebuggerPresent() != 0; } +} // namespace Catch +#elif defined(__MINGW32__) +extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); +namespace Catch { + bool isDebuggerActive() { return IsDebuggerPresent() != 0; } +} // namespace Catch +#else +namespace Catch { + bool isDebuggerActive() { return false; } +} // namespace Catch #endif // Platform // end catch_debugger.cpp // start catch_decomposer.cpp @@ -10504,46 +11881,47 @@ ITransientExpression::~ITransientExpression() = default; - void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) { - if( lhs.size() + rhs.size() < 40 && - lhs.find('\n') == std::string::npos && - rhs.find('\n') == std::string::npos ) + void formatReconstructedExpression(std::ostream& os, + std::string const& lhs, + StringRef op, + std::string const& rhs) { + if (lhs.size() + rhs.size() < 40 && + lhs.find('\n') == std::string::npos && + rhs.find('\n') == std::string::npos) os << lhs << " " << op << " " << rhs; else os << lhs << "\n" << op << "\n" << rhs; } -} +} // namespace Catch // end catch_decomposer.cpp // start catch_enforce.cpp #include <stdexcept> namespace Catch { -#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER) - [[noreturn]] - void throw_exception(std::exception const& e) { - Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n" - << "The message was: " << e.what() << '\n'; +#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && \ + !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER) + [[noreturn]] void throw_exception(std::exception const& e) { + Catch::cerr() + << "Catch will terminate because it needed to throw an exception.\n" + << "The message was: " << e.what() << '\n'; std::terminate(); } #endif - [[noreturn]] - void throw_logic_error(std::string const& msg) { + [[noreturn]] void throw_logic_error(std::string const& msg) { throw_exception(std::logic_error(msg)); } - [[noreturn]] - void throw_domain_error(std::string const& msg) { + [[noreturn]] void throw_domain_error(std::string const& msg) { throw_exception(std::domain_error(msg)); } - [[noreturn]] - void throw_runtime_error(std::string const& msg) { + [[noreturn]] void throw_runtime_error(std::string const& msg) { throw_exception(std::runtime_error(msg)); } -} // namespace Catch; +} // namespace Catch // end catch_enforce.cpp // start catch_enum_values_registry.cpp // start catch_enum_values_registry.h @@ -10555,20 +11933,25 @@ namespace Detail { - std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ); + std::unique_ptr<EnumInfo> makeEnumInfo(StringRef enumName, + StringRef allValueNames, + std::vector<int> const& values); class EnumValuesRegistry : public IMutableEnumValuesRegistry { std::vector<std::unique_ptr<EnumInfo>> m_enumInfos; - EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override; + EnumInfo const& + registerEnum(StringRef enumName, + StringRef allEnums, + std::vector<int> const& values) override; }; - std::vector<StringRef> parseEnums( StringRef enums ); + std::vector<StringRef> parseEnums(StringRef enums); - } // Detail + } // namespace Detail -} // Catch +} // namespace Catch // end catch_enum_values_registry.h @@ -10583,22 +11966,24 @@ namespace { // Extracts the actual name part of an enum instance - // In other words, it returns the Blue part of Bikeshed::Colour::Blue + // In other words, it returns the Blue part of + // Bikeshed::Colour::Blue StringRef extractInstanceName(StringRef enumInstance) { // Find last occurrence of ":" size_t name_start = enumInstance.size(); while (name_start > 0 && enumInstance[name_start - 1] != ':') { --name_start; } - return enumInstance.substr(name_start, enumInstance.size() - name_start); + return enumInstance.substr(name_start, + enumInstance.size() - name_start); } - } + } // namespace - std::vector<StringRef> parseEnums( StringRef enums ) { - auto enumValues = splitStringRef( enums, ',' ); + std::vector<StringRef> parseEnums(StringRef enums) { + auto enumValues = splitStringRef(enums, ','); std::vector<StringRef> parsed; - parsed.reserve( enumValues.size() ); - for( auto const& enumValue : enumValues ) { + parsed.reserve(enumValues.size()); + for (auto const& enumValue : enumValues) { parsed.push_back(trim(extractInstanceName(enumValue))); } return parsed; @@ -10606,35 +11991,41 @@ EnumInfo::~EnumInfo() {} - StringRef EnumInfo::lookup( int value ) const { - for( auto const& valueToName : m_values ) { - if( valueToName.first == value ) + StringRef EnumInfo::lookup(int value) const { + for (auto const& valueToName : m_values) { + if (valueToName.first == value) return valueToName.second; } return "{** unexpected enum value **}"_sr; } - std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) { - std::unique_ptr<EnumInfo> enumInfo( new EnumInfo ); + std::unique_ptr<EnumInfo> makeEnumInfo(StringRef enumName, + StringRef allValueNames, + std::vector<int> const& values) { + std::unique_ptr<EnumInfo> enumInfo(new EnumInfo); enumInfo->m_name = enumName; - enumInfo->m_values.reserve( values.size() ); + enumInfo->m_values.reserve(values.size()); - const auto valueNames = Catch::Detail::parseEnums( allValueNames ); - assert( valueNames.size() == values.size() ); + const auto valueNames = Catch::Detail::parseEnums(allValueNames); + assert(valueNames.size() == values.size()); std::size_t i = 0; - for( auto value : values ) + for (auto value : values) enumInfo->m_values.emplace_back(value, valueNames[i++]); return enumInfo; } - EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) { - m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values)); + EnumInfo const& + EnumValuesRegistry::registerEnum(StringRef enumName, + StringRef allValueNames, + std::vector<int> const& values) { + m_enumInfos.push_back( + makeEnumInfo(enumName, allValueNames, values)); return *m_enumInfos.back(); } - } // Detail -} // Catch + } // namespace Detail +} // namespace Catch // end catch_enum_values_registry.cpp // start catch_errno_guard.cpp @@ -10642,9 +12033,9 @@ #include <cerrno> namespace Catch { - ErrnoGuard::ErrnoGuard():m_oldErrno(errno){} - ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; } -} + ErrnoGuard::ErrnoGuard() : m_oldErrno(errno) {} + ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; } +} // namespace Catch // end catch_errno_guard.cpp // start catch_exception_translator_registry.cpp @@ -10659,14 +12050,14 @@ class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry { public: ~ExceptionTranslatorRegistry(); - virtual void registerTranslator( const IExceptionTranslator* translator ); + virtual void registerTranslator(const IExceptionTranslator* translator); std::string translateActiveException() const override; std::string tryTranslators() const; private: std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators; }; -} +} // namespace Catch // end catch_exception_translator_registry.h #ifdef __OBJC__ @@ -10675,11 +12066,12 @@ namespace Catch { - ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() { - } + ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {} - void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) { - m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) ); + void ExceptionTranslatorRegistry::registerTranslator( + const IExceptionTranslator* translator) { + m_translators.push_back( + std::unique_ptr<const IExceptionTranslator>(translator)); } #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) @@ -10687,11 +12079,12 @@ try { #ifdef __OBJC__ // In Objective-C try objective-c exceptions first - @try { + @try + { return tryTranslators(); - } - @catch (NSException *exception) { - return Catch::Detail::stringify( [exception description] ); + } @catch (NSException* exception) + { + return Catch::Detail::stringify([exception description]); } #else // Compiling a mixed mode project with MSVC means that CLR @@ -10707,20 +12100,15 @@ } return tryTranslators(); #endif - } - catch( TestFailureException& ) { + } catch (TestFailureException&) { std::rethrow_exception(std::current_exception()); - } - catch( std::exception& ex ) { + } catch (std::exception& ex) { return ex.what(); - } - catch( std::string& msg ) { + } catch (std::string& msg) { return msg; - } - catch( const char* msg ) { + } catch (const char* msg) { return msg; - } - catch(...) { + } catch (...) { return "Unknown exception"; } } @@ -10729,27 +12117,30 @@ if (m_translators.empty()) { std::rethrow_exception(std::current_exception()); } else { - return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end()); + return m_translators[0]->translate(m_translators.begin() + 1, + m_translators.end()); } } #else // ^^ Exceptions are enabled // Exceptions are disabled vv std::string ExceptionTranslatorRegistry::translateActiveException() const { - CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!"); + CATCH_INTERNAL_ERROR("Attempted to translate active exception under " + "CATCH_CONFIG_DISABLE_EXCEPTIONS!"); } std::string ExceptionTranslatorRegistry::tryTranslators() const { - CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!"); + CATCH_INTERNAL_ERROR("Attempted to use exception translators under " + "CATCH_CONFIG_DISABLE_EXCEPTIONS!"); } #endif -} +} // namespace Catch // end catch_exception_translator_registry.cpp // start catch_fatal_condition.cpp #include <algorithm> -#if !defined( CATCH_CONFIG_WINDOWS_SEH ) && !defined( CATCH_CONFIG_POSIX_SIGNALS ) +#if !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_POSIX_SIGNALS) namespace Catch { @@ -10764,16 +12155,19 @@ #endif // !CATCH_CONFIG_WINDOWS_SEH && !CATCH_CONFIG_POSIX_SIGNALS -#if defined( CATCH_CONFIG_WINDOWS_SEH ) && defined( CATCH_CONFIG_POSIX_SIGNALS ) -#error "Inconsistent configuration: Windows' SEH handling and POSIX signals cannot be enabled at the same time" +#if defined(CATCH_CONFIG_WINDOWS_SEH) && defined(CATCH_CONFIG_POSIX_SIGNALS) +#error \ + "Inconsistent configuration: Windows' SEH handling and POSIX signals cannot be enabled at the same time" #endif // CATCH_CONFIG_WINDOWS_SEH && CATCH_CONFIG_POSIX_SIGNALS -#if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS ) +#if defined(CATCH_CONFIG_WINDOWS_SEH) || defined(CATCH_CONFIG_POSIX_SIGNALS) namespace { //! Signals fatal error message to the run context - void reportFatal( char const * const message ) { - Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message ); + void reportFatal(char const* const message) { + Catch::getCurrentContext() + .getResultCapture() + ->handleFatalErrorCondition(message); } //! Minimal size Catch2 needs for its own fatal error handling. @@ -10784,23 +12178,31 @@ #endif // CATCH_CONFIG_WINDOWS_SEH || CATCH_CONFIG_POSIX_SIGNALS -#if defined( CATCH_CONFIG_WINDOWS_SEH ) +#if defined(CATCH_CONFIG_WINDOWS_SEH) namespace Catch { - struct SignalDefs { DWORD id; const char* name; }; + struct SignalDefs { + DWORD id; + const char* name; + }; // There is no 1-1 mapping between signals and windows exceptions. // Windows can easily distinguish between SO and SigSegV, // but SigInt, SigTerm, etc are handled differently. static SignalDefs signalDefs[] = { - { static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal" }, - { static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" }, - { static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" }, - { static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" }, + {static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), + "SIGILL - Illegal instruction signal"}, + {static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), + "SIGSEGV - Stack overflow"}, + {static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), + "SIGSEGV - Segmentation violation signal"}, + {static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), + "Divide by zero error"}, }; - static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) { + static LONG CALLBACK + handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) { for (auto const& def : signalDefs) { if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) { reportFatal(def.name); @@ -10835,15 +12237,18 @@ void FatalConditionHandler::engage_platform() { // Register as first handler in current chain - exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException); + exceptionHandlerHandle = + AddVectoredExceptionHandler(1, handleVectoredException); if (!exceptionHandlerHandle) { - CATCH_RUNTIME_ERROR("Could not register vectored exception handler"); + CATCH_RUNTIME_ERROR( + "Could not register vectored exception handler"); } } void FatalConditionHandler::disengage_platform() { if (!RemoveVectoredExceptionHandler(exceptionHandlerHandle)) { - CATCH_RUNTIME_ERROR("Could not unregister vectored exception handler"); + CATCH_RUNTIME_ERROR( + "Could not unregister vectored exception handler"); } exceptionHandlerHandle = nullptr; } @@ -10852,7 +12257,7 @@ #endif // CATCH_CONFIG_WINDOWS_SEH -#if defined( CATCH_CONFIG_POSIX_SIGNALS ) +#if defined(CATCH_CONFIG_POSIX_SIGNALS) #include <signal.h> @@ -10864,41 +12269,42 @@ }; static SignalDefs signalDefs[] = { - { SIGINT, "SIGINT - Terminal interrupt signal" }, - { SIGILL, "SIGILL - Illegal instruction signal" }, - { SIGFPE, "SIGFPE - Floating point error signal" }, - { SIGSEGV, "SIGSEGV - Segmentation violation signal" }, - { SIGTERM, "SIGTERM - Termination request signal" }, - { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" } - }; + {SIGINT, "SIGINT - Terminal interrupt signal"}, + {SIGILL, "SIGILL - Illegal instruction signal"}, + {SIGFPE, "SIGFPE - Floating point error signal"}, + {SIGSEGV, "SIGSEGV - Segmentation violation signal"}, + {SIGTERM, "SIGTERM - Termination request signal"}, + {SIGABRT, "SIGABRT - Abort (abnormal termination) signal"}}; // Older GCCs trigger -Wmissing-field-initializers for T foo = {} // which is zero initialization, but not explicit. We want to avoid // that. #if defined(__GNUC__) -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wmissing-field-initializers" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wmissing-field-initializers" #endif static char* altStackMem = nullptr; static std::size_t altStackSize = 0; static stack_t oldSigStack{}; - static struct sigaction oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)]{}; + static struct sigaction + oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)]{}; static void restorePreviousSignalHandlers() { // We set signal handlers back to the previous ones. Hopefully // nobody overwrote them in the meantime, and doesn't expect // their signal handlers to live past ours given that they // installed them after ours.. - for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) { + for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); + ++i) { sigaction(signalDefs[i].id, &oldSigActions[i], nullptr); } // Return the old stack sigaltstack(&oldSigStack, nullptr); } - static void handleSignal( int sig ) { - char const * name = "<unknown signal>"; + static void handleSignal(int sig) { + char const* name = "<unknown signal>"; for (auto const& def : signalDefs) { if (sig == def.id) { name = def.name; @@ -10909,14 +12315,17 @@ // their thing, so that the users can have the debugger break // when a signal is raised, and so on. restorePreviousSignalHandlers(); - reportFatal( name ); - raise( sig ); + reportFatal(name); + raise(sig); } FatalConditionHandler::FatalConditionHandler() { - assert(!altStackMem && "Cannot initialize POSIX signal handler when one already exists"); + assert( + !altStackMem && + "Cannot initialize POSIX signal handler when one already exists"); if (altStackSize == 0) { - altStackSize = std::max(static_cast<size_t>(SIGSTKSZ), minStackSizeForErrors); + altStackSize = + std::max(static_cast<size_t>(SIGSTKSZ), minStackSizeForErrors); } altStackMem = new char[altStackSize](); } @@ -10934,17 +12343,18 @@ sigStack.ss_size = altStackSize; sigStack.ss_flags = 0; sigaltstack(&sigStack, &oldSigStack); - struct sigaction sa = { }; + struct sigaction sa = {}; sa.sa_handler = handleSignal; sa.sa_flags = SA_ONSTACK; - for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) { + for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); + ++i) { sigaction(signalDefs[i].id, &sa, &oldSigActions[i]); } } #if defined(__GNUC__) -# pragma GCC diagnostic pop +#pragma GCC diagnostic pop #endif void FatalConditionHandler::disengage_platform() { @@ -10962,21 +12372,22 @@ namespace Catch { -IGeneratorTracker::~IGeneratorTracker() {} + IGeneratorTracker::~IGeneratorTracker() {} -const char* GeneratorException::what() const noexcept { - return m_msg; -} + const char* GeneratorException::what() const noexcept { return m_msg; } -namespace Generators { + namespace Generators { - GeneratorUntypedBase::~GeneratorUntypedBase() {} + GeneratorUntypedBase::~GeneratorUntypedBase() {} - auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& { - return getResultCapture().acquireGeneratorTracker( generatorName, lineInfo ); - } + auto acquireGeneratorTracker(StringRef generatorName, + SourceLineInfo const& lineInfo) + -> IGeneratorTracker& { + return getResultCapture().acquireGeneratorTracker(generatorName, + lineInfo); + } -} // namespace Generators + } // namespace Generators } // namespace Catch // end catch_generators.cpp // start catch_interfaces_capture.cpp @@ -10996,14 +12407,14 @@ namespace Catch { IExceptionTranslator::~IExceptionTranslator() = default; IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default; -} +} // namespace Catch // end catch_interfaces_exception.cpp // start catch_interfaces_registry_hub.cpp namespace Catch { IRegistryHub::~IRegistryHub() = default; IMutableRegistryHub::~IMutableRegistryHub() = default; -} +} // namespace Catch // end catch_interfaces_registry_hub.cpp // start catch_interfaces_reporter.cpp @@ -11020,42 +12431,40 @@ public: ListeningReporter(); - void addListener( IStreamingReporterPtr&& listener ); - void addReporter( IStreamingReporterPtr&& reporter ); + void addListener(IStreamingReporterPtr&& listener); + void addReporter(IStreamingReporterPtr&& reporter); public: // IStreamingReporter - ReporterPreferences getPreferences() const override; - void noMatchingTestCases( std::string const& spec ) override; + void noMatchingTestCases(std::string const& spec) override; - void reportInvalidArguments(std::string const&arg) override; + void reportInvalidArguments(std::string const& arg) override; static std::set<Verbosity> getSupportedVerbosities(); #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) void benchmarkPreparing(std::string const& name) override; - void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override; - void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override; + void benchmarkStarting(BenchmarkInfo const& benchmarkInfo) override; + void benchmarkEnded(BenchmarkStats<> const& benchmarkStats) override; void benchmarkFailed(std::string const&) override; #endif // CATCH_CONFIG_ENABLE_BENCHMARKING - void testRunStarting( TestRunInfo const& testRunInfo ) override; - void testGroupStarting( GroupInfo const& groupInfo ) override; - void testCaseStarting( TestCaseInfo const& testInfo ) override; - void sectionStarting( SectionInfo const& sectionInfo ) override; - void assertionStarting( AssertionInfo const& assertionInfo ) override; + void testRunStarting(TestRunInfo const& testRunInfo) override; + void testGroupStarting(GroupInfo const& groupInfo) override; + void testCaseStarting(TestCaseInfo const& testInfo) override; + void sectionStarting(SectionInfo const& sectionInfo) override; + void assertionStarting(AssertionInfo const& assertionInfo) override; // The return value indicates if the messages buffer should be cleared: - bool assertionEnded( AssertionStats const& assertionStats ) override; - void sectionEnded( SectionStats const& sectionStats ) override; - void testCaseEnded( TestCaseStats const& testCaseStats ) override; - void testGroupEnded( TestGroupStats const& testGroupStats ) override; - void testRunEnded( TestRunStats const& testRunStats ) override; + bool assertionEnded(AssertionStats const& assertionStats) override; + void sectionEnded(SectionStats const& sectionStats) override; + void testCaseEnded(TestCaseStats const& testCaseStats) override; + void testGroupEnded(TestGroupStats const& testGroupStats) override; + void testRunEnded(TestRunStats const& testRunStats) override; - void skipTest( TestCaseInfo const& testInfo ) override; + void skipTest(TestCaseInfo const& testInfo) override; bool isMulti() const override; - }; } // end namespace Catch @@ -11063,99 +12472,90 @@ // end catch_reporter_listening.h namespace Catch { - ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig ) - : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {} + ReporterConfig::ReporterConfig(IConfigPtr const& _fullConfig) : + m_stream(&_fullConfig->stream()), m_fullConfig(_fullConfig) {} - ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream ) - : m_stream( &_stream ), m_fullConfig( _fullConfig ) {} + ReporterConfig::ReporterConfig(IConfigPtr const& _fullConfig, + std::ostream& _stream) : + m_stream(&_stream), m_fullConfig(_fullConfig) {} std::ostream& ReporterConfig::stream() const { return *m_stream; } IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; } - TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {} + TestRunInfo::TestRunInfo(std::string const& _name) : name(_name) {} - GroupInfo::GroupInfo( std::string const& _name, - std::size_t _groupIndex, - std::size_t _groupsCount ) - : name( _name ), - groupIndex( _groupIndex ), - groupsCounts( _groupsCount ) - {} + GroupInfo::GroupInfo(std::string const& _name, + std::size_t _groupIndex, + std::size_t _groupsCount) : + name(_name), groupIndex(_groupIndex), groupsCounts(_groupsCount) {} - AssertionStats::AssertionStats( AssertionResult const& _assertionResult, - std::vector<MessageInfo> const& _infoMessages, - Totals const& _totals ) - : assertionResult( _assertionResult ), - infoMessages( _infoMessages ), - totals( _totals ) - { - assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression; + AssertionStats::AssertionStats( + AssertionResult const& _assertionResult, + std::vector<MessageInfo> const& _infoMessages, + Totals const& _totals) : + assertionResult(_assertionResult), + infoMessages(_infoMessages), + totals(_totals) { + assertionResult.m_resultData.lazyExpression.m_transientExpression = + _assertionResult.m_resultData.lazyExpression.m_transientExpression; - if( assertionResult.hasMessage() ) { + if (assertionResult.hasMessage()) { // Copy message into messages list. // !TBD This should have been done earlier, somewhere - MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() ); + MessageBuilder builder(assertionResult.getTestMacroName(), + assertionResult.getSourceInfo(), + assertionResult.getResultType()); builder << assertionResult.getMessage(); builder.m_info.message = builder.m_stream.str(); - infoMessages.push_back( builder.m_info ); + infoMessages.push_back(builder.m_info); } } - AssertionStats::~AssertionStats() = default; + AssertionStats::~AssertionStats() = default; - SectionStats::SectionStats( SectionInfo const& _sectionInfo, - Counts const& _assertions, - double _durationInSeconds, - bool _missingAssertions ) - : sectionInfo( _sectionInfo ), - assertions( _assertions ), - durationInSeconds( _durationInSeconds ), - missingAssertions( _missingAssertions ) - {} + SectionStats::SectionStats(SectionInfo const& _sectionInfo, + Counts const& _assertions, + double _durationInSeconds, + bool _missingAssertions) : + sectionInfo(_sectionInfo), + assertions(_assertions), + durationInSeconds(_durationInSeconds), + missingAssertions(_missingAssertions) {} SectionStats::~SectionStats() = default; - TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo, - Totals const& _totals, - std::string const& _stdOut, - std::string const& _stdErr, - bool _aborting ) - : testInfo( _testInfo ), - totals( _totals ), - stdOut( _stdOut ), - stdErr( _stdErr ), - aborting( _aborting ) - {} + TestCaseStats::TestCaseStats(TestCaseInfo const& _testInfo, + Totals const& _totals, + std::string const& _stdOut, + std::string const& _stdErr, + bool _aborting) : + testInfo(_testInfo), + totals(_totals), + stdOut(_stdOut), + stdErr(_stdErr), + aborting(_aborting) {} TestCaseStats::~TestCaseStats() = default; - TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo, - Totals const& _totals, - bool _aborting ) - : groupInfo( _groupInfo ), - totals( _totals ), - aborting( _aborting ) - {} + TestGroupStats::TestGroupStats(GroupInfo const& _groupInfo, + Totals const& _totals, + bool _aborting) : + groupInfo(_groupInfo), totals(_totals), aborting(_aborting) {} - TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo ) - : groupInfo( _groupInfo ), - aborting( false ) - {} + TestGroupStats::TestGroupStats(GroupInfo const& _groupInfo) : + groupInfo(_groupInfo), aborting(false) {} TestGroupStats::~TestGroupStats() = default; - TestRunStats::TestRunStats( TestRunInfo const& _runInfo, - Totals const& _totals, - bool _aborting ) - : runInfo( _runInfo ), - totals( _totals ), - aborting( _aborting ) - {} + TestRunStats::TestRunStats(TestRunInfo const& _runInfo, + Totals const& _totals, + bool _aborting) : + runInfo(_runInfo), totals(_totals), aborting(_aborting) {} TestRunStats::~TestRunStats() = default; - void IStreamingReporter::fatalErrorEncountered( StringRef ) {} + void IStreamingReporter::fatalErrorEncountered(StringRef) {} bool IStreamingReporter::isMulti() const { return false; } IReporterFactory::~IReporterFactory() = default; @@ -11174,7 +12574,7 @@ namespace Catch { ITestInvoker::~ITestInvoker() = default; ITestCaseRegistry::~ITestCaseRegistry() = default; -} +} // namespace Catch // end catch_interfaces_testcase.cpp // start catch_leak_detector.cpp @@ -11193,17 +12593,15 @@ // Change this to leaking allocation's number to break there _CrtSetBreakAlloc(-1); } -} +} // namespace Catch #else - Catch::LeakDetector::LeakDetector() {} +Catch::LeakDetector::LeakDetector() {} #endif -Catch::LeakDetector::~LeakDetector() { - Catch::cleanUp(); -} +Catch::LeakDetector::~LeakDetector() { Catch::cleanUp(); } // end catch_leak_detector.cpp // start catch_list.cpp @@ -11213,23 +12611,23 @@ namespace Catch { - std::size_t listTests( Config const& config ); + std::size_t listTests(Config const& config); - std::size_t listTestsNamesOnly( Config const& config ); + std::size_t listTestsNamesOnly(Config const& config); struct TagInfo { - void add( std::string const& spelling ); + void add(std::string const& spelling); std::string all() const; std::set<std::string> spellings; std::size_t count = 0; }; - std::size_t listTags( Config const& config ); + std::size_t listTags(Config const& config); std::size_t listReporters(); - Option<std::size_t> list( std::shared_ptr<Config> const& config ); + Option<std::size_t> list(std::shared_ptr<Config> const& config); } // end namespace Catch @@ -11247,60 +12645,71 @@ namespace Catch { - std::size_t listTests( Config const& config ) { + std::size_t listTests(Config const& config) { TestSpec const& testSpec = config.testSpec(); - if( config.hasTestFilters() ) + if (config.hasTestFilters()) Catch::cout() << "Matching test cases:\n"; else { Catch::cout() << "All available test cases:\n"; } - auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); - for( auto const& testCaseInfo : matchedTestCases ) { - Colour::Code colour = testCaseInfo.isHidden() - ? Colour::SecondaryText - : Colour::None; - Colour colourGuard( colour ); + auto matchedTestCases = + filterTests(getAllTestCasesSorted(config), testSpec, config); + for (auto const& testCaseInfo : matchedTestCases) { + Colour::Code colour = + testCaseInfo.isHidden() ? Colour::SecondaryText : Colour::None; + Colour colourGuard(colour); - Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n"; - if( config.verbosity() >= Verbosity::High ) { - Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl; + Catch::cout() + << Column(testCaseInfo.name).initialIndent(2).indent(4) << "\n"; + if (config.verbosity() >= Verbosity::High) { + Catch::cout() + << Column(Catch::Detail::stringify(testCaseInfo.lineInfo)) + .indent(4) + << std::endl; std::string description = testCaseInfo.description; - if( description.empty() ) + if (description.empty()) description = "(NO DESCRIPTION)"; - Catch::cout() << Column( description ).indent(4) << std::endl; + Catch::cout() << Column(description).indent(4) << std::endl; } - if( !testCaseInfo.tags.empty() ) - Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n"; + if (!testCaseInfo.tags.empty()) + Catch::cout() + << Column(testCaseInfo.tagsAsString()).indent(6) << "\n"; } - if( !config.hasTestFilters() ) - Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl; + if (!config.hasTestFilters()) + Catch::cout() << pluralise(matchedTestCases.size(), "test case") + << '\n' + << std::endl; else - Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl; + Catch::cout() << pluralise(matchedTestCases.size(), + "matching test case") + << '\n' + << std::endl; return matchedTestCases.size(); } - std::size_t listTestsNamesOnly( Config const& config ) { + std::size_t listTestsNamesOnly(Config const& config) { TestSpec const& testSpec = config.testSpec(); std::size_t matchedTests = 0; - std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); - for( auto const& testCaseInfo : matchedTestCases ) { + std::vector<TestCase> matchedTestCases = + filterTests(getAllTestCasesSorted(config), testSpec, config); + for (auto const& testCaseInfo : matchedTestCases) { matchedTests++; - if( startsWith( testCaseInfo.name, '#' ) ) - Catch::cout() << '"' << testCaseInfo.name << '"'; + if (startsWith(testCaseInfo.name, '#')) + Catch::cout() << '"' << testCaseInfo.name << '"'; else - Catch::cout() << testCaseInfo.name; - if ( config.verbosity() >= Verbosity::High ) + Catch::cout() << testCaseInfo.name; + if (config.verbosity() >= Verbosity::High) Catch::cout() << "\t@" << testCaseInfo.lineInfo; Catch::cout() << std::endl; } return matchedTests; } - void TagInfo::add( std::string const& spelling ) { + void TagInfo::add(std::string const& spelling) { ++count; - spellings.insert( spelling ); + spellings.insert(spelling); } std::string TagInfo::all() const { @@ -11310,7 +12719,8 @@ size += spelling.size() + 2; } - std::string out; out.reserve(size); + std::string out; + out.reserve(size); for (auto const& spelling : spellings) { out += '['; out += spelling; @@ -11319,9 +12729,9 @@ return out; } - std::size_t listTags( Config const& config ) { + std::size_t listTags(Config const& config) { TestSpec const& testSpec = config.testSpec(); - if( config.hasTestFilters() ) + if (config.hasTestFilters()) Catch::cout() << "Tags for matching test cases:\n"; else { Catch::cout() << "All available tags:\n"; @@ -11329,63 +12739,69 @@ std::map<std::string, TagInfo> tagCounts; - std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); - for( auto const& testCase : matchedTestCases ) { - for( auto const& tagName : testCase.getTestCaseInfo().tags ) { - std::string lcaseTagName = toLower( tagName ); - auto countIt = tagCounts.find( lcaseTagName ); - if( countIt == tagCounts.end() ) - countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first; - countIt->second.add( tagName ); + std::vector<TestCase> matchedTestCases = + filterTests(getAllTestCasesSorted(config), testSpec, config); + for (auto const& testCase : matchedTestCases) { + for (auto const& tagName : testCase.getTestCaseInfo().tags) { + std::string lcaseTagName = toLower(tagName); + auto countIt = tagCounts.find(lcaseTagName); + if (countIt == tagCounts.end()) + countIt = + tagCounts + .insert(std::make_pair(lcaseTagName, TagInfo())) + .first; + countIt->second.add(tagName); } } - for( auto const& tagCount : tagCounts ) { + for (auto const& tagCount : tagCounts) { ReusableStringStream rss; rss << " " << std::setw(2) << tagCount.second.count << " "; auto str = rss.str(); - auto wrapper = Column( tagCount.second.all() ) - .initialIndent( 0 ) - .indent( str.size() ) - .width( CATCH_CONFIG_CONSOLE_WIDTH-10 ); + auto wrapper = Column(tagCount.second.all()) + .initialIndent(0) + .indent(str.size()) + .width(CATCH_CONFIG_CONSOLE_WIDTH - 10); Catch::cout() << str << wrapper << '\n'; } - Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl; + Catch::cout() << pluralise(tagCounts.size(), "tag") << '\n' + << std::endl; return tagCounts.size(); } std::size_t listReporters() { Catch::cout() << "Available reporters:\n"; - IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories(); + IReporterRegistry::FactoryMap const& factories = + getRegistryHub().getReporterRegistry().getFactories(); std::size_t maxNameLen = 0; - for( auto const& factoryKvp : factories ) - maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() ); + for (auto const& factoryKvp : factories) + maxNameLen = (std::max)(maxNameLen, factoryKvp.first.size()); - for( auto const& factoryKvp : factories ) { - Catch::cout() - << Column( factoryKvp.first + ":" ) - .indent(2) - .width( 5+maxNameLen ) - + Column( factoryKvp.second->getDescription() ) - .initialIndent(0) - .indent(2) - .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 ) - << "\n"; + for (auto const& factoryKvp : factories) { + Catch::cout() << Column(factoryKvp.first + ":") + .indent(2) + .width(5 + maxNameLen) + + Column(factoryKvp.second->getDescription()) + .initialIndent(0) + .indent(2) + .width(CATCH_CONFIG_CONSOLE_WIDTH - + maxNameLen - 8) + << "\n"; } Catch::cout() << std::endl; return factories.size(); } - Option<std::size_t> list( std::shared_ptr<Config> const& config ) { + Option<std::size_t> list(std::shared_ptr<Config> const& config) { Option<std::size_t> listedCount; - getCurrentMutableContext().setConfig( config ); - if( config->listTests() ) - listedCount = listedCount.valueOr(0) + listTests( *config ); - if( config->listTestNamesOnly() ) - listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config ); - if( config->listTags() ) - listedCount = listedCount.valueOr(0) + listTags( *config ); - if( config->listReporters() ) + getCurrentMutableContext().setConfig(config); + if (config->listTests()) + listedCount = listedCount.valueOr(0) + listTests(*config); + if (config->listTestNamesOnly()) + listedCount = listedCount.valueOr(0) + listTestsNamesOnly(*config); + if (config->listTags()) + listedCount = listedCount.valueOr(0) + listTags(*config); + if (config->listReporters()) listedCount = listedCount.valueOr(0) + listReporters(); return listedCount; } @@ -11395,46 +12811,47 @@ // start catch_matchers.cpp namespace Catch { -namespace Matchers { - namespace Impl { + namespace Matchers { + namespace Impl { - std::string MatcherUntypedBase::toString() const { - if( m_cachedToString.empty() ) - m_cachedToString = describe(); - return m_cachedToString; - } + std::string MatcherUntypedBase::toString() const { + if (m_cachedToString.empty()) + m_cachedToString = describe(); + return m_cachedToString; + } - MatcherUntypedBase::~MatcherUntypedBase() = default; + MatcherUntypedBase::~MatcherUntypedBase() = default; - } // namespace Impl -} // namespace Matchers + } // namespace Impl + } // namespace Matchers -using namespace Matchers; -using Matchers::Impl::MatcherBase; + using namespace Matchers; + using Matchers::Impl::MatcherBase; } // namespace Catch // end catch_matchers.cpp // start catch_matchers_exception.cpp namespace Catch { -namespace Matchers { -namespace Exception { + namespace Matchers { + namespace Exception { -bool ExceptionMessageMatcher::match(std::exception const& ex) const { - return ex.what() == m_message; -} + bool + ExceptionMessageMatcher::match(std::exception const& ex) const { + return ex.what() == m_message; + } -std::string ExceptionMessageMatcher::describe() const { - return "exception message matches \"" + m_message + "\""; -} + std::string ExceptionMessageMatcher::describe() const { + return "exception message matches \"" + m_message + "\""; + } -} -Exception::ExceptionMessageMatcher Message(std::string const& message) { - return Exception::ExceptionMessageMatcher(message); -} + } // namespace Exception + Exception::ExceptionMessageMatcher Message(std::string const& message) { + return Exception::ExceptionMessageMatcher(message); + } -// namespace Exception -} // namespace Matchers + // namespace Exception + } // namespace Matchers } // namespace Catch // end catch_matchers_exception.cpp // start catch_matchers_floating.cpp @@ -11444,7 +12861,7 @@ namespace Catch { bool isnan(float f); bool isnan(double d); -} +} // namespace Catch // end catch_polyfills.hpp // start catch_to_string.hpp @@ -11452,8 +12869,7 @@ #include <string> namespace Catch { - template <typename T> - std::string to_string(T const& t) { + template <typename T> std::string to_string(T const& t) { #if defined(CATCH_CONFIG_CPP11_TO_STRING) return std::to_string(t); #else @@ -11476,112 +12892,114 @@ #include <limits> namespace Catch { -namespace { + namespace { - int32_t convert(float f) { - static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated"); - int32_t i; - std::memcpy(&i, &f, sizeof(f)); - return i; - } - - int64_t convert(double d) { - static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated"); - int64_t i; - std::memcpy(&i, &d, sizeof(d)); - return i; - } - - template <typename FP> - bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) { - // Comparison with NaN should always be false. - // This way we can rule it out before getting into the ugly details - if (Catch::isnan(lhs) || Catch::isnan(rhs)) { - return false; + int32_t convert(float f) { + static_assert(sizeof(float) == sizeof(int32_t), + "Important ULP matcher assumption violated"); + int32_t i; + std::memcpy(&i, &f, sizeof(f)); + return i; } - auto lc = convert(lhs); - auto rc = convert(rhs); - - if ((lc < 0) != (rc < 0)) { - // Potentially we can have +0 and -0 - return lhs == rhs; + int64_t convert(double d) { + static_assert(sizeof(double) == sizeof(int64_t), + "Important ULP matcher assumption violated"); + int64_t i; + std::memcpy(&i, &d, sizeof(d)); + return i; } - // static cast as a workaround for IBM XLC - auto ulpDiff = std::abs(static_cast<FP>(lc - rc)); - return static_cast<uint64_t>(ulpDiff) <= maxUlpDiff; - } + template <typename FP> + bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) { + // Comparison with NaN should always be false. + // This way we can rule it out before getting into the ugly details + if (Catch::isnan(lhs) || Catch::isnan(rhs)) { + return false; + } + + auto lc = convert(lhs); + auto rc = convert(rhs); + + if ((lc < 0) != (rc < 0)) { + // Potentially we can have +0 and -0 + return lhs == rhs; + } + + // static cast as a workaround for IBM XLC + auto ulpDiff = std::abs(static_cast<FP>(lc - rc)); + return static_cast<uint64_t>(ulpDiff) <= maxUlpDiff; + } #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) - float nextafter(float x, float y) { - return ::nextafterf(x, y); - } + float nextafter(float x, float y) { return ::nextafterf(x, y); } - double nextafter(double x, double y) { - return ::nextafter(x, y); - } + double nextafter(double x, double y) { return ::nextafter(x, y); } #endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^ -template <typename FP> -FP step(FP start, FP direction, uint64_t steps) { - for (uint64_t i = 0; i < steps; ++i) { + template <typename FP> FP step(FP start, FP direction, uint64_t steps) { + for (uint64_t i = 0; i < steps; ++i) { #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) - start = Catch::nextafter(start, direction); + start = Catch::nextafter(start, direction); #else - start = std::nextafter(start, direction); + start = std::nextafter(start, direction); #endif - } - return start; -} + } + return start; + } -// Performs equivalent check of std::fabs(lhs - rhs) <= margin -// But without the subtraction to allow for INFINITY in comparison -bool marginComparison(double lhs, double rhs, double margin) { - return (lhs + margin >= rhs) && (rhs + margin >= lhs); -} + // Performs equivalent check of std::fabs(lhs - rhs) <= margin + // But without the subtraction to allow for INFINITY in comparison + bool marginComparison(double lhs, double rhs, double margin) { + return (lhs + margin >= rhs) && (rhs + margin >= lhs); + } -template <typename FloatingPoint> -void write(std::ostream& out, FloatingPoint num) { - out << std::scientific - << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1) - << num; -} + template <typename FloatingPoint> + void write(std::ostream& out, FloatingPoint num) { + out << std::scientific + << std::setprecision( + std::numeric_limits<FloatingPoint>::max_digits10 - 1) + << num; + } -} // end anonymous namespace + } // end anonymous namespace -namespace Matchers { -namespace Floating { + namespace Matchers { + namespace Floating { - enum class FloatingPointKind : uint8_t { - Float, - Double - }; + enum class FloatingPointKind : uint8_t { Float, Double }; - WithinAbsMatcher::WithinAbsMatcher(double target, double margin) - :m_target{ target }, m_margin{ margin } { - CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.' - << " Margin has to be non-negative."); - } + WithinAbsMatcher::WithinAbsMatcher(double target, double margin) : + m_target{target}, m_margin{margin} { + CATCH_ENFORCE(margin >= 0, + "Invalid margin: " + << margin << '.' + << " Margin has to be non-negative."); + } - // Performs equivalent check of std::fabs(lhs - rhs) <= margin - // But without the subtraction to allow for INFINITY in comparison - bool WithinAbsMatcher::match(double const& matchee) const { - return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee); - } + // Performs equivalent check of std::fabs(lhs - rhs) <= margin + // But without the subtraction to allow for INFINITY in comparison + bool WithinAbsMatcher::match(double const& matchee) const { + return (matchee + m_margin >= m_target) && + (m_target + m_margin >= matchee); + } - std::string WithinAbsMatcher::describe() const { - return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target); - } + std::string WithinAbsMatcher::describe() const { + return "is within " + ::Catch::Detail::stringify(m_margin) + + " of " + ::Catch::Detail::stringify(m_target); + } - WithinUlpsMatcher::WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType) - :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } { - CATCH_ENFORCE(m_type == FloatingPointKind::Double - || m_ulps < (std::numeric_limits<uint32_t>::max)(), - "Provided ULP is impossibly large for a float comparison."); - } + WithinUlpsMatcher::WithinUlpsMatcher(double target, + uint64_t ulps, + FloatingPointKind baseType) : + m_target{target}, m_ulps{ulps}, m_type{baseType} { + CATCH_ENFORCE( + m_type == FloatingPointKind::Double || + m_ulps < (std::numeric_limits<uint32_t>::max)(), + "Provided ULP is impossibly large for a float comparison."); + } #if defined(__clang__) #pragma clang diagnostic push @@ -11589,104 +13007,132 @@ #pragma clang diagnostic ignored "-Wunreachable-code" #endif - bool WithinUlpsMatcher::match(double const& matchee) const { - switch (m_type) { - case FloatingPointKind::Float: - return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps); - case FloatingPointKind::Double: - return almostEqualUlps<double>(matchee, m_target, m_ulps); - default: - CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" ); - } - } + bool WithinUlpsMatcher::match(double const& matchee) const { + switch (m_type) { + case FloatingPointKind::Float: + return almostEqualUlps<float>( + static_cast<float>(matchee), + static_cast<float>(m_target), + m_ulps); + case FloatingPointKind::Double: + return almostEqualUlps<double>( + matchee, m_target, m_ulps); + default: + CATCH_INTERNAL_ERROR("Unknown FloatingPointKind value"); + } + } #if defined(__clang__) #pragma clang diagnostic pop #endif - std::string WithinUlpsMatcher::describe() const { - std::stringstream ret; + std::string WithinUlpsMatcher::describe() const { + std::stringstream ret; - ret << "is within " << m_ulps << " ULPs of "; + ret << "is within " << m_ulps << " ULPs of "; - if (m_type == FloatingPointKind::Float) { - write(ret, static_cast<float>(m_target)); - ret << 'f'; - } else { - write(ret, m_target); + if (m_type == FloatingPointKind::Float) { + write(ret, static_cast<float>(m_target)); + ret << 'f'; + } else { + write(ret, m_target); + } + + ret << " (["; + if (m_type == FloatingPointKind::Double) { + write( + ret, + step(m_target, static_cast<double>(-INFINITY), m_ulps)); + ret << ", "; + write( + ret, + step(m_target, static_cast<double>(INFINITY), m_ulps)); + } else { + // We have to cast INFINITY to float because of MinGW, see + // #1782 + write(ret, + step(static_cast<float>(m_target), + static_cast<float>(-INFINITY), + m_ulps)); + ret << ", "; + write(ret, + step(static_cast<float>(m_target), + static_cast<float>(INFINITY), + m_ulps)); + } + ret << "])"; + + return ret.str(); + } + + WithinRelMatcher::WithinRelMatcher(double target, double epsilon) : + m_target(target), m_epsilon(epsilon) { + CATCH_ENFORCE(m_epsilon >= 0., + "Relative comparison with epsilon < 0 does not " + "make sense."); + CATCH_ENFORCE(m_epsilon < 1., + "Relative comparison with epsilon >= 1 does not " + "make sense."); + } + + bool WithinRelMatcher::match(double const& matchee) const { + const auto relMargin = + m_epsilon * + (std::max)(std::fabs(matchee), std::fabs(m_target)); + return marginComparison( + matchee, m_target, std::isinf(relMargin) ? 0 : relMargin); + } + + std::string WithinRelMatcher::describe() const { + Catch::ReusableStringStream sstr; + sstr << "and " << m_target << " are within " << m_epsilon * 100. + << "% of each other"; + return sstr.str(); + } + + } // namespace Floating + + Floating::WithinUlpsMatcher WithinULP(double target, + uint64_t maxUlpDiff) { + return Floating::WithinUlpsMatcher( + target, maxUlpDiff, Floating::FloatingPointKind::Double); } - ret << " (["; - if (m_type == FloatingPointKind::Double) { - write(ret, step(m_target, static_cast<double>(-INFINITY), m_ulps)); - ret << ", "; - write(ret, step(m_target, static_cast<double>( INFINITY), m_ulps)); - } else { - // We have to cast INFINITY to float because of MinGW, see #1782 - write(ret, step(static_cast<float>(m_target), static_cast<float>(-INFINITY), m_ulps)); - ret << ", "; - write(ret, step(static_cast<float>(m_target), static_cast<float>( INFINITY), m_ulps)); + Floating::WithinUlpsMatcher WithinULP(float target, + uint64_t maxUlpDiff) { + return Floating::WithinUlpsMatcher( + target, maxUlpDiff, Floating::FloatingPointKind::Float); } - ret << "])"; - return ret.str(); - } + Floating::WithinAbsMatcher WithinAbs(double target, double margin) { + return Floating::WithinAbsMatcher(target, margin); + } - WithinRelMatcher::WithinRelMatcher(double target, double epsilon): - m_target(target), - m_epsilon(epsilon){ - CATCH_ENFORCE(m_epsilon >= 0., "Relative comparison with epsilon < 0 does not make sense."); - CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense."); - } + Floating::WithinRelMatcher WithinRel(double target, double eps) { + return Floating::WithinRelMatcher(target, eps); + } - bool WithinRelMatcher::match(double const& matchee) const { - const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target)); - return marginComparison(matchee, m_target, - std::isinf(relMargin)? 0 : relMargin); - } + Floating::WithinRelMatcher WithinRel(double target) { + return Floating::WithinRelMatcher( + target, std::numeric_limits<double>::epsilon() * 100); + } - std::string WithinRelMatcher::describe() const { - Catch::ReusableStringStream sstr; - sstr << "and " << m_target << " are within " << m_epsilon * 100. << "% of each other"; - return sstr.str(); - } + Floating::WithinRelMatcher WithinRel(float target, float eps) { + return Floating::WithinRelMatcher(target, eps); + } -}// namespace Floating + Floating::WithinRelMatcher WithinRel(float target) { + return Floating::WithinRelMatcher( + target, std::numeric_limits<float>::epsilon() * 100); + } -Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) { - return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double); -} - -Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) { - return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float); -} - -Floating::WithinAbsMatcher WithinAbs(double target, double margin) { - return Floating::WithinAbsMatcher(target, margin); -} - -Floating::WithinRelMatcher WithinRel(double target, double eps) { - return Floating::WithinRelMatcher(target, eps); -} - -Floating::WithinRelMatcher WithinRel(double target) { - return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100); -} - -Floating::WithinRelMatcher WithinRel(float target, float eps) { - return Floating::WithinRelMatcher(target, eps); -} - -Floating::WithinRelMatcher WithinRel(float target) { - return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100); -} - -} // namespace Matchers + } // namespace Matchers } // namespace Catch // end catch_matchers_floating.cpp // start catch_matchers_generic.cpp -std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) { +std::string +Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) { if (desc.empty()) { return "matches undescribed predicate"; } else { @@ -11699,101 +13145,127 @@ #include <regex> namespace Catch { -namespace Matchers { + namespace Matchers { - namespace StdString { + namespace StdString { - CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity ) - : m_caseSensitivity( caseSensitivity ), - m_str( adjustString( str ) ) - {} - std::string CasedString::adjustString( std::string const& str ) const { - return m_caseSensitivity == CaseSensitive::No - ? toLower( str ) - : str; - } - std::string CasedString::caseSensitivitySuffix() const { - return m_caseSensitivity == CaseSensitive::No - ? " (case insensitive)" - : std::string(); - } - - StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator ) - : m_comparator( comparator ), - m_operation( operation ) { - } - - std::string StringMatcherBase::describe() const { - std::string description; - description.reserve(5 + m_operation.size() + m_comparator.m_str.size() + - m_comparator.caseSensitivitySuffix().size()); - description += m_operation; - description += ": \""; - description += m_comparator.m_str; - description += "\""; - description += m_comparator.caseSensitivitySuffix(); - return description; - } - - EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {} - - bool EqualsMatcher::match( std::string const& source ) const { - return m_comparator.adjustString( source ) == m_comparator.m_str; - } - - ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {} - - bool ContainsMatcher::match( std::string const& source ) const { - return contains( m_comparator.adjustString( source ), m_comparator.m_str ); - } - - StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {} - - bool StartsWithMatcher::match( std::string const& source ) const { - return startsWith( m_comparator.adjustString( source ), m_comparator.m_str ); - } - - EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {} - - bool EndsWithMatcher::match( std::string const& source ) const { - return endsWith( m_comparator.adjustString( source ), m_comparator.m_str ); - } - - RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {} - - bool RegexMatcher::match(std::string const& matchee) const { - auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway - if (m_caseSensitivity == CaseSensitive::Choice::No) { - flags |= std::regex::icase; + CasedString::CasedString(std::string const& str, + CaseSensitive::Choice caseSensitivity) : + m_caseSensitivity(caseSensitivity), m_str(adjustString(str)) {} + std::string + CasedString::adjustString(std::string const& str) const { + return m_caseSensitivity == CaseSensitive::No ? toLower(str) + : str; } - auto reg = std::regex(m_regex, flags); - return std::regex_match(matchee, reg); + std::string CasedString::caseSensitivitySuffix() const { + return m_caseSensitivity == CaseSensitive::No + ? " (case insensitive)" + : std::string(); + } + + StringMatcherBase::StringMatcherBase( + std::string const& operation, CasedString const& comparator) : + m_comparator(comparator), m_operation(operation) {} + + std::string StringMatcherBase::describe() const { + std::string description; + description.reserve( + 5 + m_operation.size() + m_comparator.m_str.size() + + m_comparator.caseSensitivitySuffix().size()); + description += m_operation; + description += ": \""; + description += m_comparator.m_str; + description += "\""; + description += m_comparator.caseSensitivitySuffix(); + return description; + } + + EqualsMatcher::EqualsMatcher(CasedString const& comparator) : + StringMatcherBase("equals", comparator) {} + + bool EqualsMatcher::match(std::string const& source) const { + return m_comparator.adjustString(source) == m_comparator.m_str; + } + + ContainsMatcher::ContainsMatcher(CasedString const& comparator) : + StringMatcherBase("contains", comparator) {} + + bool ContainsMatcher::match(std::string const& source) const { + return contains(m_comparator.adjustString(source), + m_comparator.m_str); + } + + StartsWithMatcher::StartsWithMatcher( + CasedString const& comparator) : + StringMatcherBase("starts with", comparator) {} + + bool StartsWithMatcher::match(std::string const& source) const { + return startsWith(m_comparator.adjustString(source), + m_comparator.m_str); + } + + EndsWithMatcher::EndsWithMatcher(CasedString const& comparator) : + StringMatcherBase("ends with", comparator) {} + + bool EndsWithMatcher::match(std::string const& source) const { + return endsWith(m_comparator.adjustString(source), + m_comparator.m_str); + } + + RegexMatcher::RegexMatcher(std::string regex, + CaseSensitive::Choice caseSensitivity) : + m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {} + + bool RegexMatcher::match(std::string const& matchee) const { + auto flags = + std::regex::ECMAScript; // ECMAScript is the default syntax + // option anyway + if (m_caseSensitivity == CaseSensitive::Choice::No) { + flags |= std::regex::icase; + } + auto reg = std::regex(m_regex, flags); + return std::regex_match(matchee, reg); + } + + std::string RegexMatcher::describe() const { + return "matches " + ::Catch::Detail::stringify(m_regex) + + ((m_caseSensitivity == CaseSensitive::Choice::Yes) + ? " case sensitively" + : " case insensitively"); + } + + } // namespace StdString + + StdString::EqualsMatcher Equals(std::string const& str, + CaseSensitive::Choice caseSensitivity) { + return StdString::EqualsMatcher( + StdString::CasedString(str, caseSensitivity)); + } + StdString::ContainsMatcher + Contains(std::string const& str, + CaseSensitive::Choice caseSensitivity) { + return StdString::ContainsMatcher( + StdString::CasedString(str, caseSensitivity)); + } + StdString::EndsWithMatcher + EndsWith(std::string const& str, + CaseSensitive::Choice caseSensitivity) { + return StdString::EndsWithMatcher( + StdString::CasedString(str, caseSensitivity)); + } + StdString::StartsWithMatcher + StartsWith(std::string const& str, + CaseSensitive::Choice caseSensitivity) { + return StdString::StartsWithMatcher( + StdString::CasedString(str, caseSensitivity)); } - std::string RegexMatcher::describe() const { - return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively"); + StdString::RegexMatcher Matches(std::string const& regex, + CaseSensitive::Choice caseSensitivity) { + return StdString::RegexMatcher(regex, caseSensitivity); } - } // namespace StdString - - StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) { - return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) ); - } - StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) { - return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) ); - } - StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) { - return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) ); - } - StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) { - return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) ); - } - - StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) { - return StdString::RegexMatcher(regex, caseSensitivity); - } - -} // namespace Matchers + } // namespace Matchers } // namespace Catch // end catch_matchers_string.cpp // start catch_message.cpp @@ -11810,20 +13282,19 @@ namespace Catch { - MessageInfo::MessageInfo( StringRef const& _macroName, - SourceLineInfo const& _lineInfo, - ResultWas::OfType _type ) - : macroName( _macroName ), - lineInfo( _lineInfo ), - type( _type ), - sequence( ++globalCount ) - {} + MessageInfo::MessageInfo(StringRef const& _macroName, + SourceLineInfo const& _lineInfo, + ResultWas::OfType _type) : + macroName(_macroName), + lineInfo(_lineInfo), + type(_type), + sequence(++globalCount) {} - bool MessageInfo::operator==( MessageInfo const& other ) const { + bool MessageInfo::operator==(MessageInfo const& other) const { return sequence == other.sequence; } - bool MessageInfo::operator<( MessageInfo const& other ) const { + bool MessageInfo::operator<(MessageInfo const& other) const { return sequence < other.sequence; } @@ -11832,44 +13303,47 @@ //////////////////////////////////////////////////////////////////////////// - Catch::MessageBuilder::MessageBuilder( StringRef const& macroName, - SourceLineInfo const& lineInfo, - ResultWas::OfType type ) - :m_info(macroName, lineInfo, type) {} + Catch::MessageBuilder::MessageBuilder(StringRef const& macroName, + SourceLineInfo const& lineInfo, + ResultWas::OfType type) : + m_info(macroName, lineInfo, type) {} //////////////////////////////////////////////////////////////////////////// - ScopedMessage::ScopedMessage( MessageBuilder const& builder ) - : m_info( builder.m_info ), m_moved() - { + ScopedMessage::ScopedMessage(MessageBuilder const& builder) : + m_info(builder.m_info), m_moved() { m_info.message = builder.m_stream.str(); - getResultCapture().pushScopedMessage( m_info ); + getResultCapture().pushScopedMessage(m_info); } - ScopedMessage::ScopedMessage( ScopedMessage&& old ) - : m_info( old.m_info ), m_moved() - { + ScopedMessage::ScopedMessage(ScopedMessage&& old) : + m_info(old.m_info), m_moved() { old.m_moved = true; } ScopedMessage::~ScopedMessage() { - if ( !uncaught_exceptions() && !m_moved ){ + if (!uncaught_exceptions() && !m_moved) { getResultCapture().popScopedMessage(m_info); } } - Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) { - auto trimmed = [&] (size_t start, size_t end) { - while (names[start] == ',' || isspace(static_cast<unsigned char>(names[start]))) { + Capturer::Capturer(StringRef macroName, + SourceLineInfo const& lineInfo, + ResultWas::OfType resultType, + StringRef names) { + auto trimmed = [&](size_t start, size_t end) { + while (names[start] == ',' || + isspace(static_cast<unsigned char>(names[start]))) { ++start; } - while (names[end] == ',' || isspace(static_cast<unsigned char>(names[end]))) { + while (names[end] == ',' || + isspace(static_cast<unsigned char>(names[end]))) { --end; } return names.substr(start, end - start + 1); }; - auto skipq = [&] (size_t start, char quote) { - for (auto i = start + 1; i < names.size() ; ++i) { + auto skipq = [&](size_t start, char quote) { + for (auto i = start + 1; i < names.size(); ++i) { if (names[i] == quote) return i; if (names[i] == '\\') @@ -11883,50 +13357,53 @@ for (size_t pos = 0; pos < names.size(); ++pos) { char c = names[pos]; switch (c) { - case '[': - case '{': - case '(': - // It is basically impossible to disambiguate between - // comparison and start of template args in this context -// case '<': - openings.push(c); - break; - case ']': - case '}': - case ')': -// case '>': - openings.pop(); - break; - case '"': - case '\'': - pos = skipq(pos, c); - break; - case ',': - if (start != pos && openings.empty()) { - m_messages.emplace_back(macroName, lineInfo, resultType); - m_messages.back().message = static_cast<std::string>(trimmed(start, pos)); - m_messages.back().message += " := "; - start = pos; - } + case '[': + case '{': + case '(': + // It is basically impossible to disambiguate between + // comparison and start of template args in this context + // case '<': + openings.push(c); + break; + case ']': + case '}': + case ')': + // case '>': + openings.pop(); + break; + case '"': + case '\'': + pos = skipq(pos, c); + break; + case ',': + if (start != pos && openings.empty()) { + m_messages.emplace_back( + macroName, lineInfo, resultType); + m_messages.back().message = + static_cast<std::string>(trimmed(start, pos)); + m_messages.back().message += " := "; + start = pos; + } } } assert(openings.empty() && "Mismatched openings"); m_messages.emplace_back(macroName, lineInfo, resultType); - m_messages.back().message = static_cast<std::string>(trimmed(start, names.size() - 1)); + m_messages.back().message = + static_cast<std::string>(trimmed(start, names.size() - 1)); m_messages.back().message += " := "; } Capturer::~Capturer() { - if ( !uncaught_exceptions() ){ - assert( m_captured == m_messages.size() ); - for( size_t i = 0; i < m_captured; ++i ) - m_resultCapture.popScopedMessage( m_messages[i] ); + if (!uncaught_exceptions()) { + assert(m_captured == m_messages.size()); + for (size_t i = 0; i < m_captured; ++i) + m_resultCapture.popScopedMessage(m_messages[i]); } } - void Capturer::captureValue( size_t index, std::string const& value ) { - assert( index < m_messages.size() ); + void Capturer::captureValue(size_t index, std::string const& value) { + assert(index < m_messages.size()); m_messages[index].message += value; - m_resultCapture.pushScopedMessage( m_messages[index] ); + m_resultCapture.pushScopedMessage(m_messages[index]); m_captured++; } @@ -11950,13 +13427,15 @@ std::streambuf* m_prevBuf; public: - RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream ); + RedirectedStream(std::ostream& originalStream, + std::ostream& redirectionStream); ~RedirectedStream(); }; class RedirectedStdOut { ReusableStringStream m_rss; RedirectedStream m_cout; + public: RedirectedStdOut(); auto str() const -> std::string; @@ -11969,6 +13448,7 @@ ReusableStringStream m_rss; RedirectedStream m_cerr; RedirectedStream m_clog; + public: RedirectedStdErr(); auto str() const -> std::string; @@ -11981,8 +13461,10 @@ RedirectedStreams(RedirectedStreams&&) = delete; RedirectedStreams& operator=(RedirectedStreams&&) = delete; - RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr); + RedirectedStreams(std::string& redirectedCout, + std::string& redirectedCerr); ~RedirectedStreams(); + private: std::string& m_redirectedCout; std::string& m_redirectedCerr; @@ -12011,9 +13493,9 @@ private: std::FILE* m_file = nullptr; - #if defined(_MSC_VER) - char m_buffer[L_tmpnam] = { 0 }; - #endif +#if defined(_MSC_VER) + char m_buffer[L_tmpnam] = {0}; +#endif }; class OutputRedirect { @@ -12048,43 +13530,39 @@ #include <stdexcept> #if defined(CATCH_CONFIG_NEW_CAPTURE) - #if defined(_MSC_VER) - #include <io.h> //_dup and _dup2 - #define dup _dup - #define dup2 _dup2 - #define fileno _fileno - #else - #include <unistd.h> // dup and dup2 - #endif +#if defined(_MSC_VER) +#include <io.h> //_dup and _dup2 +#define dup _dup +#define dup2 _dup2 +#define fileno _fileno +#else +#include <unistd.h> // dup and dup2 +#endif #endif namespace Catch { - RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream ) - : m_originalStream( originalStream ), - m_redirectionStream( redirectionStream ), - m_prevBuf( m_originalStream.rdbuf() ) - { - m_originalStream.rdbuf( m_redirectionStream.rdbuf() ); + RedirectedStream::RedirectedStream(std::ostream& originalStream, + std::ostream& redirectionStream) : + m_originalStream(originalStream), + m_redirectionStream(redirectionStream), + m_prevBuf(m_originalStream.rdbuf()) { + m_originalStream.rdbuf(m_redirectionStream.rdbuf()); } - RedirectedStream::~RedirectedStream() { - m_originalStream.rdbuf( m_prevBuf ); - } + RedirectedStream::~RedirectedStream() { m_originalStream.rdbuf(m_prevBuf); } - RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {} + RedirectedStdOut::RedirectedStdOut() : m_cout(Catch::cout(), m_rss.get()) {} auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); } - RedirectedStdErr::RedirectedStdErr() - : m_cerr( Catch::cerr(), m_rss.get() ), - m_clog( Catch::clog(), m_rss.get() ) - {} + RedirectedStdErr::RedirectedStdErr() : + m_cerr(Catch::cerr(), m_rss.get()), + m_clog(Catch::clog(), m_rss.get()) {} auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); } - RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr) - : m_redirectedCout(redirectedCout), - m_redirectedCerr(redirectedCerr) - {} + RedirectedStreams::RedirectedStreams(std::string& redirectedCout, + std::string& redirectedCerr) : + m_redirectedCout(redirectedCout), m_redirectedCerr(redirectedCerr) {} RedirectedStreams::~RedirectedStreams() { m_redirectedCout += m_redirectedStdOut.str(); @@ -12103,7 +13581,8 @@ if (strerror_s(buffer, errno)) { CATCH_RUNTIME_ERROR("Could not translate errno to a string"); } - CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer); + CATCH_RUNTIME_ERROR("Could not open the temp file: '" + << m_buffer << "' because: " << buffer); } } #else @@ -12117,18 +13596,16 @@ #endif TempFile::~TempFile() { - // TBD: What to do about errors here? - std::fclose(m_file); - // We manually create the file on Windows only, on Linux - // it will be autodeleted + // TBD: What to do about errors here? + std::fclose(m_file); + // We manually create the file on Windows only, on Linux + // it will be autodeleted #if defined(_MSC_VER) - std::remove(m_buffer); + std::remove(m_buffer); #endif } - FILE* TempFile::getFile() { - return m_file; - } + FILE* TempFile::getFile() { return m_file; } std::string TempFile::getContents() { std::stringstream sstr; @@ -12140,7 +13617,8 @@ return sstr.str(); } - OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) : + OutputRedirect::OutputRedirect(std::string& stdout_dest, + std::string& stderr_dest) : m_originalStdout(dup(1)), m_originalStderr(dup(2)), m_stdoutDest(stdout_dest), @@ -12170,11 +13648,11 @@ } // namespace Catch #if defined(CATCH_CONFIG_NEW_CAPTURE) - #if defined(_MSC_VER) - #undef dup - #undef dup2 - #undef fileno - #endif +#if defined(_MSC_VER) +#undef dup +#undef dup2 +#undef fileno +#endif #endif // end catch_output_redirect.cpp // start catch_polyfills.cpp @@ -12184,20 +13662,12 @@ namespace Catch { #if !defined(CATCH_CONFIG_POLYFILL_ISNAN) - bool isnan(float f) { - return std::isnan(f); - } - bool isnan(double d) { - return std::isnan(d); - } + bool isnan(float f) { return std::isnan(f); } + bool isnan(double d) { return std::isnan(d); } #else // For now we only use this for embarcadero - bool isnan(float f) { - return std::_isnan(f); - } - bool isnan(double d) { - return std::_isnan(d); - } + bool isnan(float f) { return std::_isnan(f); } + bool isnan(double d) { return std::_isnan(d); } #endif } // end namespace Catch @@ -12206,11 +13676,11 @@ namespace Catch { -namespace { + namespace { #if defined(_MSC_VER) #pragma warning(push) -#pragma warning(disable:4146) // we negate uint32 during the rotate +#pragma warning(disable : 4146) // we negate uint32 during the rotate #endif // Safe rotr implementation thanks to John Regehr uint32_t rotate_right(uint32_t val, uint32_t count) { @@ -12223,11 +13693,9 @@ #pragma warning(pop) #endif -} + } // namespace - SimplePcg32::SimplePcg32(result_type seed_) { - seed(seed_); - } + SimplePcg32::SimplePcg32(result_type seed_) { seed(seed_); } void SimplePcg32::seed(result_type seed_) { m_state = 0; @@ -12246,7 +13714,8 @@ SimplePcg32::result_type SimplePcg32::operator()() { // prepare the output value - const uint32_t xorshifted = static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u); + const uint32_t xorshifted = + static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u); const auto output = rotate_right(xorshifted, m_state >> 59u); // advance state @@ -12262,7 +13731,7 @@ bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs) { return lhs.m_state != rhs.m_state; } -} +} // namespace Catch // end catch_random_number_generator.cpp // start catch_registry_hub.cpp @@ -12278,44 +13747,54 @@ class TestCase; struct IConfig; - std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ); + std::vector<TestCase> + sortTests(IConfig const& config, + std::vector<TestCase> const& unsortedTestCases); - bool isThrowSafe( TestCase const& testCase, IConfig const& config ); - bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ); + bool isThrowSafe(TestCase const& testCase, IConfig const& config); + bool matchTest(TestCase const& testCase, + TestSpec const& testSpec, + IConfig const& config); - void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ); + void enforceNoDuplicateTestCases(std::vector<TestCase> const& functions); - std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ); - std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ); + std::vector<TestCase> filterTests(std::vector<TestCase> const& testCases, + TestSpec const& testSpec, + IConfig const& config); + std::vector<TestCase> const& getAllTestCasesSorted(IConfig const& config); class TestRegistry : public ITestCaseRegistry { public: virtual ~TestRegistry() = default; - virtual void registerTest( TestCase const& testCase ); + virtual void registerTest(TestCase const& testCase); std::vector<TestCase> const& getAllTests() const override; - std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override; + std::vector<TestCase> const& + getAllTestsSorted(IConfig const& config) const override; private: std::vector<TestCase> m_functions; - mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder; + mutable RunTests::InWhatOrder m_currentSortOrder = + RunTests::InDeclarationOrder; mutable std::vector<TestCase> m_sortedFunctions; std::size_t m_unnamedCount = 0; - std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised + std::ios_base::Init + m_ostreamInit; // Forces cout/ cerr to be initialised }; /////////////////////////////////////////////////////////////////////////// class TestInvokerAsFunction : public ITestInvoker { - void(*m_testAsFunction)(); + void (*m_testAsFunction)(); + public: - TestInvokerAsFunction( void(*testAsFunction)() ) noexcept; + TestInvokerAsFunction(void (*testAsFunction)()) noexcept; void invoke() const override; }; - std::string extractClassName( StringRef const& classOrQualifiedMethodName ); + std::string extractClassName(StringRef const& classOrQualifiedMethodName); /////////////////////////////////////////////////////////////////////////// @@ -12331,13 +13810,14 @@ class ReporterRegistry : public IReporterRegistry { public: - ~ReporterRegistry() override; - IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override; + IStreamingReporterPtr create(std::string const& name, + IConfigPtr const& config) const override; - void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ); - void registerListener( IReporterFactoryPtr const& factory ); + void registerReporter(std::string const& name, + IReporterFactoryPtr const& factory); + void registerListener(IReporterFactoryPtr const& factory); FactoryMap const& getFactories() const override; Listeners const& getListeners() const override; @@ -12346,7 +13826,7 @@ FactoryMap m_factories; Listeners m_listeners; }; -} +} // namespace Catch // end catch_reporter_registry.h // start catch_tag_alias_registry.h @@ -12374,9 +13854,12 @@ class TagAliasRegistry : public ITagAliasRegistry { public: ~TagAliasRegistry() override; - TagAlias const* find( std::string const& alias ) const override; - std::string expandAliases( std::string const& unexpandedTestSpec ) const override; - void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ); + TagAlias const* find(std::string const& alias) const override; + std::string + expandAliases(std::string const& unexpandedTestSpec) const override; + void add(std::string const& alias, + std::string const& tag, + SourceLineInfo const& lineInfo); private: std::map<std::string, TagAlias> m_registry; @@ -12397,6 +13880,7 @@ public: void add(std::exception_ptr const& exception) noexcept; std::vector<std::exception_ptr> const& getExceptions() const noexcept; + private: std::vector<std::exception_ptr> m_exceptions; #endif @@ -12413,25 +13897,25 @@ virtual ~ISingleton(); }; - void addSingleton( ISingleton* singleton ); + void addSingleton(ISingleton* singleton); void cleanupSingletons(); - template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT> + template <typename SingletonImplT, + typename InterfaceT = SingletonImplT, + typename MutableInterfaceT = InterfaceT> class Singleton : SingletonImplT, public ISingleton { static auto getInternal() -> Singleton* { static Singleton* s_instance = nullptr; - if( !s_instance ) { + if (!s_instance) { s_instance = new Singleton; - addSingleton( s_instance ); + addSingleton(s_instance); } return s_instance; } public: - static auto get() -> InterfaceT const& { - return *getInternal(); - } + static auto get() -> InterfaceT const& { return *getInternal(); } static auto getMutable() -> MutableInterfaceT& { return *getInternal(); } @@ -12444,7 +13928,8 @@ namespace { - class RegistryHub : public IRegistryHub, public IMutableRegistryHub, + class RegistryHub : public IRegistryHub, + public IMutableRegistryHub, private NonCopyable { public: // IRegistryHub @@ -12455,40 +13940,48 @@ ITestCaseRegistry const& getTestCaseRegistry() const override { return m_testCaseRegistry; } - IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override { + IExceptionTranslatorRegistry const& + getExceptionTranslatorRegistry() const override { return m_exceptionTranslatorRegistry; } ITagAliasRegistry const& getTagAliasRegistry() const override { return m_tagAliasRegistry; } - StartupExceptionRegistry const& getStartupExceptionRegistry() const override { + StartupExceptionRegistry const& + getStartupExceptionRegistry() const override { return m_exceptionRegistry; } public: // IMutableRegistryHub - void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override { - m_reporterRegistry.registerReporter( name, factory ); + void registerReporter(std::string const& name, + IReporterFactoryPtr const& factory) override { + m_reporterRegistry.registerReporter(name, factory); } - void registerListener( IReporterFactoryPtr const& factory ) override { - m_reporterRegistry.registerListener( factory ); + void registerListener(IReporterFactoryPtr const& factory) override { + m_reporterRegistry.registerListener(factory); } - void registerTest( TestCase const& testInfo ) override { - m_testCaseRegistry.registerTest( testInfo ); + void registerTest(TestCase const& testInfo) override { + m_testCaseRegistry.registerTest(testInfo); } - void registerTranslator( const IExceptionTranslator* translator ) override { - m_exceptionTranslatorRegistry.registerTranslator( translator ); + void registerTranslator( + const IExceptionTranslator* translator) override { + m_exceptionTranslatorRegistry.registerTranslator(translator); } - void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override { - m_tagAliasRegistry.add( alias, tag, lineInfo ); + void registerTagAlias(std::string const& alias, + std::string const& tag, + SourceLineInfo const& lineInfo) override { + m_tagAliasRegistry.add(alias, tag, lineInfo); } void registerStartupException() noexcept override { #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) m_exceptionRegistry.add(std::current_exception()); #else - CATCH_INTERNAL_ERROR("Attempted to register active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!"); + CATCH_INTERNAL_ERROR("Attempted to register active exception " + "under CATCH_CONFIG_DISABLE_EXCEPTIONS!"); #endif } - IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override { + IMutableEnumValuesRegistry& + getMutableEnumValuesRegistry() override { return m_enumValuesRegistry; } @@ -12500,13 +13993,12 @@ StartupExceptionRegistry m_exceptionRegistry; Detail::EnumValuesRegistry m_enumValuesRegistry; }; - } + } // namespace - using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>; + using RegistryHubSingleton = + Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>; - IRegistryHub const& getRegistryHub() { - return RegistryHubSingleton::get(); - } + IRegistryHub const& getRegistryHub() { return RegistryHubSingleton::get(); } IMutableRegistryHub& getMutableRegistryHub() { return RegistryHubSingleton::getMutable(); } @@ -12515,7 +14007,9 @@ cleanUpContext(); } std::string translateActiveException() { - return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException(); + return getRegistryHub() + .getExceptionTranslatorRegistry() + .translateActiveException(); } } // end namespace Catch @@ -12526,46 +14020,56 @@ ReporterRegistry::~ReporterRegistry() = default; - IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const { - auto it = m_factories.find( name ); - if( it == m_factories.end() ) + IStreamingReporterPtr + ReporterRegistry::create(std::string const& name, + IConfigPtr const& config) const { + auto it = m_factories.find(name); + if (it == m_factories.end()) return nullptr; - return it->second->create( ReporterConfig( config ) ); + return it->second->create(ReporterConfig(config)); } - void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) { + void + ReporterRegistry::registerReporter(std::string const& name, + IReporterFactoryPtr const& factory) { m_factories.emplace(name, factory); } - void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) { - m_listeners.push_back( factory ); + void + ReporterRegistry::registerListener(IReporterFactoryPtr const& factory) { + m_listeners.push_back(factory); } - IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const { + IReporterRegistry::FactoryMap const& + ReporterRegistry::getFactories() const { return m_factories; } IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const { return m_listeners; } -} +} // namespace Catch // end catch_reporter_registry.cpp // start catch_result_type.cpp namespace Catch { - bool isOk( ResultWas::OfType resultType ) { - return ( resultType & ResultWas::FailureBit ) == 0; + bool isOk(ResultWas::OfType resultType) { + return (resultType & ResultWas::FailureBit) == 0; } - bool isJustInfo( int flags ) { - return flags == ResultWas::Info; + bool isJustInfo(int flags) { return flags == ResultWas::Info; } + + ResultDisposition::Flags operator|(ResultDisposition::Flags lhs, + ResultDisposition::Flags rhs) { + return static_cast<ResultDisposition::Flags>(static_cast<int>(lhs) | + static_cast<int>(rhs)); } - ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) { - return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) ); + bool shouldContinueOnFailure(int flags) { + return (flags & ResultDisposition::ContinueOnFailure) != 0; } - - bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; } - bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; } + bool shouldSuppressFailure(int flags) { + return (flags & ResultDisposition::SuppressFail) != 0; + } } // end namespace Catch // end catch_result_type.cpp @@ -12578,15 +14082,20 @@ namespace Catch { namespace Generators { - struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker { + struct GeneratorTracker : TestCaseTracking::TrackerBase, + IGeneratorTracker { GeneratorBasePtr m_generator; - GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ) - : TrackerBase( nameAndLocation, ctx, parent ) - {} + GeneratorTracker( + TestCaseTracking::NameAndLocation const& nameAndLocation, + TrackerContext& ctx, + ITracker* parent) : + TrackerBase(nameAndLocation, ctx, parent) {} ~GeneratorTracker(); - static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) { + static GeneratorTracker& + acquire(TrackerContext& ctx, + TestCaseTracking::NameAndLocation const& nameAndLocation) { std::shared_ptr<GeneratorTracker> tracker; ITracker& currentTracker = ctx.currentTracker(); @@ -12602,20 +14111,26 @@ // // without it, the code above creates 5 nested generators. if (currentTracker.nameAndLocation() == nameAndLocation) { - auto thisTracker = currentTracker.parent().findChild(nameAndLocation); + auto thisTracker = + currentTracker.parent().findChild(nameAndLocation); assert(thisTracker); assert(thisTracker->isGeneratorTracker()); - tracker = std::static_pointer_cast<GeneratorTracker>(thisTracker); - } else if ( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) { - assert( childTracker ); - assert( childTracker->isGeneratorTracker() ); - tracker = std::static_pointer_cast<GeneratorTracker>( childTracker ); + tracker = + std::static_pointer_cast<GeneratorTracker>(thisTracker); + } else if (TestCaseTracking::ITrackerPtr childTracker = + currentTracker.findChild(nameAndLocation)) + { + assert(childTracker); + assert(childTracker->isGeneratorTracker()); + tracker = std::static_pointer_cast<GeneratorTracker>( + childTracker); } else { - tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, ¤tTracker ); - currentTracker.addChild( tracker ); + tracker = std::make_shared<GeneratorTracker>( + nameAndLocation, ctx, ¤tTracker); + currentTracker.addChild(tracker); } - if( !tracker->isComplete() ) { + if (!tracker->isComplete()) { tracker->open(); } @@ -12624,9 +14139,7 @@ // TrackerBase interface bool isGeneratorTracker() const override { return true; } - auto hasGenerator() const -> bool override { - return !!m_generator; - } + auto hasGenerator() const -> bool override { return !!m_generator; } void close() override { TrackerBase::close(); // If a generator has a child (it is followed by a section) @@ -12638,16 +14151,16 @@ // doing so would break `GENERATE` _not_ followed by `SECTION`s. const bool should_wait_for_child = [&]() { // No children -> nobody to wait for - if ( m_children.empty() ) { + if (m_children.empty()) { return false; } // If at least one child started executing, don't wait - if ( std::find_if( - m_children.begin(), - m_children.end(), - []( TestCaseTracking::ITrackerPtr tracker ) { - return tracker->hasStarted(); - } ) != m_children.end() ) { + if (std::find_if(m_children.begin(), + m_children.end(), + [](TestCaseTracking::ITrackerPtr tracker) { + return tracker->hasStarted(); + }) != m_children.end()) + { return false; } @@ -12657,27 +14170,26 @@ auto* parent = m_parent; // This is safe: there is always at least one section // tracker in a test case tracking tree - while ( !parent->isSectionTracker() ) { - parent = &( parent->parent() ); + while (!parent->isSectionTracker()) { + parent = &(parent->parent()); } - assert( parent && - "Missing root (test case) level section" ); + assert(parent && "Missing root (test case) level section"); auto const& parentSection = - static_cast<SectionTracker&>( *parent ); + static_cast<SectionTracker&>(*parent); auto const& filters = parentSection.getFilters(); // No filters -> no restrictions on running sections - if ( filters.empty() ) { + if (filters.empty()) { return true; } - for ( auto const& child : m_children ) { - if ( child->isSectionTracker() && - std::find( filters.begin(), - filters.end(), - static_cast<SectionTracker&>( *child ) - .trimmedName() ) != - filters.end() ) { + for (auto const& child : m_children) { + if (child->isSectionTracker() && + std::find(filters.begin(), + filters.end(), + static_cast<SectionTracker&>(*child) + .trimmedName()) != filters.end()) + { return true; } } @@ -12688,9 +14200,10 @@ // has a side-effect, where it consumes generator's current // value, but we do not want to invoke the side-effect if // this generator is still waiting for any child to start. - if ( should_wait_for_child || - ( m_runState == CompletedSuccessfully && - m_generator->next() ) ) { + if (should_wait_for_child || + (m_runState == CompletedSuccessfully && + m_generator->next())) + { m_children.clear(); m_runState = Executing; } @@ -12700,21 +14213,26 @@ auto getGenerator() const -> GeneratorBasePtr const& override { return m_generator; } - void setGenerator( GeneratorBasePtr&& generator ) override { - m_generator = std::move( generator ); + void setGenerator(GeneratorBasePtr&& generator) override { + m_generator = std::move(generator); } }; GeneratorTracker::~GeneratorTracker() {} - } + } // namespace Generators - RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter) - : m_runInfo(_config->name()), + RunContext::RunContext(IConfigPtr const& _config, + IStreamingReporterPtr&& reporter) : + m_runInfo(_config->name()), m_context(getCurrentMutableContext()), m_config(_config), m_reporter(std::move(reporter)), - m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal }, - m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions ) - { + m_lastAssertionInfo{StringRef(), + SourceLineInfo("", 0), + StringRef(), + ResultDisposition::Normal}, + m_includeSuccessfulResults( + m_config->includeSuccessfulResults() || + m_reporter->getPreferences().shouldReportAllAssertions) { m_context.setRunner(this); m_context.setConfig(m_config); m_context.setResultCapture(this); @@ -12725,12 +14243,19 @@ m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting())); } - void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) { - m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount)); + void RunContext::testGroupStarting(std::string const& testSpec, + std::size_t groupIndex, + std::size_t groupsCount) { + m_reporter->testGroupStarting( + GroupInfo(testSpec, groupIndex, groupsCount)); } - void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) { - m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting())); + void RunContext::testGroupEnded(std::string const& testSpec, + Totals const& totals, + std::size_t groupIndex, + std::size_t groupsCount) { + m_reporter->testGroupEnded(TestGroupStats( + GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting())); } Totals RunContext::runTest(TestCase const& testCase) { @@ -12747,10 +14272,14 @@ ITracker& rootTracker = m_trackerContext.startRun(); assert(rootTracker.isSectionTracker()); - static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun()); + static_cast<SectionTracker&>(rootTracker) + .addInitialFilters(m_config->getSectionsToRun()); do { m_trackerContext.startCycle(); - m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo)); + m_testCaseTracker = + &SectionTracker::acquire(m_trackerContext, + TestCaseTracking::NameAndLocation( + testInfo.name, testInfo.lineInfo)); runCurrentTest(redirectedCout, redirectedCerr); } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting()); @@ -12761,11 +14290,8 @@ deltaTotals.testCases.failed++; } m_totals.testCases += deltaTotals.testCases; - m_reporter->testCaseEnded(TestCaseStats(testInfo, - deltaTotals, - redirectedCout, - redirectedCerr, - aborting())); + m_reporter->testCaseEnded(TestCaseStats( + testInfo, deltaTotals, redirectedCout, redirectedCerr, aborting())); m_activeTestCase = nullptr; m_testCaseTracker = nullptr; @@ -12773,32 +14299,29 @@ return deltaTotals; } - IConfigPtr RunContext::config() const { - return m_config; - } + IConfigPtr RunContext::config() const { return m_config; } - IStreamingReporter& RunContext::reporter() const { - return *m_reporter; - } + IStreamingReporter& RunContext::reporter() const { return *m_reporter; } - void RunContext::assertionEnded(AssertionResult const & result) { + void RunContext::assertionEnded(AssertionResult const& result) { if (result.getResultType() == ResultWas::Ok) { m_totals.assertions.passed++; m_lastAssertionPassed = true; } else if (!result.isOk()) { m_lastAssertionPassed = false; - if( m_activeTestCase->getTestCaseInfo().okToFail() ) + if (m_activeTestCase->getTestCaseInfo().okToFail()) m_totals.assertions.failedButOk++; else m_totals.assertions.failed++; - } - else { + } else { m_lastAssertionPassed = true; } - // We have no use for the return value (whether messages should be cleared), because messages were made scoped - // and should be let to clear themselves out. - static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals))); + // We have no use for the return value (whether messages should be + // cleared), because messages were made scoped and should be let to + // clear themselves out. + static_cast<void>(m_reporter->assertionEnded( + AssertionStats(result, m_messages, m_totals))); if (result.getResultType() != ResultWas::Warning) m_messageScopes.clear(); @@ -12809,11 +14332,16 @@ } void RunContext::resetAssertionInfo() { m_lastAssertionInfo.macroName = StringRef(); - m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr; + m_lastAssertionInfo.capturedExpression = + "{Unknown expression after the reported line}"_sr; } - bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) { - ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo)); + bool RunContext::sectionStarted(SectionInfo const& sectionInfo, + Counts& assertions) { + ITracker& sectionTracker = SectionTracker::acquire( + m_trackerContext, + TestCaseTracking::NameAndLocation(sectionInfo.name, + sectionInfo.lineInfo)); if (!sectionTracker.isOpen()) return false; m_activeSections.push_back(§ionTracker); @@ -12826,10 +14354,14 @@ return true; } - auto RunContext::acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& { + auto RunContext::acquireGeneratorTracker(StringRef generatorName, + SourceLineInfo const& lineInfo) + -> IGeneratorTracker& { using namespace Generators; - GeneratorTracker& tracker = GeneratorTracker::acquire(m_trackerContext, - TestCaseTracking::NameAndLocation( static_cast<std::string>(generatorName), lineInfo ) ); + GeneratorTracker& tracker = GeneratorTracker::acquire( + m_trackerContext, + TestCaseTracking::NameAndLocation( + static_cast<std::string>(generatorName), lineInfo)); m_lastAssertionInfo.lineInfo = lineInfo; return tracker; } @@ -12846,7 +14378,7 @@ return true; } - void RunContext::sectionEnded(SectionEndInfo const & endInfo) { + void RunContext::sectionEnded(SectionEndInfo const& endInfo) { Counts assertions = m_totals.assertions - endInfo.prevAssertions; bool missingAssertions = testForMissingAssertions(assertions); @@ -12855,12 +14387,15 @@ m_activeSections.pop_back(); } - m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions)); + m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, + assertions, + endInfo.durationInSeconds, + missingAssertions)); m_messages.clear(); m_messageScopes.clear(); } - void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) { + void RunContext::sectionEndedEarly(SectionEndInfo const& endInfo) { if (m_unfinishedSections.empty()) m_activeSections.back()->fail(); else @@ -12874,36 +14409,37 @@ void RunContext::benchmarkPreparing(std::string const& name) { m_reporter->benchmarkPreparing(name); } - void RunContext::benchmarkStarting( BenchmarkInfo const& info ) { - m_reporter->benchmarkStarting( info ); + void RunContext::benchmarkStarting(BenchmarkInfo const& info) { + m_reporter->benchmarkStarting(info); } - void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) { - m_reporter->benchmarkEnded( stats ); + void RunContext::benchmarkEnded(BenchmarkStats<> const& stats) { + m_reporter->benchmarkEnded(stats); } - void RunContext::benchmarkFailed(std::string const & error) { + void RunContext::benchmarkFailed(std::string const& error) { m_reporter->benchmarkFailed(error); } #endif // CATCH_CONFIG_ENABLE_BENCHMARKING - void RunContext::pushScopedMessage(MessageInfo const & message) { + void RunContext::pushScopedMessage(MessageInfo const& message) { m_messages.push_back(message); } - void RunContext::popScopedMessage(MessageInfo const & message) { - m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end()); + void RunContext::popScopedMessage(MessageInfo const& message) { + m_messages.erase( + std::remove(m_messages.begin(), m_messages.end(), message), + m_messages.end()); } - void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) { - m_messageScopes.emplace_back( builder ); + void RunContext::emplaceUnscopedMessage(MessageBuilder const& builder) { + m_messageScopes.emplace_back(builder); } std::string RunContext::getCurrentTestName() const { - return m_activeTestCase - ? m_activeTestCase->getTestCaseInfo().name - : std::string(); + return m_activeTestCase ? m_activeTestCase->getTestCaseInfo().name + : std::string(); } - const AssertionResult * RunContext::getLastResult() const { + const AssertionResult* RunContext::getLastResult() const { return &(*m_lastResult); } @@ -12911,13 +14447,13 @@ m_shouldReportUnexpected = false; } - void RunContext::handleFatalErrorCondition( StringRef message ) { + void RunContext::handleFatalErrorCondition(StringRef message) { // First notify reporter that bad things happened m_reporter->fatalErrorEncountered(message); - // Don't rebuild the result -- the stringification itself can cause more fatal errors - // Instead, fake a result data. - AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } ); + // Don't rebuild the result -- the stringification itself can cause more + // fatal errors Instead, fake a result data. + AssertionResultData tempResult(ResultWas::FatalErrorCondition, {false}); tempResult.message = static_cast<std::string>(message); AssertionResult result(m_lastAssertionInfo, tempResult); @@ -12925,13 +14461,15 @@ handleUnfinishedSections(); - // Recreate section for test case (as we will lose the one that was in scope) + // Recreate section for test case (as we will lose the one that was in + // scope) auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name); Counts assertions; assertions.failed = 1; - SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false); + SectionStats testCaseSectionStats( + testCaseSection, assertions, 0, false); m_reporter->sectionEnded(testCaseSectionStats); auto const& testInfo = m_activeTestCase->getTestCaseInfo(); @@ -12939,19 +14477,14 @@ Totals deltaTotals; deltaTotals.testCases.failed = 1; deltaTotals.assertions.failed = 1; - m_reporter->testCaseEnded(TestCaseStats(testInfo, - deltaTotals, - std::string(), - std::string(), - false)); + m_reporter->testCaseEnded(TestCaseStats( + testInfo, deltaTotals, std::string(), std::string(), false)); m_totals.testCases.failed++; testGroupEnded(std::string(), m_totals, 1, 1); m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false)); } - bool RunContext::lastAssertionPassed() { - return m_lastAssertionPassed; - } + bool RunContext::lastAssertionPassed() { return m_lastAssertionPassed; } void RunContext::assertionPassed() { m_lastAssertionPassed = true; @@ -12961,17 +14494,22 @@ } bool RunContext::aborting() const { - return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter()); + return m_totals.assertions.failed >= + static_cast<std::size_t>(m_config->abortAfter()); } - void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) { + void RunContext::runCurrentTest(std::string& redirectedCout, + std::string& redirectedCerr) { auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name); m_reporter->sectionStarting(testCaseSection); Counts prevAssertions = m_totals.assertions; double duration = 0; m_shouldReportUnexpected = true; - m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal }; + m_lastAssertionInfo = {"TEST_CASE"_sr, + testCaseInfo.lineInfo, + StringRef(), + ResultDisposition::Normal}; seedRng(*m_config); @@ -12979,7 +14517,8 @@ CATCH_TRY { if (m_reporter->getPreferences().shouldRedirectStdOut) { #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT) - RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr); + RedirectedStreams redirectedStreams(redirectedCout, + redirectedCerr); timer.start(); invokeActiveTestCase(); @@ -12993,14 +14532,19 @@ invokeActiveTestCase(); } duration = timer.getElapsedSeconds(); - } CATCH_CATCH_ANON (TestFailureException&) { + } + CATCH_CATCH_ANON(TestFailureException&) { // This just means the test was aborted due to failure - } CATCH_CATCH_ALL { - // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions - // are reported without translation at the point of origin. - if( m_shouldReportUnexpected ) { + } + CATCH_CATCH_ALL { + // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under + // REQUIRE assertions are reported without translation at the point + // of origin. + if (m_shouldReportUnexpected) { AssertionReaction dummyReaction; - handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction ); + handleUnexpectedInflightException(m_lastAssertionInfo, + translateActiveException(), + dummyReaction); } } Counts assertions = m_totals.assertions - prevAssertions; @@ -13011,7 +14555,8 @@ m_messages.clear(); m_messageScopes.clear(); - SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions); + SectionStats testCaseSectionStats( + testCaseSection, assertions, duration, missingAssertions); m_reporter->sectionEnded(testCaseSectionStats); } @@ -13024,117 +14569,109 @@ // If sections ended prematurely due to an exception we stored their // infos here so we can tear them down outside the unwind process. for (auto it = m_unfinishedSections.rbegin(), - itEnd = m_unfinishedSections.rend(); + itEnd = m_unfinishedSections.rend(); it != itEnd; ++it) sectionEnded(*it); m_unfinishedSections.clear(); } - void RunContext::handleExpr( - AssertionInfo const& info, - ITransientExpression const& expr, - AssertionReaction& reaction - ) { - m_reporter->assertionStarting( info ); + void RunContext::handleExpr(AssertionInfo const& info, + ITransientExpression const& expr, + AssertionReaction& reaction) { + m_reporter->assertionStarting(info); - bool negated = isFalseTest( info.resultDisposition ); + bool negated = isFalseTest(info.resultDisposition); bool result = expr.getResult() != negated; - if( result ) { + if (result) { if (!m_includeSuccessfulResults) { assertionPassed(); - } - else { + } else { reportExpr(info, ResultWas::Ok, &expr, negated); } - } - else { - reportExpr(info, ResultWas::ExpressionFailed, &expr, negated ); - populateReaction( reaction ); + } else { + reportExpr(info, ResultWas::ExpressionFailed, &expr, negated); + populateReaction(reaction); } } - void RunContext::reportExpr( - AssertionInfo const &info, - ResultWas::OfType resultType, - ITransientExpression const *expr, - bool negated ) { + void RunContext::reportExpr(AssertionInfo const& info, + ResultWas::OfType resultType, + ITransientExpression const* expr, + bool negated) { m_lastAssertionInfo = info; - AssertionResultData data( resultType, LazyExpression( negated ) ); + AssertionResultData data(resultType, LazyExpression(negated)); - AssertionResult assertionResult{ info, data }; - assertionResult.m_resultData.lazyExpression.m_transientExpression = expr; + AssertionResult assertionResult{info, data}; + assertionResult.m_resultData.lazyExpression.m_transientExpression = + expr; - assertionEnded( assertionResult ); + assertionEnded(assertionResult); } - void RunContext::handleMessage( - AssertionInfo const& info, - ResultWas::OfType resultType, - StringRef const& message, - AssertionReaction& reaction - ) { - m_reporter->assertionStarting( info ); + void RunContext::handleMessage(AssertionInfo const& info, + ResultWas::OfType resultType, + StringRef const& message, + AssertionReaction& reaction) { + m_reporter->assertionStarting(info); m_lastAssertionInfo = info; - AssertionResultData data( resultType, LazyExpression( false ) ); + AssertionResultData data(resultType, LazyExpression(false)); data.message = static_cast<std::string>(message); - AssertionResult assertionResult{ m_lastAssertionInfo, data }; - assertionEnded( assertionResult ); - if( !assertionResult.isOk() ) - populateReaction( reaction ); + AssertionResult assertionResult{m_lastAssertionInfo, data}; + assertionEnded(assertionResult); + if (!assertionResult.isOk()) + populateReaction(reaction); } void RunContext::handleUnexpectedExceptionNotThrown( - AssertionInfo const& info, - AssertionReaction& reaction - ) { + AssertionInfo const& info, AssertionReaction& reaction) { handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction); } - void RunContext::handleUnexpectedInflightException( - AssertionInfo const& info, - std::string const& message, - AssertionReaction& reaction - ) { + void + RunContext::handleUnexpectedInflightException(AssertionInfo const& info, + std::string const& message, + AssertionReaction& reaction) { m_lastAssertionInfo = info; - AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) ); + AssertionResultData data(ResultWas::ThrewException, + LazyExpression(false)); data.message = message; - AssertionResult assertionResult{ info, data }; - assertionEnded( assertionResult ); - populateReaction( reaction ); + AssertionResult assertionResult{info, data}; + assertionEnded(assertionResult); + populateReaction(reaction); } - void RunContext::populateReaction( AssertionReaction& reaction ) { + void RunContext::populateReaction(AssertionReaction& reaction) { reaction.shouldDebugBreak = m_config->shouldDebugBreak(); - reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal); + reaction.shouldThrow = + aborting() || + (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal); } - void RunContext::handleIncomplete( - AssertionInfo const& info - ) { + void RunContext::handleIncomplete(AssertionInfo const& info) { m_lastAssertionInfo = info; - AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) ); - data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE"; - AssertionResult assertionResult{ info, data }; - assertionEnded( assertionResult ); + AssertionResultData data(ResultWas::ThrewException, + LazyExpression(false)); + data.message = + "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE"; + AssertionResult assertionResult{info, data}; + assertionEnded(assertionResult); } - void RunContext::handleNonExpr( - AssertionInfo const &info, - ResultWas::OfType resultType, - AssertionReaction &reaction - ) { + void RunContext::handleNonExpr(AssertionInfo const& info, + ResultWas::OfType resultType, + AssertionReaction& reaction) { m_lastAssertionInfo = info; - AssertionResultData data( resultType, LazyExpression( false ) ); - AssertionResult assertionResult{ info, data }; - assertionEnded( assertionResult ); + AssertionResultData data(resultType, LazyExpression(false)); + AssertionResult assertionResult{info, data}; + assertionEnded(assertionResult); - if( !assertionResult.isOk() ) - populateReaction( reaction ); + if (!assertionResult.isOk()) + populateReaction(reaction); } IResultCapture& getResultCapture() { @@ -13155,33 +14692,32 @@ return getCurrentContext().getConfig()->rngSeed(); } -} +} // namespace Catch // end catch_run_context.cpp // start catch_section.cpp namespace Catch { - Section::Section( SectionInfo const& info ) - : m_info( info ), - m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) ) - { + Section::Section(SectionInfo const& info) : + m_info(info), + m_sectionIncluded( + getResultCapture().sectionStarted(m_info, m_assertions)) { m_timer.start(); } Section::~Section() { - if( m_sectionIncluded ) { - SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() }; - if( uncaught_exceptions() ) - getResultCapture().sectionEndedEarly( endInfo ); + if (m_sectionIncluded) { + SectionEndInfo endInfo{ + m_info, m_assertions, m_timer.getElapsedSeconds()}; + if (uncaught_exceptions()) + getResultCapture().sectionEndedEarly(endInfo); else - getResultCapture().sectionEnded( endInfo ); + getResultCapture().sectionEnded(endInfo); } } // This indicates whether the section should be executed or not - Section::operator bool() const { - return m_sectionIncluded; - } + Section::operator bool() const { return m_sectionIncluded; } } // end namespace Catch // end catch_section.cpp @@ -13189,12 +14725,9 @@ namespace Catch { - SectionInfo::SectionInfo - ( SourceLineInfo const& _lineInfo, - std::string const& _name ) - : name( _name ), - lineInfo( _lineInfo ) - {} + SectionInfo::SectionInfo(SourceLineInfo const& _lineInfo, + std::string const& _name) : + name(_name), lineInfo(_lineInfo) {} } // end namespace Catch // end catch_section_info.cpp @@ -13208,22 +14741,20 @@ class Session : NonCopyable { public: - Session(); ~Session() override; void showHelp() const; void libIdentify(); - int applyCommandLine( int argc, char const * const * argv ); - #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE) - int applyCommandLine( int argc, wchar_t const * const * argv ); - #endif + int applyCommandLine(int argc, char const* const* argv); +#if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE) + int applyCommandLine(int argc, wchar_t const* const* argv); +#endif - void useConfigData( ConfigData const& configData ); + void useConfigData(ConfigData const& configData); - template<typename CharT> - int run(int argc, CharT const * const argv[]) { + template <typename CharT> int run(int argc, CharT const* const argv[]) { if (m_startupExceptions) return 1; int returnCode = applyCommandLine(argc, argv); @@ -13235,9 +14766,10 @@ int run(); clara::Parser const& cli() const; - void cli( clara::Parser const& newParser ); + void cli(clara::Parser const& newParser); ConfigData& configData(); Config& config(); + private: int runInternal(); @@ -13258,27 +14790,28 @@ // Versioning information struct Version { - Version( Version const& ) = delete; - Version& operator=( Version const& ) = delete; - Version( unsigned int _majorVersion, - unsigned int _minorVersion, - unsigned int _patchNumber, - char const * const _branchName, - unsigned int _buildNumber ); + Version(Version const&) = delete; + Version& operator=(Version const&) = delete; + Version(unsigned int _majorVersion, + unsigned int _minorVersion, + unsigned int _patchNumber, + char const* const _branchName, + unsigned int _buildNumber); unsigned int const majorVersion; unsigned int const minorVersion; unsigned int const patchNumber; // buildNumber is only used if branchName is not null - char const * const branchName; + char const* const branchName; unsigned int const buildNumber; - friend std::ostream& operator << ( std::ostream& os, Version const& version ); + friend std::ostream& operator<<(std::ostream& os, + Version const& version); }; Version const& libraryVersion(); -} +} // namespace Catch // end catch_version.h #include <cstdlib> @@ -13291,15 +14824,24 @@ namespace { const int MaxExitCode = 255; - IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) { - auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config); - CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'"); + IStreamingReporterPtr createReporter(std::string const& reporterName, + IConfigPtr const& config) { + auto reporter = + Catch::getRegistryHub().getReporterRegistry().create( + reporterName, config); + CATCH_ENFORCE(reporter, + "No reporter registered with name: '" << reporterName + << "'"); return reporter; } - IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) { - if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) { + IStreamingReporterPtr + makeReporter(std::shared_ptr<Config> const& config) { + if (Catch::getRegistryHub() + .getReporterRegistry() + .getListeners() + .empty()) { return createReporter(config->getReporterName(), config); } @@ -13308,24 +14850,27 @@ // doesn't compile without a std::move call. However, this causes // a warning on newer platforms. Thus, we have to work around // it a bit and downcast the pointer manually. - auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter); + auto ret = + std::unique_ptr<IStreamingReporter>(new ListeningReporter); auto& multi = static_cast<ListeningReporter&>(*ret); - auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners(); + auto const& listeners = + Catch::getRegistryHub().getReporterRegistry().getListeners(); for (auto const& listener : listeners) { - multi.addListener(listener->create(Catch::ReporterConfig(config))); + multi.addListener( + listener->create(Catch::ReporterConfig(config))); } - multi.addReporter(createReporter(config->getReporterName(), config)); + multi.addReporter( + createReporter(config->getReporterName(), config)); return ret; } class TestGroup { public: - explicit TestGroup(std::shared_ptr<Config> const& config) - : m_config{config} - , m_context{config, makeReporter(config)} - { + explicit TestGroup(std::shared_ptr<Config> const& config) : + m_config{config}, m_context{config, makeReporter(config)} { auto const& allTestCases = getAllTestCasesSorted(*m_config); - m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config); + m_matches = m_config->testSpec().matchesByFilter(allTestCases, + *m_config); auto const& invalidArgs = m_config->testSpec().getInvalidArgs(); if (m_matches.empty() && invalidArgs.empty()) { @@ -13357,8 +14902,8 @@ } if (!invalidArgs.empty()) { - for (auto const& invalidArg: invalidArgs) - m_context.reporter().reportInvalidArguments(invalidArg); + for (auto const& invalidArg : invalidArgs) + m_context.reporter().reportInvalidArguments(invalidArg); } m_context.testGroupEnded(m_config->name(), totals, 1, 1); @@ -13375,7 +14920,8 @@ }; void applyFilenamesAsTags(Catch::IConfig const& config) { - auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config)); + auto& tests = const_cast<std::vector<TestCase>&>( + getAllTestCasesSorted(config)); for (auto& testCase : tests) { auto tags = testCase.tags; @@ -13396,141 +14942,151 @@ } } - } // anon namespace + } // namespace Session::Session() { static bool alreadyInstantiated = false; - if( alreadyInstantiated ) { - CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); } - CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); } + if (alreadyInstantiated) { + CATCH_TRY { + CATCH_INTERNAL_ERROR( + "Only one instance of Catch::Session can ever be used"); + } + CATCH_CATCH_ALL { + getMutableRegistryHub().registerStartupException(); + } } // There cannot be exceptions at startup in no-exception mode. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) - const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions(); - if ( !exceptions.empty() ) { + const auto& exceptions = + getRegistryHub().getStartupExceptionRegistry().getExceptions(); + if (!exceptions.empty()) { config(); getCurrentMutableContext().setConfig(m_config); m_startupExceptions = true; - Colour colourGuard( Colour::Red ); + Colour colourGuard(Colour::Red); Catch::cerr() << "Errors occurred during startup!" << '\n'; // iterate over all exceptions and notify user - for ( const auto& ex_ptr : exceptions ) { + for (const auto& ex_ptr : exceptions) { try { std::rethrow_exception(ex_ptr); - } catch ( std::exception const& ex ) { - Catch::cerr() << Column( ex.what() ).indent(2) << '\n'; + } catch (std::exception const& ex) { + Catch::cerr() << Column(ex.what()).indent(2) << '\n'; } } } #endif alreadyInstantiated = true; - m_cli = makeCommandLineParser( m_configData ); + m_cli = makeCommandLineParser(m_configData); } - Session::~Session() { - Catch::cleanUp(); - } + Session::~Session() { Catch::cleanUp(); } void Session::showHelp() const { - Catch::cout() - << "\nCatch v" << libraryVersion() << "\n" - << m_cli << std::endl - << "For more detailed usage please see the project docs\n" << std::endl; + Catch::cout() << "\nCatch v" << libraryVersion() << "\n" + << m_cli << std::endl + << "For more detailed usage please see the project docs\n" + << std::endl; } void Session::libIdentify() { - Catch::cout() - << std::left << std::setw(16) << "description: " << "A Catch2 test executable\n" - << std::left << std::setw(16) << "category: " << "testframework\n" - << std::left << std::setw(16) << "framework: " << "Catch Test\n" - << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl; + Catch::cout() << std::left << std::setw(16) << "description: " + << "A Catch2 test executable\n" + << std::left << std::setw(16) << "category: " + << "testframework\n" + << std::left << std::setw(16) << "framework: " + << "Catch Test\n" + << std::left << std::setw(16) + << "version: " << libraryVersion() << std::endl; } - int Session::applyCommandLine( int argc, char const * const * argv ) { - if( m_startupExceptions ) + int Session::applyCommandLine(int argc, char const* const* argv) { + if (m_startupExceptions) return 1; - auto result = m_cli.parse( clara::Args( argc, argv ) ); - if( !result ) { + auto result = m_cli.parse(clara::Args(argc, argv)); + if (!result) { config(); getCurrentMutableContext().setConfig(m_config); - Catch::cerr() - << Colour( Colour::Red ) - << "\nError(s) in input:\n" - << Column( result.errorMessage() ).indent( 2 ) - << "\n\n"; + Catch::cerr() << Colour(Colour::Red) << "\nError(s) in input:\n" + << Column(result.errorMessage()).indent(2) << "\n\n"; Catch::cerr() << "Run with -? for usage\n" << std::endl; return MaxExitCode; } - if( m_configData.showHelp ) + if (m_configData.showHelp) showHelp(); - if( m_configData.libIdentify ) + if (m_configData.libIdentify) libIdentify(); m_config.reset(); return 0; } #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE) - int Session::applyCommandLine( int argc, wchar_t const * const * argv ) { + int Session::applyCommandLine(int argc, wchar_t const* const* argv) { - char **utf8Argv = new char *[ argc ]; + char** utf8Argv = new char*[argc]; - for ( int i = 0; i < argc; ++i ) { - int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, nullptr, 0, nullptr, nullptr ); + for (int i = 0; i < argc; ++i) { + int bufSize = WideCharToMultiByte( + CP_UTF8, 0, argv[i], -1, nullptr, 0, nullptr, nullptr); - utf8Argv[ i ] = new char[ bufSize ]; + utf8Argv[i] = new char[bufSize]; - WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, nullptr, nullptr ); + WideCharToMultiByte(CP_UTF8, + 0, + argv[i], + -1, + utf8Argv[i], + bufSize, + nullptr, + nullptr); } - int returnCode = applyCommandLine( argc, utf8Argv ); + int returnCode = applyCommandLine(argc, utf8Argv); - for ( int i = 0; i < argc; ++i ) - delete [] utf8Argv[ i ]; + for (int i = 0; i < argc; ++i) + delete[] utf8Argv[i]; - delete [] utf8Argv; + delete[] utf8Argv; return returnCode; } #endif - void Session::useConfigData( ConfigData const& configData ) { + void Session::useConfigData(ConfigData const& configData) { m_configData = configData; m_config.reset(); } int Session::run() { - if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) { - Catch::cout() << "...waiting for enter/ return before starting" << std::endl; + if ((m_configData.waitForKeypress & WaitForKeypress::BeforeStart) != 0) + { + Catch::cout() << "...waiting for enter/ return before starting" + << std::endl; static_cast<void>(std::getchar()); } int exitCode = runInternal(); - if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) { - Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl; + if ((m_configData.waitForKeypress & WaitForKeypress::BeforeExit) != 0) { + Catch::cout() + << "...waiting for enter/ return before exiting, with code: " + << exitCode << std::endl; static_cast<void>(std::getchar()); } return exitCode; } - clara::Parser const& Session::cli() const { - return m_cli; - } - void Session::cli( clara::Parser const& newParser ) { - m_cli = newParser; - } - ConfigData& Session::configData() { - return m_configData; - } + clara::Parser const& Session::cli() const { return m_cli; } + void Session::cli(clara::Parser const& newParser) { m_cli = newParser; } + ConfigData& Session::configData() { return m_configData; } Config& Session::config() { - if( !m_config ) - m_config = std::make_shared<Config>( m_configData ); + if (!m_config) + m_config = std::make_shared<Config>(m_configData); return *m_config; } int Session::runInternal() { - if( m_startupExceptions ) + if (m_startupExceptions) return 1; if (m_configData.showHelp || m_configData.libIdentify) { @@ -13540,28 +15096,31 @@ CATCH_TRY { config(); // Force config to be constructed - seedRng( *m_config ); + seedRng(*m_config); - if( m_configData.filenamesAsTags ) - applyFilenamesAsTags( *m_config ); + if (m_configData.filenamesAsTags) + applyFilenamesAsTags(*m_config); // Handle list request - if( Option<std::size_t> listed = list( m_config ) ) - return static_cast<int>( *listed ); + if (Option<std::size_t> listed = list(m_config)) + return static_cast<int>(*listed); - TestGroup tests { m_config }; + TestGroup tests{m_config}; auto const totals = tests.execute(); - if( m_config->warnAboutNoTests() && totals.error == -1 ) + if (m_config->warnAboutNoTests() && totals.error == -1) return 2; - // Note that on unices only the lower 8 bits are usually used, clamping - // the return value to 255 prevents false negative when some multiple - // of 256 tests has failed - return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed))); + // Note that on unices only the lower 8 bits are usually used, + // clamping the return value to 255 prevents false negative when + // some multiple of 256 tests has failed + return (std::min)( + MaxExitCode, + (std::max)(totals.error, + static_cast<int>(totals.assertions.failed))); } #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) - catch( std::exception& ex ) { + catch (std::exception& ex) { Catch::cerr() << ex.what() << std::endl; return MaxExitCode; } @@ -13579,20 +15138,20 @@ namespace { static auto getSingletons() -> std::vector<ISingleton*>*& { static std::vector<ISingleton*>* g_singletons = nullptr; - if( !g_singletons ) + if (!g_singletons) g_singletons = new std::vector<ISingleton*>(); return g_singletons; } - } + } // namespace ISingleton::~ISingleton() {} - void addSingleton(ISingleton* singleton ) { - getSingletons()->push_back( singleton ); + void addSingleton(ISingleton* singleton) { + getSingletons()->push_back(singleton); } void cleanupSingletons() { auto& singletons = getSingletons(); - for( auto singleton : *singletons ) + for (auto singleton : *singletons) delete singleton; delete singletons; singletons = nullptr; @@ -13604,16 +15163,18 @@ #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) namespace Catch { -void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept { - CATCH_TRY { - m_exceptions.push_back(exception); - } CATCH_CATCH_ALL { - // If we run out of memory during start-up there's really not a lot more we can do about it + void StartupExceptionRegistry::add( + std::exception_ptr const& exception) noexcept { + CATCH_TRY { m_exceptions.push_back(exception); } + CATCH_CATCH_ALL { + // If we run out of memory during start-up there's really not a lot + // more we can do about it std::terminate(); } } - std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept { + std::vector<std::exception_ptr> const& + StartupExceptionRegistry::getExceptions() const noexcept { return m_exceptions; } @@ -13633,163 +15194,168 @@ Catch::IStream::~IStream() = default; - namespace Detail { namespace { - template<typename WriterF, std::size_t bufferSize=256> - class StreamBufImpl : public std::streambuf { - char data[bufferSize]; - WriterF m_writer; + namespace Detail { + namespace { + template <typename WriterF, std::size_t bufferSize = 256> + class StreamBufImpl : public std::streambuf { + char data[bufferSize]; + WriterF m_writer; - public: - StreamBufImpl() { - setp( data, data + sizeof(data) ); - } + public: + StreamBufImpl() { setp(data, data + sizeof(data)); } - ~StreamBufImpl() noexcept { - StreamBufImpl::sync(); - } + ~StreamBufImpl() noexcept { StreamBufImpl::sync(); } - private: - int overflow( int c ) override { - sync(); + private: + int overflow(int c) override { + sync(); - if( c != EOF ) { - if( pbase() == epptr() ) - m_writer( std::string( 1, static_cast<char>( c ) ) ); - else - sputc( static_cast<char>( c ) ); + if (c != EOF) { + if (pbase() == epptr()) + m_writer(std::string(1, static_cast<char>(c))); + else + sputc(static_cast<char>(c)); + } + return 0; } - return 0; - } - int sync() override { - if( pbase() != pptr() ) { - m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) ); - setp( pbase(), epptr() ); + int sync() override { + if (pbase() != pptr()) { + m_writer( + std::string(pbase(), + static_cast<std::string::size_type>( + pptr() - pbase()))); + setp(pbase(), epptr()); + } + return 0; } - return 0; - } - }; + }; - /////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////// - struct OutputDebugWriter { + struct OutputDebugWriter { - void operator()( std::string const&str ) { - writeToDebugConsole( str ); - } - }; + void operator()(std::string const& str) { + writeToDebugConsole(str); + } + }; - /////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////// - class FileStream : public IStream { - mutable std::ofstream m_ofs; - public: - FileStream( StringRef filename ) { - m_ofs.open( filename.c_str() ); - CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" ); - } - ~FileStream() override = default; - public: // IStream - std::ostream& stream() const override { - return m_ofs; - } - }; + class FileStream : public IStream { + mutable std::ofstream m_ofs; - /////////////////////////////////////////////////////////////////////////// + public: + FileStream(StringRef filename) { + m_ofs.open(filename.c_str()); + CATCH_ENFORCE(!m_ofs.fail(), + "Unable to open file: '" << filename << "'"); + } + ~FileStream() override = default; - class CoutStream : public IStream { - mutable std::ostream m_os; - public: - // Store the streambuf from cout up-front because - // cout may get redirected when running tests - CoutStream() : m_os( Catch::cout().rdbuf() ) {} - ~CoutStream() override = default; + public: // IStream + std::ostream& stream() const override { return m_ofs; } + }; - public: // IStream - std::ostream& stream() const override { return m_os; } - }; + /////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////// + class CoutStream : public IStream { + mutable std::ostream m_os; - class DebugOutStream : public IStream { - std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf; - mutable std::ostream m_os; - public: - DebugOutStream() - : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ), - m_os( m_streamBuf.get() ) - {} + public: + // Store the streambuf from cout up-front because + // cout may get redirected when running tests + CoutStream() : m_os(Catch::cout().rdbuf()) {} + ~CoutStream() override = default; - ~DebugOutStream() override = default; + public: // IStream + std::ostream& stream() const override { return m_os; } + }; - public: // IStream - std::ostream& stream() const override { return m_os; } - }; + /////////////////////////////////////////////////////////////////////////// - }} // namespace anon::detail + class DebugOutStream : public IStream { + std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf; + mutable std::ostream m_os; + + public: + DebugOutStream() : + m_streamBuf(new StreamBufImpl<OutputDebugWriter>()), + m_os(m_streamBuf.get()) {} + + ~DebugOutStream() override = default; + + public: // IStream + std::ostream& stream() const override { return m_os; } + }; + + } // namespace + } // namespace Detail /////////////////////////////////////////////////////////////////////////// - auto makeStream( StringRef const &filename ) -> IStream const* { - if( filename.empty() ) + auto makeStream(StringRef const& filename) -> IStream const* { + if (filename.empty()) return new Detail::CoutStream(); - else if( filename[0] == '%' ) { - if( filename == "%debug" ) + else if (filename[0] == '%') { + if (filename == "%debug") return new Detail::DebugOutStream(); else - CATCH_ERROR( "Unrecognised stream: '" << filename << "'" ); - } - else - return new Detail::FileStream( filename ); + CATCH_ERROR("Unrecognised stream: '" << filename << "'"); + } else + return new Detail::FileStream(filename); } - // This class encapsulates the idea of a pool of ostringstreams that can be reused. + // This class encapsulates the idea of a pool of ostringstreams that can be + // reused. struct StringStreams { std::vector<std::unique_ptr<std::ostringstream>> m_streams; std::vector<std::size_t> m_unused; std::ostringstream m_referenceStream; // Used for copy state/ flags from auto add() -> std::size_t { - if( m_unused.empty() ) { - m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) ); - return m_streams.size()-1; - } - else { + if (m_unused.empty()) { + m_streams.push_back(std::unique_ptr<std::ostringstream>( + new std::ostringstream)); + return m_streams.size() - 1; + } else { auto index = m_unused.back(); m_unused.pop_back(); return index; } } - void release( std::size_t index ) { - m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state + void release(std::size_t index) { + m_streams[index]->copyfmt( + m_referenceStream); // Restore initial flags and other state m_unused.push_back(index); } }; - ReusableStringStream::ReusableStringStream() - : m_index( Singleton<StringStreams>::getMutable().add() ), - m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() ) - {} + ReusableStringStream::ReusableStringStream() : + m_index(Singleton<StringStreams>::getMutable().add()), + m_oss(Singleton<StringStreams>::getMutable().m_streams[m_index].get()) { + } ReusableStringStream::~ReusableStringStream() { - static_cast<std::ostringstream*>( m_oss )->str(""); + static_cast<std::ostringstream*>(m_oss)->str(""); m_oss->clear(); - Singleton<StringStreams>::getMutable().release( m_index ); + Singleton<StringStreams>::getMutable().release(m_index); } auto ReusableStringStream::str() const -> std::string { - return static_cast<std::ostringstream*>( m_oss )->str(); + return static_cast<std::ostringstream*>(m_oss)->str(); } /////////////////////////////////////////////////////////////////////////// -#ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions +#ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these + // functions std::ostream& cout() { return std::cout; } std::ostream& cerr() { return std::cerr; } std::ostream& clog() { return std::clog; } #endif -} +} // namespace Catch // end catch_stream.cpp // start catch_string_manip.cpp @@ -13803,39 +15369,43 @@ namespace { char toLowerCh(char c) { - return static_cast<char>( std::tolower( static_cast<unsigned char>(c) ) ); + return static_cast<char>( + std::tolower(static_cast<unsigned char>(c))); } - } + } // namespace - bool startsWith( std::string const& s, std::string const& prefix ) { - return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin()); + bool startsWith(std::string const& s, std::string const& prefix) { + return s.size() >= prefix.size() && + std::equal(prefix.begin(), prefix.end(), s.begin()); } - bool startsWith( std::string const& s, char prefix ) { + bool startsWith(std::string const& s, char prefix) { return !s.empty() && s[0] == prefix; } - bool endsWith( std::string const& s, std::string const& suffix ) { - return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin()); + bool endsWith(std::string const& s, std::string const& suffix) { + return s.size() >= suffix.size() && + std::equal(suffix.rbegin(), suffix.rend(), s.rbegin()); } - bool endsWith( std::string const& s, char suffix ) { - return !s.empty() && s[s.size()-1] == suffix; + bool endsWith(std::string const& s, char suffix) { + return !s.empty() && s[s.size() - 1] == suffix; } - bool contains( std::string const& s, std::string const& infix ) { - return s.find( infix ) != std::string::npos; + bool contains(std::string const& s, std::string const& infix) { + return s.find(infix) != std::string::npos; } - void toLowerInPlace( std::string& s ) { - std::transform( s.begin(), s.end(), s.begin(), toLowerCh ); + void toLowerInPlace(std::string& s) { + std::transform(s.begin(), s.end(), s.begin(), toLowerCh); } - std::string toLower( std::string const& s ) { + std::string toLower(std::string const& s) { std::string lc = s; - toLowerInPlace( lc ); + toLowerInPlace(lc); return lc; } - std::string trim( std::string const& str ) { + std::string trim(std::string const& str) { static char const* whitespaceChars = "\n\r\t "; - std::string::size_type start = str.find_first_not_of( whitespaceChars ); - std::string::size_type end = str.find_last_not_of( whitespaceChars ); + std::string::size_type start = str.find_first_not_of(whitespaceChars); + std::string::size_type end = str.find_last_not_of(whitespaceChars); - return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string(); + return start != std::string::npos ? str.substr(start, 1 + end - start) + : std::string(); } StringRef trim(StringRef ref) { @@ -13843,55 +15413,60 @@ return c == ' ' || c == '\t' || c == '\n' || c == '\r'; }; size_t real_begin = 0; - while (real_begin < ref.size() && is_ws(ref[real_begin])) { ++real_begin; } + while (real_begin < ref.size() && is_ws(ref[real_begin])) { + ++real_begin; + } size_t real_end = ref.size(); - while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; } + while (real_end > real_begin && is_ws(ref[real_end - 1])) { + --real_end; + } return ref.substr(real_begin, real_end - real_begin); } - bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) { + bool replaceInPlace(std::string& str, + std::string const& replaceThis, + std::string const& withThis) { bool replaced = false; - std::size_t i = str.find( replaceThis ); - while( i != std::string::npos ) { + std::size_t i = str.find(replaceThis); + while (i != std::string::npos) { replaced = true; - str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() ); - if( i < str.size()-withThis.size() ) - i = str.find( replaceThis, i+withThis.size() ); + str = str.substr(0, i) + withThis + + str.substr(i + replaceThis.size()); + if (i < str.size() - withThis.size()) + i = str.find(replaceThis, i + withThis.size()); else i = std::string::npos; } return replaced; } - std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) { + std::vector<StringRef> splitStringRef(StringRef str, char delimiter) { std::vector<StringRef> subStrings; std::size_t start = 0; - for(std::size_t pos = 0; pos < str.size(); ++pos ) { - if( str[pos] == delimiter ) { - if( pos - start > 1 ) - subStrings.push_back( str.substr( start, pos-start ) ); - start = pos+1; + for (std::size_t pos = 0; pos < str.size(); ++pos) { + if (str[pos] == delimiter) { + if (pos - start > 1) + subStrings.push_back(str.substr(start, pos - start)); + start = pos + 1; } } - if( start < str.size() ) - subStrings.push_back( str.substr( start, str.size()-start ) ); + if (start < str.size()) + subStrings.push_back(str.substr(start, str.size() - start)); return subStrings; } - pluralise::pluralise( std::size_t count, std::string const& label ) - : m_count( count ), - m_label( label ) - {} + pluralise::pluralise(std::size_t count, std::string const& label) : + m_count(count), m_label(label) {} - std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) { + std::ostream& operator<<(std::ostream& os, pluralise const& pluraliser) { os << pluraliser.m_count << ' ' << pluraliser.m_label; - if( pluraliser.m_count != 1 ) + if (pluraliser.m_count != 1) os << 's'; return os; } -} +} // namespace Catch // end catch_string_manip.cpp // start catch_stringref.cpp @@ -13901,35 +15476,36 @@ #include <cstdint> namespace Catch { - StringRef::StringRef( char const* rawChars ) noexcept - : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) ) - {} + StringRef::StringRef(char const* rawChars) noexcept : + StringRef(rawChars, + static_cast<StringRef::size_type>(std::strlen(rawChars))) {} auto StringRef::c_str() const -> char const* { - CATCH_ENFORCE(isNullTerminated(), "Called StringRef::c_str() on a non-null-terminated instance"); + CATCH_ENFORCE( + isNullTerminated(), + "Called StringRef::c_str() on a non-null-terminated instance"); return m_start; } - auto StringRef::data() const noexcept -> char const* { - return m_start; - } + auto StringRef::data() const noexcept -> char const* { return m_start; } - auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef { + auto StringRef::substr(size_type start, size_type size) const noexcept + -> StringRef { if (start < m_size) { return StringRef(m_start + start, (std::min)(m_size - start, size)); } else { return StringRef(); } } - auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool { - return m_size == other.m_size - && (std::memcmp( m_start, other.m_start, m_size ) == 0); + auto StringRef::operator==(StringRef const& other) const noexcept -> bool { + return m_size == other.m_size && + (std::memcmp(m_start, other.m_start, m_size) == 0); } - auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& { + auto operator<<(std::ostream& os, StringRef const& str) -> std::ostream& { return os.write(str.data(), str.size()); } - auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& { + auto operator+=(std::string& lhs, StringRef const& rhs) -> std::string& { lhs.append(rhs.data(), rhs.size()); return lhs; } @@ -13939,23 +15515,27 @@ // start catch_tag_alias.cpp namespace Catch { - TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {} -} + TagAlias::TagAlias(std::string const& _tag, SourceLineInfo _lineInfo) : + tag(_tag), lineInfo(_lineInfo) {} +} // namespace Catch // end catch_tag_alias.cpp // start catch_tag_alias_autoregistrar.cpp namespace Catch { - RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) { + RegistrarForTagAliases::RegistrarForTagAliases( + char const* alias, char const* tag, SourceLineInfo const& lineInfo) { CATCH_TRY { getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo); - } CATCH_CATCH_ALL { - // Do not throw when constructing global objects, instead register the exception to be processed later + } + CATCH_CATCH_ALL { + // Do not throw when constructing global objects, instead register + // the exception to be processed later getMutableRegistryHub().registerStartupException(); } } -} +} // namespace Catch // end catch_tag_alias_autoregistrar.cpp // start catch_tag_alias_registry.cpp @@ -13965,35 +15545,43 @@ TagAliasRegistry::~TagAliasRegistry() {} - TagAlias const* TagAliasRegistry::find( std::string const& alias ) const { - auto it = m_registry.find( alias ); - if( it != m_registry.end() ) + TagAlias const* TagAliasRegistry::find(std::string const& alias) const { + auto it = m_registry.find(alias); + if (it != m_registry.end()) return &(it->second); else return nullptr; } - std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const { + std::string TagAliasRegistry::expandAliases( + std::string const& unexpandedTestSpec) const { std::string expandedTestSpec = unexpandedTestSpec; - for( auto const& registryKvp : m_registry ) { - std::size_t pos = expandedTestSpec.find( registryKvp.first ); - if( pos != std::string::npos ) { - expandedTestSpec = expandedTestSpec.substr( 0, pos ) + - registryKvp.second.tag + - expandedTestSpec.substr( pos + registryKvp.first.size() ); + for (auto const& registryKvp : m_registry) { + std::size_t pos = expandedTestSpec.find(registryKvp.first); + if (pos != std::string::npos) { + expandedTestSpec = + expandedTestSpec.substr(0, pos) + registryKvp.second.tag + + expandedTestSpec.substr(pos + registryKvp.first.size()); } } return expandedTestSpec; } - void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) { - CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'), - "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo ); + void TagAliasRegistry::add(std::string const& alias, + std::string const& tag, + SourceLineInfo const& lineInfo) { + CATCH_ENFORCE(startsWith(alias, "[@") && endsWith(alias, ']'), + "error: tag alias, '" + << alias << "' is not of the form [@alias name].\n" + << lineInfo); - CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second, - "error: tag alias, '" << alias << "' already registered.\n" - << "\tFirst seen at: " << find(alias)->lineInfo << "\n" - << "\tRedefined at: " << lineInfo ); + CATCH_ENFORCE( + m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))) + .second, + "error: tag alias, '" + << alias << "' already registered.\n" + << "\tFirst seen at: " << find(alias)->lineInfo << "\n" + << "\tRedefined at: " << lineInfo); } ITagAliasRegistry::~ITagAliasRegistry() {} @@ -14014,39 +15602,44 @@ namespace Catch { namespace { - TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) { - if( startsWith( tag, '.' ) || - tag == "!hide" ) + TestCaseInfo::SpecialProperties + parseSpecialTag(std::string const& tag) { + if (startsWith(tag, '.') || tag == "!hide") return TestCaseInfo::IsHidden; - else if( tag == "!throws" ) + else if (tag == "!throws") return TestCaseInfo::Throws; - else if( tag == "!shouldfail" ) + else if (tag == "!shouldfail") return TestCaseInfo::ShouldFail; - else if( tag == "!mayfail" ) + else if (tag == "!mayfail") return TestCaseInfo::MayFail; - else if( tag == "!nonportable" ) + else if (tag == "!nonportable") return TestCaseInfo::NonPortable; - else if( tag == "!benchmark" ) - return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden ); + else if (tag == "!benchmark") + return static_cast<TestCaseInfo::SpecialProperties>( + TestCaseInfo::Benchmark | TestCaseInfo::IsHidden); else return TestCaseInfo::None; } - bool isReservedTag( std::string const& tag ) { - return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) ); + bool isReservedTag(std::string const& tag) { + return parseSpecialTag(tag) == TestCaseInfo::None && + tag.size() > 0 && + !std::isalnum(static_cast<unsigned char>(tag[0])); } - void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) { - CATCH_ENFORCE( !isReservedTag(tag), - "Tag name: [" << tag << "] is not allowed.\n" - << "Tag names starting with non alphanumeric characters are reserved\n" - << _lineInfo ); + void enforceNotReservedTag(std::string const& tag, + SourceLineInfo const& _lineInfo) { + CATCH_ENFORCE(!isReservedTag(tag), + "Tag name: [" + << tag << "] is not allowed.\n" + << "Tag names starting with non alphanumeric " + "characters are reserved\n" + << _lineInfo); } - } + } // namespace - TestCase makeTestCase( ITestInvoker* _testCase, - std::string const& _className, - NameAndTags const& nameAndTags, - SourceLineInfo const& _lineInfo ) - { + TestCase makeTestCase(ITestInvoker* _testCase, + std::string const& _className, + NameAndTags const& nameAndTags, + SourceLineInfo const& _lineInfo) { bool isHidden = false; // Parse out tags @@ -14054,19 +15647,18 @@ std::string desc, tag; bool inTag = false; for (char c : nameAndTags.tags) { - if( !inTag ) { - if( c == '[' ) + if (!inTag) { + if (c == '[') inTag = true; else desc += c; - } - else { - if( c == ']' ) { - TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag ); - if( ( prop & TestCaseInfo::IsHidden ) != 0 ) + } else { + if (c == ']') { + TestCaseInfo::SpecialProperties prop = parseSpecialTag(tag); + if ((prop & TestCaseInfo::IsHidden) != 0) isHidden = true; - else if( prop == TestCaseInfo::None ) - enforceNotReservedTag( tag, _lineInfo ); + else if (prop == TestCaseInfo::None) + enforceNotReservedTag(tag, _lineInfo); // Merged hide tags like `[.approvals]` should be added as // `[.][approvals]`. The `[.]` is added at later point, so @@ -14074,61 +15666,61 @@ if (startsWith(tag, '.') && tag.size() > 1) { tag.erase(0, 1); } - tags.push_back( tag ); + tags.push_back(tag); tag.clear(); inTag = false; - } - else + } else tag += c; } } - if( isHidden ) { + if (isHidden) { // Add all "hidden" tags to make them behave identically - tags.insert( tags.end(), { ".", "!hide" } ); + tags.insert(tags.end(), {".", "!hide"}); } - TestCaseInfo info( static_cast<std::string>(nameAndTags.name), _className, desc, tags, _lineInfo ); - return TestCase( _testCase, std::move(info) ); + TestCaseInfo info(static_cast<std::string>(nameAndTags.name), + _className, + desc, + tags, + _lineInfo); + return TestCase(_testCase, std::move(info)); } - void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) { + void setTags(TestCaseInfo& testCaseInfo, std::vector<std::string> tags) { std::sort(begin(tags), end(tags)); tags.erase(std::unique(begin(tags), end(tags)), end(tags)); testCaseInfo.lcaseTags.clear(); - for( auto const& tag : tags ) { - std::string lcaseTag = toLower( tag ); - testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) ); - testCaseInfo.lcaseTags.push_back( lcaseTag ); + for (auto const& tag : tags) { + std::string lcaseTag = toLower(tag); + testCaseInfo.properties = + static_cast<TestCaseInfo::SpecialProperties>( + testCaseInfo.properties | parseSpecialTag(lcaseTag)); + testCaseInfo.lcaseTags.push_back(lcaseTag); } testCaseInfo.tags = std::move(tags); } - TestCaseInfo::TestCaseInfo( std::string const& _name, - std::string const& _className, - std::string const& _description, - std::vector<std::string> const& _tags, - SourceLineInfo const& _lineInfo ) - : name( _name ), - className( _className ), - description( _description ), - lineInfo( _lineInfo ), - properties( None ) - { - setTags( *this, _tags ); + TestCaseInfo::TestCaseInfo(std::string const& _name, + std::string const& _className, + std::string const& _description, + std::vector<std::string> const& _tags, + SourceLineInfo const& _lineInfo) : + name(_name), + className(_className), + description(_description), + lineInfo(_lineInfo), + properties(None) { + setTags(*this, _tags); } - bool TestCaseInfo::isHidden() const { - return ( properties & IsHidden ) != 0; - } - bool TestCaseInfo::throws() const { - return ( properties & Throws ) != 0; - } + bool TestCaseInfo::isHidden() const { return (properties & IsHidden) != 0; } + bool TestCaseInfo::throws() const { return (properties & Throws) != 0; } bool TestCaseInfo::okToFail() const { - return ( properties & (ShouldFail | MayFail ) ) != 0; + return (properties & (ShouldFail | MayFail)) != 0; } bool TestCaseInfo::expectedToFail() const { - return ( properties & (ShouldFail ) ) != 0; + return (properties & (ShouldFail)) != 0; } std::string TestCaseInfo::tagsAsString() const { @@ -14148,32 +15740,27 @@ return ret; } - TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {} + TestCase::TestCase(ITestInvoker* testCase, TestCaseInfo&& info) : + TestCaseInfo(std::move(info)), test(testCase) {} - TestCase TestCase::withName( std::string const& _newName ) const { - TestCase other( *this ); + TestCase TestCase::withName(std::string const& _newName) const { + TestCase other(*this); other.name = _newName; return other; } - void TestCase::invoke() const { - test->invoke(); + void TestCase::invoke() const { test->invoke(); } + + bool TestCase::operator==(TestCase const& other) const { + return test.get() == other.test.get() && name == other.name && + className == other.className; } - bool TestCase::operator == ( TestCase const& other ) const { - return test.get() == other.test.get() && - name == other.name && - className == other.className; - } - - bool TestCase::operator < ( TestCase const& other ) const { + bool TestCase::operator<(TestCase const& other) const { return name < other.name; } - TestCaseInfo const& TestCase::getTestCaseInfo() const - { - return *this; - } + TestCaseInfo const& TestCase::getTestCaseInfo() const { return *this; } } // end namespace Catch // end catch_test_case_info.cpp @@ -14188,21 +15775,20 @@ struct TestHasher { using hash_t = uint64_t; - explicit TestHasher( hash_t hashSuffix ): - m_hashSuffix{ hashSuffix } {} + explicit TestHasher(hash_t hashSuffix) : m_hashSuffix{hashSuffix} {} - uint32_t operator()( TestCase const& t ) const { + uint32_t operator()(TestCase const& t) const { // FNV-1a hash with multiplication fold. const hash_t prime = 1099511628211u; hash_t hash = 14695981039346656037u; - for ( const char c : t.name ) { + for (const char c : t.name) { hash ^= c; hash *= prime; } hash ^= m_hashSuffix; hash *= prime; - const uint32_t low{ static_cast<uint32_t>( hash ) }; - const uint32_t high{ static_cast<uint32_t>( hash >> 32 ) }; + const uint32_t low{static_cast<uint32_t>(hash)}; + const uint32_t high{static_cast<uint32_t>(hash >> 32)}; return low * high; } @@ -14211,40 +15797,44 @@ }; } // end unnamed namespace - std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) { - switch( config.runOrder() ) { + std::vector<TestCase> + sortTests(IConfig const& config, + std::vector<TestCase> const& unsortedTestCases) { + switch (config.runOrder()) { case RunTests::InDeclarationOrder: // already in declaration order break; case RunTests::InLexicographicalOrder: { std::vector<TestCase> sorted = unsortedTestCases; - std::sort( sorted.begin(), sorted.end() ); + std::sort(sorted.begin(), sorted.end()); return sorted; } case RunTests::InRandomOrder: { - seedRng( config ); - TestHasher h{ config.rngSeed() }; + seedRng(config); + TestHasher h{config.rngSeed()}; - using hashedTest = std::pair<TestHasher::hash_t, TestCase const*>; + using hashedTest = + std::pair<TestHasher::hash_t, TestCase const*>; std::vector<hashedTest> indexed_tests; - indexed_tests.reserve( unsortedTestCases.size() ); + indexed_tests.reserve(unsortedTestCases.size()); for (auto const& testCase : unsortedTestCases) { indexed_tests.emplace_back(h(testCase), &testCase); } - std::sort(indexed_tests.begin(), indexed_tests.end(), + std::sort(indexed_tests.begin(), + indexed_tests.end(), [](hashedTest const& lhs, hashedTest const& rhs) { - if (lhs.first == rhs.first) { - return lhs.second->name < rhs.second->name; - } - return lhs.first < rhs.first; - }); + if (lhs.first == rhs.first) { + return lhs.second->name < rhs.second->name; + } + return lhs.first < rhs.first; + }); std::vector<TestCase> sorted; - sorted.reserve( indexed_tests.size() ); + sorted.reserve(indexed_tests.size()); for (auto const& hashed : indexed_tests) { sorted.emplace_back(*hashed.second); @@ -14256,80 +15846,92 @@ return unsortedTestCases; } - bool isThrowSafe( TestCase const& testCase, IConfig const& config ) { + bool isThrowSafe(TestCase const& testCase, IConfig const& config) { return !testCase.throws() || config.allowThrows(); } - bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) { - return testSpec.matches( testCase ) && isThrowSafe( testCase, config ); + bool matchTest(TestCase const& testCase, + TestSpec const& testSpec, + IConfig const& config) { + return testSpec.matches(testCase) && isThrowSafe(testCase, config); } - void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) { + void enforceNoDuplicateTestCases(std::vector<TestCase> const& functions) { std::set<TestCase> seenFunctions; - for( auto const& function : functions ) { - auto prev = seenFunctions.insert( function ); - CATCH_ENFORCE( prev.second, - "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n" - << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n" - << "\tRedefined at " << function.getTestCaseInfo().lineInfo ); + for (auto const& function : functions) { + auto prev = seenFunctions.insert(function); + CATCH_ENFORCE(prev.second, + "error: TEST_CASE( \"" + << function.name << "\" ) already defined.\n" + << "\tFirst seen at " + << prev.first->getTestCaseInfo().lineInfo << "\n" + << "\tRedefined at " + << function.getTestCaseInfo().lineInfo); } } - std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) { + std::vector<TestCase> filterTests(std::vector<TestCase> const& testCases, + TestSpec const& testSpec, + IConfig const& config) { std::vector<TestCase> filtered; - filtered.reserve( testCases.size() ); + filtered.reserve(testCases.size()); for (auto const& testCase : testCases) { if ((!testSpec.hasFilters() && !testCase.isHidden()) || - (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) { + (testSpec.hasFilters() && + matchTest(testCase, testSpec, config))) + { filtered.push_back(testCase); } } return filtered; } - std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) { - return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config ); + std::vector<TestCase> const& getAllTestCasesSorted(IConfig const& config) { + return getRegistryHub().getTestCaseRegistry().getAllTestsSorted(config); } - void TestRegistry::registerTest( TestCase const& testCase ) { + void TestRegistry::registerTest(TestCase const& testCase) { std::string name = testCase.getTestCaseInfo().name; - if( name.empty() ) { + if (name.empty()) { ReusableStringStream rss; rss << "Anonymous test case " << ++m_unnamedCount; - return registerTest( testCase.withName( rss.str() ) ); + return registerTest(testCase.withName(rss.str())); } - m_functions.push_back( testCase ); + m_functions.push_back(testCase); } std::vector<TestCase> const& TestRegistry::getAllTests() const { return m_functions; } - std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const { - if( m_sortedFunctions.empty() ) - enforceNoDuplicateTestCases( m_functions ); + std::vector<TestCase> const& + TestRegistry::getAllTestsSorted(IConfig const& config) const { + if (m_sortedFunctions.empty()) + enforceNoDuplicateTestCases(m_functions); - if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) { - m_sortedFunctions = sortTests( config, m_functions ); + if (m_currentSortOrder != config.runOrder() || + m_sortedFunctions.empty()) { + m_sortedFunctions = sortTests(config, m_functions); m_currentSortOrder = config.runOrder(); } return m_sortedFunctions; } /////////////////////////////////////////////////////////////////////////// - TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {} + TestInvokerAsFunction::TestInvokerAsFunction( + void (*testAsFunction)()) noexcept : + m_testAsFunction(testAsFunction) {} - void TestInvokerAsFunction::invoke() const { - m_testAsFunction(); - } + void TestInvokerAsFunction::invoke() const { m_testAsFunction(); } - std::string extractClassName( StringRef const& classOrQualifiedMethodName ) { + std::string extractClassName(StringRef const& classOrQualifiedMethodName) { std::string className(classOrQualifiedMethodName); - if( startsWith( className, '&' ) ) - { - std::size_t lastColons = className.rfind( "::" ); - std::size_t penultimateColons = className.rfind( "::", lastColons-1 ); - if( penultimateColons == std::string::npos ) + if (startsWith(className, '&')) { + std::size_t lastColons = className.rfind("::"); + std::size_t penultimateColons = + className.rfind("::", lastColons - 1); + if (penultimateColons == std::string::npos) penultimateColons = 1; - className = className.substr( penultimateColons, lastColons-penultimateColons ); + className = className.substr(penultimateColons, + lastColons - penultimateColons); } return className; } @@ -14345,265 +15947,280 @@ #include <sstream> #if defined(__clang__) -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wexit-time-destructors" +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wexit-time-destructors" #endif namespace Catch { -namespace TestCaseTracking { + namespace TestCaseTracking { - NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location ) - : name( _name ), - location( _location ) - {} + NameAndLocation::NameAndLocation(std::string const& _name, + SourceLineInfo const& _location) : + name(_name), location(_location) {} - ITracker::~ITracker() = default; + ITracker::~ITracker() = default; - ITracker& TrackerContext::startRun() { - m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr ); - m_currentTracker = nullptr; - m_runState = Executing; - return *m_rootTracker; - } + ITracker& TrackerContext::startRun() { + m_rootTracker = std::make_shared<SectionTracker>( + NameAndLocation("{root}", CATCH_INTERNAL_LINEINFO), + *this, + nullptr); + m_currentTracker = nullptr; + m_runState = Executing; + return *m_rootTracker; + } - void TrackerContext::endRun() { - m_rootTracker.reset(); - m_currentTracker = nullptr; - m_runState = NotStarted; - } + void TrackerContext::endRun() { + m_rootTracker.reset(); + m_currentTracker = nullptr; + m_runState = NotStarted; + } - void TrackerContext::startCycle() { - m_currentTracker = m_rootTracker.get(); - m_runState = Executing; - } - void TrackerContext::completeCycle() { - m_runState = CompletedCycle; - } + void TrackerContext::startCycle() { + m_currentTracker = m_rootTracker.get(); + m_runState = Executing; + } + void TrackerContext::completeCycle() { m_runState = CompletedCycle; } - bool TrackerContext::completedCycle() const { - return m_runState == CompletedCycle; - } - ITracker& TrackerContext::currentTracker() { - return *m_currentTracker; - } - void TrackerContext::setCurrentTracker( ITracker* tracker ) { - m_currentTracker = tracker; - } + bool TrackerContext::completedCycle() const { + return m_runState == CompletedCycle; + } + ITracker& TrackerContext::currentTracker() { return *m_currentTracker; } + void TrackerContext::setCurrentTracker(ITracker* tracker) { + m_currentTracker = tracker; + } - TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ): - ITracker(nameAndLocation), - m_ctx( ctx ), - m_parent( parent ) - {} + TrackerBase::TrackerBase(NameAndLocation const& nameAndLocation, + TrackerContext& ctx, + ITracker* parent) : + ITracker(nameAndLocation), m_ctx(ctx), m_parent(parent) {} - bool TrackerBase::isComplete() const { - return m_runState == CompletedSuccessfully || m_runState == Failed; - } - bool TrackerBase::isSuccessfullyCompleted() const { - return m_runState == CompletedSuccessfully; - } - bool TrackerBase::isOpen() const { - return m_runState != NotStarted && !isComplete(); - } - bool TrackerBase::hasChildren() const { - return !m_children.empty(); - } + bool TrackerBase::isComplete() const { + return m_runState == CompletedSuccessfully || m_runState == Failed; + } + bool TrackerBase::isSuccessfullyCompleted() const { + return m_runState == CompletedSuccessfully; + } + bool TrackerBase::isOpen() const { + return m_runState != NotStarted && !isComplete(); + } + bool TrackerBase::hasChildren() const { return !m_children.empty(); } - void TrackerBase::addChild( ITrackerPtr const& child ) { - m_children.push_back( child ); - } + void TrackerBase::addChild(ITrackerPtr const& child) { + m_children.push_back(child); + } - ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) { - auto it = std::find_if( m_children.begin(), m_children.end(), - [&nameAndLocation]( ITrackerPtr const& tracker ){ - return - tracker->nameAndLocation().location == nameAndLocation.location && - tracker->nameAndLocation().name == nameAndLocation.name; - } ); - return( it != m_children.end() ) - ? *it - : nullptr; - } - ITracker& TrackerBase::parent() { - assert( m_parent ); // Should always be non-null except for root - return *m_parent; - } + ITrackerPtr + TrackerBase::findChild(NameAndLocation const& nameAndLocation) { + auto it = + std::find_if(m_children.begin(), + m_children.end(), + [&nameAndLocation](ITrackerPtr const& tracker) { + return tracker->nameAndLocation().location == + nameAndLocation.location && + tracker->nameAndLocation().name == + nameAndLocation.name; + }); + return (it != m_children.end()) ? *it : nullptr; + } + ITracker& TrackerBase::parent() { + assert(m_parent); // Should always be non-null except for root + return *m_parent; + } - void TrackerBase::openChild() { - if( m_runState != ExecutingChildren ) { - m_runState = ExecutingChildren; - if( m_parent ) + void TrackerBase::openChild() { + if (m_runState != ExecutingChildren) { + m_runState = ExecutingChildren; + if (m_parent) + m_parent->openChild(); + } + } + + bool TrackerBase::isSectionTracker() const { return false; } + bool TrackerBase::isGeneratorTracker() const { return false; } + + void TrackerBase::open() { + m_runState = Executing; + moveToThis(); + if (m_parent) m_parent->openChild(); } - } - bool TrackerBase::isSectionTracker() const { return false; } - bool TrackerBase::isGeneratorTracker() const { return false; } + void TrackerBase::close() { - void TrackerBase::open() { - m_runState = Executing; - moveToThis(); - if( m_parent ) - m_parent->openChild(); - } + // Close any still open children (e.g. generators) + while (&m_ctx.currentTracker() != this) + m_ctx.currentTracker().close(); - void TrackerBase::close() { + switch (m_runState) { + case NeedsAnotherRun: + break; - // Close any still open children (e.g. generators) - while( &m_ctx.currentTracker() != this ) - m_ctx.currentTracker().close(); - - switch( m_runState ) { - case NeedsAnotherRun: - break; - - case Executing: - m_runState = CompletedSuccessfully; - break; - case ExecutingChildren: - if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t){ return t->isComplete(); }) ) + case Executing: m_runState = CompletedSuccessfully; - break; + break; + case ExecutingChildren: + if (std::all_of(m_children.begin(), + m_children.end(), + [](ITrackerPtr const& t) { + return t->isComplete(); + })) + m_runState = CompletedSuccessfully; + break; - case NotStarted: - case CompletedSuccessfully: - case Failed: - CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState ); + case NotStarted: + case CompletedSuccessfully: + case Failed: + CATCH_INTERNAL_ERROR("Illogical state: " << m_runState); - default: - CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState ); + default: + CATCH_INTERNAL_ERROR("Unknown state: " << m_runState); + } + moveToParent(); + m_ctx.completeCycle(); } - moveToParent(); - m_ctx.completeCycle(); - } - void TrackerBase::fail() { - m_runState = Failed; - if( m_parent ) - m_parent->markAsNeedingAnotherRun(); - moveToParent(); - m_ctx.completeCycle(); - } - void TrackerBase::markAsNeedingAnotherRun() { - m_runState = NeedsAnotherRun; - } - - void TrackerBase::moveToParent() { - assert( m_parent ); - m_ctx.setCurrentTracker( m_parent ); - } - void TrackerBase::moveToThis() { - m_ctx.setCurrentTracker( this ); - } - - SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ) - : TrackerBase( nameAndLocation, ctx, parent ), - m_trimmed_name(trim(nameAndLocation.name)) - { - if( parent ) { - while( !parent->isSectionTracker() ) - parent = &parent->parent(); - - SectionTracker& parentSection = static_cast<SectionTracker&>( *parent ); - addNextFilters( parentSection.m_filters ); + void TrackerBase::fail() { + m_runState = Failed; + if (m_parent) + m_parent->markAsNeedingAnotherRun(); + moveToParent(); + m_ctx.completeCycle(); } - } - - bool SectionTracker::isComplete() const { - bool complete = true; - - if (m_filters.empty() - || m_filters[0] == "" - || std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) { - complete = TrackerBase::isComplete(); + void TrackerBase::markAsNeedingAnotherRun() { + m_runState = NeedsAnotherRun; } - return complete; - } - bool SectionTracker::isSectionTracker() const { return true; } - - SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) { - std::shared_ptr<SectionTracker> section; - - ITracker& currentTracker = ctx.currentTracker(); - if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) { - assert( childTracker ); - assert( childTracker->isSectionTracker() ); - section = std::static_pointer_cast<SectionTracker>( childTracker ); + void TrackerBase::moveToParent() { + assert(m_parent); + m_ctx.setCurrentTracker(m_parent); } - else { - section = std::make_shared<SectionTracker>( nameAndLocation, ctx, ¤tTracker ); - currentTracker.addChild( section ); + void TrackerBase::moveToThis() { m_ctx.setCurrentTracker(this); } + + SectionTracker::SectionTracker(NameAndLocation const& nameAndLocation, + TrackerContext& ctx, + ITracker* parent) : + TrackerBase(nameAndLocation, ctx, parent), + m_trimmed_name(trim(nameAndLocation.name)) { + if (parent) { + while (!parent->isSectionTracker()) + parent = &parent->parent(); + + SectionTracker& parentSection = + static_cast<SectionTracker&>(*parent); + addNextFilters(parentSection.m_filters); + } } - if( !ctx.completedCycle() ) - section->tryOpen(); - return *section; - } - void SectionTracker::tryOpen() { - if( !isComplete() ) - open(); - } + bool SectionTracker::isComplete() const { + bool complete = true; - void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) { - if( !filters.empty() ) { - m_filters.reserve( m_filters.size() + filters.size() + 2 ); - m_filters.emplace_back(""); // Root - should never be consulted - m_filters.emplace_back(""); // Test Case - not a section filter - m_filters.insert( m_filters.end(), filters.begin(), filters.end() ); + if (m_filters.empty() || m_filters[0] == "" || + std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != + m_filters.end()) + { + complete = TrackerBase::isComplete(); + } + return complete; } - } - void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) { - if( filters.size() > 1 ) - m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() ); - } - std::vector<std::string> const& SectionTracker::getFilters() const { - return m_filters; - } + bool SectionTracker::isSectionTracker() const { return true; } - std::string const& SectionTracker::trimmedName() const { - return m_trimmed_name; - } + SectionTracker& + SectionTracker::acquire(TrackerContext& ctx, + NameAndLocation const& nameAndLocation) { + std::shared_ptr<SectionTracker> section; -} // namespace TestCaseTracking + ITracker& currentTracker = ctx.currentTracker(); + if (ITrackerPtr childTracker = + currentTracker.findChild(nameAndLocation)) { + assert(childTracker); + assert(childTracker->isSectionTracker()); + section = + std::static_pointer_cast<SectionTracker>(childTracker); + } else { + section = std::make_shared<SectionTracker>( + nameAndLocation, ctx, ¤tTracker); + currentTracker.addChild(section); + } + if (!ctx.completedCycle()) + section->tryOpen(); + return *section; + } -using TestCaseTracking::ITracker; -using TestCaseTracking::TrackerContext; -using TestCaseTracking::SectionTracker; + void SectionTracker::tryOpen() { + if (!isComplete()) + open(); + } + + void SectionTracker::addInitialFilters( + std::vector<std::string> const& filters) { + if (!filters.empty()) { + m_filters.reserve(m_filters.size() + filters.size() + 2); + m_filters.emplace_back(""); // Root - should never be consulted + m_filters.emplace_back(""); // Test Case - not a section filter + m_filters.insert( + m_filters.end(), filters.begin(), filters.end()); + } + } + void SectionTracker::addNextFilters( + std::vector<std::string> const& filters) { + if (filters.size() > 1) + m_filters.insert( + m_filters.end(), filters.begin() + 1, filters.end()); + } + + std::vector<std::string> const& SectionTracker::getFilters() const { + return m_filters; + } + + std::string const& SectionTracker::trimmedName() const { + return m_trimmed_name; + } + + } // namespace TestCaseTracking + + using TestCaseTracking::ITracker; + using TestCaseTracking::SectionTracker; + using TestCaseTracking::TrackerContext; } // namespace Catch #if defined(__clang__) -# pragma clang diagnostic pop +#pragma clang diagnostic pop #endif // end catch_test_case_tracker.cpp // start catch_test_registry.cpp namespace Catch { - auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* { - return new(std::nothrow) TestInvokerAsFunction( testAsFunction ); + auto makeTestInvoker(void (*testAsFunction)()) noexcept -> ITestInvoker* { + return new (std::nothrow) TestInvokerAsFunction(testAsFunction); } - NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {} + NameAndTags::NameAndTags(StringRef const& name_, + StringRef const& tags_) noexcept : + name(name_), tags(tags_) {} - AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept { + AutoReg::AutoReg(ITestInvoker* invoker, + SourceLineInfo const& lineInfo, + StringRef const& classOrMethod, + NameAndTags const& nameAndTags) noexcept { CATCH_TRY { - getMutableRegistryHub() - .registerTest( - makeTestCase( - invoker, - extractClassName( classOrMethod ), - nameAndTags, - lineInfo)); - } CATCH_CATCH_ALL { - // Do not throw when constructing global objects, instead register the exception to be processed later + getMutableRegistryHub().registerTest( + makeTestCase(invoker, + extractClassName(classOrMethod), + nameAndTags, + lineInfo)); + } + CATCH_CATCH_ALL { + // Do not throw when constructing global objects, instead register + // the exception to be processed later getMutableRegistryHub().registerStartupException(); } } AutoReg::~AutoReg() = default; -} +} // namespace Catch // end catch_test_registry.cpp // start catch_test_spec.cpp @@ -14614,104 +16231,110 @@ namespace Catch { - TestSpec::Pattern::Pattern( std::string const& name ) - : m_name( name ) - {} + TestSpec::Pattern::Pattern(std::string const& name) : m_name(name) {} TestSpec::Pattern::~Pattern() = default; - std::string const& TestSpec::Pattern::name() const { - return m_name; + std::string const& TestSpec::Pattern::name() const { return m_name; } + + TestSpec::NamePattern::NamePattern(std::string const& name, + std::string const& filterString) : + Pattern(filterString), + m_wildcardPattern(toLower(name), CaseSensitive::No) {} + + bool TestSpec::NamePattern::matches(TestCaseInfo const& testCase) const { + return m_wildcardPattern.matches(testCase.name); } - TestSpec::NamePattern::NamePattern( std::string const& name, std::string const& filterString ) - : Pattern( filterString ) - , m_wildcardPattern( toLower( name ), CaseSensitive::No ) - {} + TestSpec::TagPattern::TagPattern(std::string const& tag, + std::string const& filterString) : + Pattern(filterString), m_tag(toLower(tag)) {} - bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const { - return m_wildcardPattern.matches( testCase.name ); - } - - TestSpec::TagPattern::TagPattern( std::string const& tag, std::string const& filterString ) - : Pattern( filterString ) - , m_tag( toLower( tag ) ) - {} - - bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const { + bool TestSpec::TagPattern::matches(TestCaseInfo const& testCase) const { return std::find(begin(testCase.lcaseTags), end(testCase.lcaseTags), m_tag) != end(testCase.lcaseTags); } - TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) - : Pattern( underlyingPattern->name() ) - , m_underlyingPattern( underlyingPattern ) - {} + TestSpec::ExcludedPattern::ExcludedPattern( + PatternPtr const& underlyingPattern) : + Pattern(underlyingPattern->name()), + m_underlyingPattern(underlyingPattern) {} - bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { - return !m_underlyingPattern->matches( testCase ); + bool + TestSpec::ExcludedPattern::matches(TestCaseInfo const& testCase) const { + return !m_underlyingPattern->matches(testCase); } - bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const { - return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr const& p ){ return p->matches( testCase ); } ); + bool TestSpec::Filter::matches(TestCaseInfo const& testCase) const { + return std::all_of( + m_patterns.begin(), m_patterns.end(), [&](PatternPtr const& p) { + return p->matches(testCase); + }); } std::string TestSpec::Filter::name() const { std::string name; - for( auto const& p : m_patterns ) + for (auto const& p : m_patterns) name += p->name(); return name; } - bool TestSpec::hasFilters() const { - return !m_filters.empty(); + bool TestSpec::hasFilters() const { return !m_filters.empty(); } + + bool TestSpec::matches(TestCaseInfo const& testCase) const { + return std::any_of( + m_filters.begin(), m_filters.end(), [&](Filter const& f) { + return f.matches(testCase); + }); } - bool TestSpec::matches( TestCaseInfo const& testCase ) const { - return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter const& f ){ return f.matches( testCase ); } ); - } - - TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const - { - Matches matches( m_filters.size() ); - std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter const& filter ){ - std::vector<TestCase const*> currentMatches; - for( auto const& test : testCases ) - if( isThrowSafe( test, config ) && filter.matches( test ) ) - currentMatches.emplace_back( &test ); - return FilterMatch{ filter.name(), currentMatches }; - } ); + TestSpec::Matches + TestSpec::matchesByFilter(std::vector<TestCase> const& testCases, + IConfig const& config) const { + Matches matches(m_filters.size()); + std::transform(m_filters.begin(), + m_filters.end(), + matches.begin(), + [&](Filter const& filter) { + std::vector<TestCase const*> currentMatches; + for (auto const& test : testCases) + if (isThrowSafe(test, config) && + filter.matches(test)) + currentMatches.emplace_back(&test); + return FilterMatch{filter.name(), currentMatches}; + }); return matches; } - const TestSpec::vectorStrings& TestSpec::getInvalidArgs() const{ - return (m_invalidArgs); + const TestSpec::vectorStrings& TestSpec::getInvalidArgs() const { + return (m_invalidArgs); } -} +} // namespace Catch // end catch_test_spec.cpp // start catch_test_spec_parser.cpp namespace Catch { - TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {} + TestSpecParser::TestSpecParser(ITagAliasRegistry const& tagAliases) : + m_tagAliases(&tagAliases) {} - TestSpecParser& TestSpecParser::parse( std::string const& arg ) { + TestSpecParser& TestSpecParser::parse(std::string const& arg) { m_mode = None; m_exclusion = false; - m_arg = m_tagAliases->expandAliases( arg ); + m_arg = m_tagAliases->expandAliases(arg); m_escapeChars.clear(); m_substring.reserve(m_arg.size()); m_patternName.reserve(m_arg.size()); m_realPatternPos = 0; - for( m_pos = 0; m_pos < m_arg.size(); ++m_pos ) - //if visitChar fails - if( !visitChar( m_arg[m_pos] ) ){ - m_testSpec.m_invalidArgs.push_back(arg); - break; - } + for (m_pos = 0; m_pos < m_arg.size(); ++m_pos) + // if visitChar fails + if (!visitChar(m_arg[m_pos])) { + m_testSpec.m_invalidArgs.push_back(arg); + break; + } endMode(); return *this; } @@ -14719,37 +16342,37 @@ addFilter(); return m_testSpec; } - bool TestSpecParser::visitChar( char c ) { - if( (m_mode != EscapedName) && (c == '\\') ) { + bool TestSpecParser::visitChar(char c) { + if ((m_mode != EscapedName) && (c == '\\')) { escape(); addCharToPattern(c); return true; - }else if((m_mode != EscapedName) && (c == ',') ) { + } else if ((m_mode != EscapedName) && (c == ',')) { return separate(); } - switch( m_mode ) { - case None: - if( processNoneChar( c ) ) + switch (m_mode) { + case None: + if (processNoneChar(c)) + return true; + break; + case Name: + processNameChar(c); + break; + case EscapedName: + endMode(); + addCharToPattern(c); return true; - break; - case Name: - processNameChar( c ); - break; - case EscapedName: - endMode(); - addCharToPattern(c); - return true; - default: - case Tag: - case QuotedName: - if( processOtherChar( c ) ) - return true; - break; + default: + case Tag: + case QuotedName: + if (processOtherChar(c)) + return true; + break; } m_substring += c; - if( !isControlChar( c ) ) { + if (!isControlChar(c)) { m_patternName += c; m_realPatternPos++; } @@ -14757,56 +16380,54 @@ } // Two of the processing methods return true to signal the caller to return // without adding the given character to the current pattern strings - bool TestSpecParser::processNoneChar( char c ) { - switch( c ) { - case ' ': - return true; - case '~': - m_exclusion = true; - return false; - case '[': - startNewMode( Tag ); - return false; - case '"': - startNewMode( QuotedName ); - return false; - default: - startNewMode( Name ); - return false; + bool TestSpecParser::processNoneChar(char c) { + switch (c) { + case ' ': + return true; + case '~': + m_exclusion = true; + return false; + case '[': + startNewMode(Tag); + return false; + case '"': + startNewMode(QuotedName); + return false; + default: + startNewMode(Name); + return false; } } - void TestSpecParser::processNameChar( char c ) { - if( c == '[' ) { - if( m_substring == "exclude:" ) + void TestSpecParser::processNameChar(char c) { + if (c == '[') { + if (m_substring == "exclude:") m_exclusion = true; else endMode(); - startNewMode( Tag ); + startNewMode(Tag); } } - bool TestSpecParser::processOtherChar( char c ) { - if( !isControlChar( c ) ) + bool TestSpecParser::processOtherChar(char c) { + if (!isControlChar(c)) return false; m_substring += c; endMode(); return true; } - void TestSpecParser::startNewMode( Mode mode ) { - m_mode = mode; - } + void TestSpecParser::startNewMode(Mode mode) { m_mode = mode; } void TestSpecParser::endMode() { - switch( m_mode ) { - case Name: - case QuotedName: - return addNamePattern(); - case Tag: - return addTagPattern(); - case EscapedName: - revertBackToLastMode(); - return; - case None: - default: - return startNewMode( None ); + switch (m_mode) { + case Name: + case QuotedName: + return addNamePattern(); + case Tag: + return addTagPattern(); + case EscapedName: + revertBackToLastMode(); + return; + case None: + default: + return startNewMode(None); } } void TestSpecParser::escape() { @@ -14814,8 +16435,8 @@ m_mode = EscapedName; m_escapeChars.push_back(m_realPatternPos); } - bool TestSpecParser::isControlChar( char c ) const { - switch( m_mode ) { + bool TestSpecParser::isControlChar(char c) const { + switch (m_mode) { default: return false; case None: @@ -14832,39 +16453,36 @@ } void TestSpecParser::addFilter() { - if( !m_currentFilter.m_patterns.empty() ) { - m_testSpec.m_filters.push_back( m_currentFilter ); + if (!m_currentFilter.m_patterns.empty()) { + m_testSpec.m_filters.push_back(m_currentFilter); m_currentFilter = TestSpec::Filter(); } } - void TestSpecParser::saveLastMode() { - lastMode = m_mode; - } + void TestSpecParser::saveLastMode() { lastMode = m_mode; } - void TestSpecParser::revertBackToLastMode() { - m_mode = lastMode; - } + void TestSpecParser::revertBackToLastMode() { m_mode = lastMode; } bool TestSpecParser::separate() { - if( (m_mode==QuotedName) || (m_mode==Tag) ){ - //invalid argument, signal failure to previous scope. - m_mode = None; - m_pos = m_arg.size(); - m_substring.clear(); - m_patternName.clear(); - m_realPatternPos = 0; - return false; - } - endMode(); - addFilter(); - return true; //success + if ((m_mode == QuotedName) || (m_mode == Tag)) { + // invalid argument, signal failure to previous scope. + m_mode = None; + m_pos = m_arg.size(); + m_substring.clear(); + m_patternName.clear(); + m_realPatternPos = 0; + return false; + } + endMode(); + addFilter(); + return true; // success } std::string TestSpecParser::preprocessPattern() { std::string token = m_patternName; for (std::size_t i = 0; i < m_escapeChars.size(); ++i) - token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1); + token = token.substr(0, m_escapeChars[i] - i) + + token.substr(m_escapeChars[i] - i + 1); m_escapeChars.clear(); if (startsWith(token, "exclude:")) { m_exclusion = true; @@ -14881,7 +16499,8 @@ auto token = preprocessPattern(); if (!token.empty()) { - TestSpec::PatternPtr pattern = std::make_shared<TestSpec::NamePattern>(token, m_substring); + TestSpec::PatternPtr pattern = + std::make_shared<TestSpec::NamePattern>(token, m_substring); if (m_exclusion) pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern); m_currentFilter.m_patterns.push_back(pattern); @@ -14899,14 +16518,17 @@ // we have to create a separate hide tag and shorten the real one if (token.size() > 1 && token[0] == '.') { token.erase(token.begin()); - TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(".", m_substring); + TestSpec::PatternPtr pattern = + std::make_shared<TestSpec::TagPattern>(".", m_substring); if (m_exclusion) { - pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern); + pattern = + std::make_shared<TestSpec::ExcludedPattern>(pattern); } m_currentFilter.m_patterns.push_back(pattern); } - TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(token, m_substring); + TestSpec::PatternPtr pattern = + std::make_shared<TestSpec::TagPattern>(token, m_substring); if (m_exclusion) { pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern); @@ -14918,8 +16540,8 @@ m_mode = None; } - TestSpec parseTestSpec( std::string const& arg ) { - return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec(); + TestSpec parseTestSpec(std::string const& arg) { + return TestSpecParser(ITagAliasRegistry::get()).parse(arg).testSpec(); } } // namespace Catch @@ -14933,7 +16555,9 @@ namespace Catch { auto getCurrentNanosecondsSinceEpoch() -> uint64_t { - return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count(); + return std::chrono::duration_cast<std::chrono::nanoseconds>( + std::chrono::high_resolution_clock::now().time_since_epoch()) + .count(); } namespace { @@ -14943,49 +16567,49 @@ auto startTime = getCurrentNanosecondsSinceEpoch(); - for( std::size_t i = 0; i < iterations; ++i ) { + for (std::size_t i = 0; i < iterations; ++i) { uint64_t ticks; uint64_t baseTicks = getCurrentNanosecondsSinceEpoch(); do { ticks = getCurrentNanosecondsSinceEpoch(); - } while( ticks == baseTicks ); + } while (ticks == baseTicks); auto delta = ticks - baseTicks; sum += delta; // If we have been calibrating for over 3 seconds -- the clock // is terrible and we should move on. - // TBD: How to signal that the measured resolution is probably wrong? + // TBD: How to signal that the measured resolution is probably + // wrong? if (ticks > startTime + 3 * nanosecondsInSecond) { - return sum / ( i + 1u ); + return sum / (i + 1u); } } - // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers + // We're just taking the mean, here. To do better we could take the + // std. dev and exclude outliers // - and potentially do more iterations if there's a high variance. - return sum/iterations; + return sum / iterations; } - } + } // namespace auto getEstimatedClockResolution() -> uint64_t { static auto s_resolution = estimateClockResolution(); return s_resolution; } - void Timer::start() { - m_nanoseconds = getCurrentNanosecondsSinceEpoch(); - } + void Timer::start() { m_nanoseconds = getCurrentNanosecondsSinceEpoch(); } auto Timer::getElapsedNanoseconds() const -> uint64_t { return getCurrentNanosecondsSinceEpoch() - m_nanoseconds; } auto Timer::getElapsedMicroseconds() const -> uint64_t { - return getElapsedNanoseconds()/1000; + return getElapsedNanoseconds() / 1000; } auto Timer::getElapsedMilliseconds() const -> unsigned int { - return static_cast<unsigned int>(getElapsedMicroseconds()/1000); + return static_cast<unsigned int>(getElapsedMicroseconds() / 1000); } auto Timer::getElapsedSeconds() const -> double { - return getElapsedMicroseconds()/1000000.0; + return getElapsedMicroseconds() / 1000000.0; } } // namespace Catch @@ -14993,9 +16617,9 @@ // start catch_tostring.cpp #if defined(__clang__) -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wexit-time-destructors" -# pragma clang diagnostic ignored "-Wglobal-constructors" +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wexit-time-destructors" +#pragma clang diagnostic ignored "-Wglobal-constructors" #endif // Enable specific decls locally @@ -15008,237 +16632,239 @@ namespace Catch { -namespace Detail { + namespace Detail { - const std::string unprintableString = "{?}"; + const std::string unprintableString = "{?}"; - namespace { - const int hexThreshold = 255; + namespace { + const int hexThreshold = 255; - struct Endianness { - enum Arch { Big, Little }; + struct Endianness { + enum Arch { Big, Little }; - static Arch which() { - int one = 1; - // If the lowest byte we read is non-zero, we can assume - // that little endian format is used. - auto value = *reinterpret_cast<char*>(&one); - return value ? Little : Big; + static Arch which() { + int one = 1; + // If the lowest byte we read is non-zero, we can assume + // that little endian format is used. + auto value = *reinterpret_cast<char*>(&one); + return value ? Little : Big; + } + }; + } // namespace + + std::string rawMemoryToString(const void* object, std::size_t size) { + // Reverse order for little endian architectures + int i = 0, end = static_cast<int>(size), inc = 1; + if (Endianness::which() == Endianness::Little) { + i = end - 1; + end = inc = -1; } - }; - } - std::string rawMemoryToString( const void *object, std::size_t size ) { - // Reverse order for little endian architectures - int i = 0, end = static_cast<int>( size ), inc = 1; - if( Endianness::which() == Endianness::Little ) { - i = end-1; - end = inc = -1; + unsigned char const* bytes = + static_cast<unsigned char const*>(object); + ReusableStringStream rss; + rss << "0x" << std::setfill('0') << std::hex; + for (; i != end; i += inc) + rss << std::setw(2) << static_cast<unsigned>(bytes[i]); + return rss.str(); + } + } // namespace Detail + + template <typename T> std::string fpToString(T value, int precision) { + if (Catch::isnan(value)) { + return "nan"; } - unsigned char const *bytes = static_cast<unsigned char const *>(object); ReusableStringStream rss; - rss << "0x" << std::setfill('0') << std::hex; - for( ; i != end; i += inc ) - rss << std::setw(2) << static_cast<unsigned>(bytes[i]); - return rss.str(); - } -} - -template<typename T> -std::string fpToString( T value, int precision ) { - if (Catch::isnan(value)) { - return "nan"; - } - - ReusableStringStream rss; - rss << std::setprecision( precision ) - << std::fixed - << value; - std::string d = rss.str(); - std::size_t i = d.find_last_not_of( '0' ); - if( i != std::string::npos && i != d.size()-1 ) { - if( d[i] == '.' ) - i++; - d = d.substr( 0, i+1 ); - } - return d; -} - -//// ======================================================= //// -// -// Out-of-line defs for full specialization of StringMaker -// -//// ======================================================= //// - -std::string StringMaker<std::string>::convert(const std::string& str) { - if (!getCurrentContext().getConfig()->showInvisibles()) { - return '"' + str + '"'; - } - - std::string s("\""); - for (char c : str) { - switch (c) { - case '\n': - s.append("\\n"); - break; - case '\t': - s.append("\\t"); - break; - default: - s.push_back(c); - break; + rss << std::setprecision(precision) << std::fixed << value; + std::string d = rss.str(); + std::size_t i = d.find_last_not_of('0'); + if (i != std::string::npos && i != d.size() - 1) { + if (d[i] == '.') + i++; + d = d.substr(0, i + 1); } + return d; } - s.append("\""); - return s; -} + + //// ======================================================= //// + // + // Out-of-line defs for full specialization of StringMaker + // + //// ======================================================= //// + + std::string StringMaker<std::string>::convert(const std::string& str) { + if (!getCurrentContext().getConfig()->showInvisibles()) { + return '"' + str + '"'; + } + + std::string s("\""); + for (char c : str) { + switch (c) { + case '\n': + s.append("\\n"); + break; + case '\t': + s.append("\\t"); + break; + default: + s.push_back(c); + break; + } + } + s.append("\""); + return s; + } #ifdef CATCH_CONFIG_CPP17_STRING_VIEW -std::string StringMaker<std::string_view>::convert(std::string_view str) { - return ::Catch::Detail::stringify(std::string{ str }); -} + std::string StringMaker<std::string_view>::convert(std::string_view str) { + return ::Catch::Detail::stringify(std::string{str}); + } #endif -std::string StringMaker<char const*>::convert(char const* str) { - if (str) { - return ::Catch::Detail::stringify(std::string{ str }); - } else { - return{ "{null string}" }; + std::string StringMaker<char const*>::convert(char const* str) { + if (str) { + return ::Catch::Detail::stringify(std::string{str}); + } else { + return {"{null string}"}; + } } -} -std::string StringMaker<char*>::convert(char* str) { - if (str) { - return ::Catch::Detail::stringify(std::string{ str }); - } else { - return{ "{null string}" }; + std::string StringMaker<char*>::convert(char* str) { + if (str) { + return ::Catch::Detail::stringify(std::string{str}); + } else { + return {"{null string}"}; + } } -} #ifdef CATCH_CONFIG_WCHAR -std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) { - std::string s; - s.reserve(wstr.size()); - for (auto c : wstr) { - s += (c <= 0xff) ? static_cast<char>(c) : '?'; + std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) { + std::string s; + s.reserve(wstr.size()); + for (auto c : wstr) { + s += (c <= 0xff) ? static_cast<char>(c) : '?'; + } + return ::Catch::Detail::stringify(s); } - return ::Catch::Detail::stringify(s); -} -# ifdef CATCH_CONFIG_CPP17_STRING_VIEW -std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) { - return StringMaker<std::wstring>::convert(std::wstring(str)); -} -# endif +#ifdef CATCH_CONFIG_CPP17_STRING_VIEW + std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) { + return StringMaker<std::wstring>::convert(std::wstring(str)); + } +#endif -std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) { - if (str) { - return ::Catch::Detail::stringify(std::wstring{ str }); - } else { - return{ "{null string}" }; + std::string StringMaker<wchar_t const*>::convert(wchar_t const* str) { + if (str) { + return ::Catch::Detail::stringify(std::wstring{str}); + } else { + return {"{null string}"}; + } } -} -std::string StringMaker<wchar_t *>::convert(wchar_t * str) { - if (str) { - return ::Catch::Detail::stringify(std::wstring{ str }); - } else { - return{ "{null string}" }; + std::string StringMaker<wchar_t*>::convert(wchar_t* str) { + if (str) { + return ::Catch::Detail::stringify(std::wstring{str}); + } else { + return {"{null string}"}; + } } -} #endif #if defined(CATCH_CONFIG_CPP17_BYTE) #include <cstddef> -std::string StringMaker<std::byte>::convert(std::byte value) { - return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value)); -} + std::string StringMaker<std::byte>::convert(std::byte value) { + return ::Catch::Detail::stringify( + std::to_integer<unsigned long long>(value)); + } #endif // defined(CATCH_CONFIG_CPP17_BYTE) -std::string StringMaker<int>::convert(int value) { - return ::Catch::Detail::stringify(static_cast<long long>(value)); -} -std::string StringMaker<long>::convert(long value) { - return ::Catch::Detail::stringify(static_cast<long long>(value)); -} -std::string StringMaker<long long>::convert(long long value) { - ReusableStringStream rss; - rss << value; - if (value > Detail::hexThreshold) { - rss << " (0x" << std::hex << value << ')'; + std::string StringMaker<int>::convert(int value) { + return ::Catch::Detail::stringify(static_cast<long long>(value)); } - return rss.str(); -} - -std::string StringMaker<unsigned int>::convert(unsigned int value) { - return ::Catch::Detail::stringify(static_cast<unsigned long long>(value)); -} -std::string StringMaker<unsigned long>::convert(unsigned long value) { - return ::Catch::Detail::stringify(static_cast<unsigned long long>(value)); -} -std::string StringMaker<unsigned long long>::convert(unsigned long long value) { - ReusableStringStream rss; - rss << value; - if (value > Detail::hexThreshold) { - rss << " (0x" << std::hex << value << ')'; + std::string StringMaker<long>::convert(long value) { + return ::Catch::Detail::stringify(static_cast<long long>(value)); } - return rss.str(); -} - -std::string StringMaker<bool>::convert(bool b) { - return b ? "true" : "false"; -} - -std::string StringMaker<signed char>::convert(signed char value) { - if (value == '\r') { - return "'\\r'"; - } else if (value == '\f') { - return "'\\f'"; - } else if (value == '\n') { - return "'\\n'"; - } else if (value == '\t') { - return "'\\t'"; - } else if ('\0' <= value && value < ' ') { - return ::Catch::Detail::stringify(static_cast<unsigned int>(value)); - } else { - char chstr[] = "' '"; - chstr[1] = value; - return chstr; + std::string StringMaker<long long>::convert(long long value) { + ReusableStringStream rss; + rss << value; + if (value > Detail::hexThreshold) { + rss << " (0x" << std::hex << value << ')'; + } + return rss.str(); } -} -std::string StringMaker<char>::convert(char c) { - return ::Catch::Detail::stringify(static_cast<signed char>(c)); -} -std::string StringMaker<unsigned char>::convert(unsigned char c) { - return ::Catch::Detail::stringify(static_cast<char>(c)); -} -std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) { - return "nullptr"; -} + std::string StringMaker<unsigned int>::convert(unsigned int value) { + return ::Catch::Detail::stringify( + static_cast<unsigned long long>(value)); + } + std::string StringMaker<unsigned long>::convert(unsigned long value) { + return ::Catch::Detail::stringify( + static_cast<unsigned long long>(value)); + } + std::string + StringMaker<unsigned long long>::convert(unsigned long long value) { + ReusableStringStream rss; + rss << value; + if (value > Detail::hexThreshold) { + rss << " (0x" << std::hex << value << ')'; + } + return rss.str(); + } -int StringMaker<float>::precision = 5; + std::string StringMaker<bool>::convert(bool b) { + return b ? "true" : "false"; + } -std::string StringMaker<float>::convert(float value) { - return fpToString(value, precision) + 'f'; -} + std::string StringMaker<signed char>::convert(signed char value) { + if (value == '\r') { + return "'\\r'"; + } else if (value == '\f') { + return "'\\f'"; + } else if (value == '\n') { + return "'\\n'"; + } else if (value == '\t') { + return "'\\t'"; + } else if ('\0' <= value && value < ' ') { + return ::Catch::Detail::stringify(static_cast<unsigned int>(value)); + } else { + char chstr[] = "' '"; + chstr[1] = value; + return chstr; + } + } + std::string StringMaker<char>::convert(char c) { + return ::Catch::Detail::stringify(static_cast<signed char>(c)); + } + std::string StringMaker<unsigned char>::convert(unsigned char c) { + return ::Catch::Detail::stringify(static_cast<char>(c)); + } -int StringMaker<double>::precision = 10; + std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) { + return "nullptr"; + } -std::string StringMaker<double>::convert(double value) { - return fpToString(value, precision); -} + int StringMaker<float>::precision = 5; -std::string ratio_string<std::atto>::symbol() { return "a"; } -std::string ratio_string<std::femto>::symbol() { return "f"; } -std::string ratio_string<std::pico>::symbol() { return "p"; } -std::string ratio_string<std::nano>::symbol() { return "n"; } -std::string ratio_string<std::micro>::symbol() { return "u"; } -std::string ratio_string<std::milli>::symbol() { return "m"; } + std::string StringMaker<float>::convert(float value) { + return fpToString(value, precision) + 'f'; + } + + int StringMaker<double>::precision = 10; + + std::string StringMaker<double>::convert(double value) { + return fpToString(value, precision); + } + + std::string ratio_string<std::atto>::symbol() { return "a"; } + std::string ratio_string<std::femto>::symbol() { return "f"; } + std::string ratio_string<std::pico>::symbol() { return "p"; } + std::string ratio_string<std::nano>::symbol() { return "n"; } + std::string ratio_string<std::micro>::symbol() { return "u"; } + std::string ratio_string<std::milli>::symbol() { return "m"; } } // end namespace Catch #if defined(__clang__) -# pragma clang diagnostic pop +#pragma clang diagnostic pop #endif // end catch_tostring.cpp @@ -15246,7 +16872,7 @@ namespace Catch { - Counts Counts::operator - ( Counts const& other ) const { + Counts Counts::operator-(Counts const& other) const { Counts diff; diff.passed = passed - other.passed; diff.failed = failed - other.failed; @@ -15254,48 +16880,42 @@ return diff; } - Counts& Counts::operator += ( Counts const& other ) { + Counts& Counts::operator+=(Counts const& other) { passed += other.passed; failed += other.failed; failedButOk += other.failedButOk; return *this; } - std::size_t Counts::total() const { - return passed + failed + failedButOk; - } - bool Counts::allPassed() const { - return failed == 0 && failedButOk == 0; - } - bool Counts::allOk() const { - return failed == 0; - } + std::size_t Counts::total() const { return passed + failed + failedButOk; } + bool Counts::allPassed() const { return failed == 0 && failedButOk == 0; } + bool Counts::allOk() const { return failed == 0; } - Totals Totals::operator - ( Totals const& other ) const { + Totals Totals::operator-(Totals const& other) const { Totals diff; diff.assertions = assertions - other.assertions; diff.testCases = testCases - other.testCases; return diff; } - Totals& Totals::operator += ( Totals const& other ) { + Totals& Totals::operator+=(Totals const& other) { assertions += other.assertions; testCases += other.testCases; return *this; } - Totals Totals::delta( Totals const& prevTotals ) const { + Totals Totals::delta(Totals const& prevTotals) const { Totals diff = *this - prevTotals; - if( diff.assertions.failed > 0 ) + if (diff.assertions.failed > 0) ++diff.testCases.failed; - else if( diff.assertions.failedButOk > 0 ) + else if (diff.assertions.failedButOk > 0) ++diff.testCases.failedButOk; else ++diff.testCases.passed; return diff; } -} +} // namespace Catch // end catch_totals.cpp // start catch_uncaught_exceptions.cpp @@ -15312,24 +16932,24 @@ #define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP #if defined(_MSC_VER) -# if _MSC_VER >= 1900 // Visual Studio 2015 or newer -# define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS -# endif +#if _MSC_VER >= 1900 // Visual Studio 2015 or newer +#define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS +#endif #endif #include <exception> -#if defined(__cpp_lib_uncaught_exceptions) \ - && !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) +#if defined(__cpp_lib_uncaught_exceptions) && \ + !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) -# define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS +#define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS #endif // __cpp_lib_uncaught_exceptions -#if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) \ - && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) \ - && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) +#if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && \ + !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && \ + !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) -# define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS +#define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS #endif #endif // CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP @@ -15345,7 +16965,7 @@ #else return std::uncaught_exception(); #endif - } + } } // end namespace Catch // end catch_uncaught_exceptions.cpp // start catch_version.cpp @@ -15354,76 +16974,73 @@ namespace Catch { - Version::Version - ( unsigned int _majorVersion, - unsigned int _minorVersion, - unsigned int _patchNumber, - char const * const _branchName, - unsigned int _buildNumber ) - : majorVersion( _majorVersion ), - minorVersion( _minorVersion ), - patchNumber( _patchNumber ), - branchName( _branchName ), - buildNumber( _buildNumber ) - {} + Version::Version(unsigned int _majorVersion, + unsigned int _minorVersion, + unsigned int _patchNumber, + char const* const _branchName, + unsigned int _buildNumber) : + majorVersion(_majorVersion), + minorVersion(_minorVersion), + patchNumber(_patchNumber), + branchName(_branchName), + buildNumber(_buildNumber) {} - std::ostream& operator << ( std::ostream& os, Version const& version ) { - os << version.majorVersion << '.' - << version.minorVersion << '.' - << version.patchNumber; + std::ostream& operator<<(std::ostream& os, Version const& version) { + os << version.majorVersion << '.' << version.minorVersion << '.' + << version.patchNumber; // branchName is never null -> 0th char is \0 if it is empty if (version.branchName[0]) { - os << '-' << version.branchName - << '.' << version.buildNumber; + os << '-' << version.branchName << '.' << version.buildNumber; } return os; } Version const& libraryVersion() { - static Version version( 2, 13, 7, "", 0 ); + static Version version(2, 13, 7, "", 0); return version; } -} +} // namespace Catch // end catch_version.cpp // start catch_wildcard_pattern.cpp namespace Catch { - WildcardPattern::WildcardPattern( std::string const& pattern, - CaseSensitive::Choice caseSensitivity ) - : m_caseSensitivity( caseSensitivity ), - m_pattern( normaliseString( pattern ) ) - { - if( startsWith( m_pattern, '*' ) ) { - m_pattern = m_pattern.substr( 1 ); + WildcardPattern::WildcardPattern(std::string const& pattern, + CaseSensitive::Choice caseSensitivity) : + m_caseSensitivity(caseSensitivity), + m_pattern(normaliseString(pattern)) { + if (startsWith(m_pattern, '*')) { + m_pattern = m_pattern.substr(1); m_wildcard = WildcardAtStart; } - if( endsWith( m_pattern, '*' ) ) { - m_pattern = m_pattern.substr( 0, m_pattern.size()-1 ); - m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd ); + if (endsWith(m_pattern, '*')) { + m_pattern = m_pattern.substr(0, m_pattern.size() - 1); + m_wildcard = + static_cast<WildcardPosition>(m_wildcard | WildcardAtEnd); } } - bool WildcardPattern::matches( std::string const& str ) const { - switch( m_wildcard ) { + bool WildcardPattern::matches(std::string const& str) const { + switch (m_wildcard) { case NoWildcard: - return m_pattern == normaliseString( str ); + return m_pattern == normaliseString(str); case WildcardAtStart: - return endsWith( normaliseString( str ), m_pattern ); + return endsWith(normaliseString(str), m_pattern); case WildcardAtEnd: - return startsWith( normaliseString( str ), m_pattern ); + return startsWith(normaliseString(str), m_pattern); case WildcardAtBothEnds: - return contains( normaliseString( str ), m_pattern ); + return contains(normaliseString(str), m_pattern); default: - CATCH_INTERNAL_ERROR( "Unknown enum" ); + CATCH_INTERNAL_ERROR("Unknown enum"); } } - std::string WildcardPattern::normaliseString( std::string const& str ) const { - return trim( m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str ); + std::string WildcardPattern::normaliseString(std::string const& str) const { + return trim(m_caseSensitivity == CaseSensitive::No ? toLower(str) + : str); } -} +} // namespace Catch // end catch_wildcard_pattern.cpp // start catch_xmlwriter.cpp @@ -15432,184 +17049,190 @@ namespace Catch { -namespace { + namespace { - size_t trailingBytes(unsigned char c) { - if ((c & 0xE0) == 0xC0) { - return 2; + size_t trailingBytes(unsigned char c) { + if ((c & 0xE0) == 0xC0) { + return 2; + } + if ((c & 0xF0) == 0xE0) { + return 3; + } + if ((c & 0xF8) == 0xF0) { + return 4; + } + CATCH_INTERNAL_ERROR( + "Invalid multibyte utf-8 start byte encountered"); } - if ((c & 0xF0) == 0xE0) { - return 3; + + uint32_t headerValue(unsigned char c) { + if ((c & 0xE0) == 0xC0) { + return c & 0x1F; + } + if ((c & 0xF0) == 0xE0) { + return c & 0x0F; + } + if ((c & 0xF8) == 0xF0) { + return c & 0x07; + } + CATCH_INTERNAL_ERROR( + "Invalid multibyte utf-8 start byte encountered"); } - if ((c & 0xF8) == 0xF0) { - return 4; + + void hexEscapeChar(std::ostream& os, unsigned char c) { + std::ios_base::fmtflags f(os.flags()); + os << "\\x" << std::uppercase << std::hex << std::setfill('0') + << std::setw(2) << static_cast<int>(c); + os.flags(f); } - CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered"); - } - uint32_t headerValue(unsigned char c) { - if ((c & 0xE0) == 0xC0) { - return c & 0x1F; + bool shouldNewline(XmlFormatting fmt) { + return !!(static_cast<std::underlying_type<XmlFormatting>::type>( + fmt & XmlFormatting::Newline)); } - if ((c & 0xF0) == 0xE0) { - return c & 0x0F; + + bool shouldIndent(XmlFormatting fmt) { + return !!(static_cast<std::underlying_type<XmlFormatting>::type>( + fmt & XmlFormatting::Indent)); } - if ((c & 0xF8) == 0xF0) { - return c & 0x07; - } - CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered"); - } - void hexEscapeChar(std::ostream& os, unsigned char c) { - std::ios_base::fmtflags f(os.flags()); - os << "\\x" - << std::uppercase << std::hex << std::setfill('0') << std::setw(2) - << static_cast<int>(c); - os.flags(f); - } + } // anonymous namespace - bool shouldNewline(XmlFormatting fmt) { - return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Newline)); - } - - bool shouldIndent(XmlFormatting fmt) { - return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Indent)); - } - -} // anonymous namespace - - XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs) { + XmlFormatting operator|(XmlFormatting lhs, XmlFormatting rhs) { return static_cast<XmlFormatting>( static_cast<std::underlying_type<XmlFormatting>::type>(lhs) | - static_cast<std::underlying_type<XmlFormatting>::type>(rhs) - ); + static_cast<std::underlying_type<XmlFormatting>::type>(rhs)); } - XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs) { + XmlFormatting operator&(XmlFormatting lhs, XmlFormatting rhs) { return static_cast<XmlFormatting>( static_cast<std::underlying_type<XmlFormatting>::type>(lhs) & - static_cast<std::underlying_type<XmlFormatting>::type>(rhs) - ); + static_cast<std::underlying_type<XmlFormatting>::type>(rhs)); } - XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat ) - : m_str( str ), - m_forWhat( forWhat ) - {} + XmlEncode::XmlEncode(std::string const& str, ForWhat forWhat) : + m_str(str), m_forWhat(forWhat) {} - void XmlEncode::encodeTo( std::ostream& os ) const { - // Apostrophe escaping not necessary if we always use " to write attributes - // (see: http://www.w3.org/TR/xml/#syntax) + void XmlEncode::encodeTo(std::ostream& os) const { + // Apostrophe escaping not necessary if we always use " to write + // attributes (see: http://www.w3.org/TR/xml/#syntax) - for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) { + for (std::size_t idx = 0; idx < m_str.size(); ++idx) { unsigned char c = m_str[idx]; switch (c) { - case '<': os << "<"; break; - case '&': os << "&"; break; - - case '>': - // See: http://www.w3.org/TR/xml/#syntax - if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']') - os << ">"; - else - os << c; - break; - - case '\"': - if (m_forWhat == ForAttributes) - os << """; - else - os << c; - break; - - default: - // Check for control characters and invalid utf-8 - - // Escape control characters in standard ascii - // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0 - if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) { - hexEscapeChar(os, c); + case '<': + os << "<"; break; - } - - // Plain ASCII: Write it to stream - if (c < 0x7F) { - os << c; + case '&': + os << "&"; break; - } - // UTF-8 territory - // Check if the encoding is valid and if it is not, hex escape bytes. - // Important: We do not check the exact decoded values for validity, only the encoding format - // First check that this bytes is a valid lead byte: - // This means that it is not encoded as 1111 1XXX - // Or as 10XX XXXX - if (c < 0xC0 || - c >= 0xF8) { - hexEscapeChar(os, c); + case '>': + // See: http://www.w3.org/TR/xml/#syntax + if (idx > 2 && m_str[idx - 1] == ']' && + m_str[idx - 2] == ']') + os << ">"; + else + os << c; break; - } - auto encBytes = trailingBytes(c); - // Are there enough bytes left to avoid accessing out-of-bounds memory? - if (idx + encBytes - 1 >= m_str.size()) { - hexEscapeChar(os, c); + case '\"': + if (m_forWhat == ForAttributes) + os << """; + else + os << c; break; - } - // The header is valid, check data - // The next encBytes bytes must together be a valid utf-8 - // This means: bitpattern 10XX XXXX and the extracted value is sane (ish) - bool valid = true; - uint32_t value = headerValue(c); - for (std::size_t n = 1; n < encBytes; ++n) { - unsigned char nc = m_str[idx + n]; - valid &= ((nc & 0xC0) == 0x80); - value = (value << 6) | (nc & 0x3F); - } - if ( - // Wrong bit pattern of following bytes - (!valid) || - // Overlong encodings - (value < 0x80) || - (0x80 <= value && value < 0x800 && encBytes > 2) || - (0x800 < value && value < 0x10000 && encBytes > 3) || - // Encoded value out of range - (value >= 0x110000) - ) { - hexEscapeChar(os, c); + default: + // Check for control characters and invalid utf-8 + + // Escape control characters in standard ascii + // see + // http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0 + if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) { + hexEscapeChar(os, c); + break; + } + + // Plain ASCII: Write it to stream + if (c < 0x7F) { + os << c; + break; + } + + // UTF-8 territory + // Check if the encoding is valid and if it is not, hex + // escape bytes. Important: We do not check the exact + // decoded values for validity, only the encoding format + // First check that this bytes is a valid lead byte: + // This means that it is not encoded as 1111 1XXX + // Or as 10XX XXXX + if (c < 0xC0 || c >= 0xF8) { + hexEscapeChar(os, c); + break; + } + + auto encBytes = trailingBytes(c); + // Are there enough bytes left to avoid accessing + // out-of-bounds memory? + if (idx + encBytes - 1 >= m_str.size()) { + hexEscapeChar(os, c); + break; + } + // The header is valid, check data + // The next encBytes bytes must together be a valid utf-8 + // This means: bitpattern 10XX XXXX and the extracted value + // is sane (ish) + bool valid = true; + uint32_t value = headerValue(c); + for (std::size_t n = 1; n < encBytes; ++n) { + unsigned char nc = m_str[idx + n]; + valid &= ((nc & 0xC0) == 0x80); + value = (value << 6) | (nc & 0x3F); + } + + if ( + // Wrong bit pattern of following bytes + (!valid) || + // Overlong encodings + (value < 0x80) || + (0x80 <= value && value < 0x800 && encBytes > 2) || + (0x800 < value && value < 0x10000 && encBytes > 3) || + // Encoded value out of range + (value >= 0x110000)) + { + hexEscapeChar(os, c); + break; + } + + // If we got here, this is in fact a valid(ish) utf-8 + // sequence + for (std::size_t n = 0; n < encBytes; ++n) { + os << m_str[idx + n]; + } + idx += encBytes - 1; break; - } - - // If we got here, this is in fact a valid(ish) utf-8 sequence - for (std::size_t n = 0; n < encBytes; ++n) { - os << m_str[idx + n]; - } - idx += encBytes - 1; - break; } } } - std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) { - xmlEncode.encodeTo( os ); + std::ostream& operator<<(std::ostream& os, XmlEncode const& xmlEncode) { + xmlEncode.encodeTo(os); return os; } - XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting fmt ) - : m_writer( writer ), - m_fmt(fmt) - {} + XmlWriter::ScopedElement::ScopedElement(XmlWriter* writer, + XmlFormatting fmt) : + m_writer(writer), m_fmt(fmt) {} - XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept - : m_writer( other.m_writer ), - m_fmt(other.m_fmt) - { + XmlWriter::ScopedElement::ScopedElement(ScopedElement&& other) noexcept : + m_writer(other.m_writer), m_fmt(other.m_fmt) { other.m_writer = nullptr; other.m_fmt = XmlFormatting::None; } - XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept { - if ( m_writer ) { + XmlWriter::ScopedElement& + XmlWriter::ScopedElement::operator=(ScopedElement&& other) noexcept { + if (m_writer) { m_writer->endElement(); } m_writer = other.m_writer; @@ -15625,15 +17248,14 @@ } } - XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, XmlFormatting fmt ) { - m_writer->writeText( text, fmt ); + XmlWriter::ScopedElement& + XmlWriter::ScopedElement::writeText(std::string const& text, + XmlFormatting fmt) { + m_writer->writeText(text, fmt); return *this; } - XmlWriter::XmlWriter( std::ostream& os ) : m_os( os ) - { - writeDeclaration(); - } + XmlWriter::XmlWriter(std::ostream& os) : m_os(os) { writeDeclaration(); } XmlWriter::~XmlWriter() { while (!m_tags.empty()) { @@ -15642,7 +17264,8 @@ newlineIfNecessary(); } - XmlWriter& XmlWriter::startElement( std::string const& name, XmlFormatting fmt ) { + XmlWriter& XmlWriter::startElement(std::string const& name, + XmlFormatting fmt) { ensureTagClosed(); newlineIfNecessary(); if (shouldIndent(fmt)) { @@ -15650,22 +17273,23 @@ m_indent += " "; } m_os << '<' << name; - m_tags.push_back( name ); + m_tags.push_back(name); m_tagIsOpen = true; applyFormatting(fmt); return *this; } - XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name, XmlFormatting fmt ) { - ScopedElement scoped( this, fmt ); - startElement( name, fmt ); + XmlWriter::ScopedElement XmlWriter::scopedElement(std::string const& name, + XmlFormatting fmt) { + ScopedElement scoped(this, fmt); + startElement(name, fmt); return scoped; } XmlWriter& XmlWriter::endElement(XmlFormatting fmt) { m_indent = m_indent.substr(0, m_indent.size() - 2); - if( m_tagIsOpen ) { + if (m_tagIsOpen) { m_os << "/>"; m_tagIsOpen = false; } else { @@ -15681,31 +17305,36 @@ return *this; } - XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) { - if( !name.empty() && !attribute.empty() ) - m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"'; + XmlWriter& XmlWriter::writeAttribute(std::string const& name, + std::string const& attribute) { + if (!name.empty() && !attribute.empty()) + m_os << ' ' << name << "=\"" + << XmlEncode(attribute, XmlEncode::ForAttributes) << '"'; return *this; } - XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) { - m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"'; + XmlWriter& XmlWriter::writeAttribute(std::string const& name, + bool attribute) { + m_os << ' ' << name << "=\"" << (attribute ? "true" : "false") << '"'; return *this; } - XmlWriter& XmlWriter::writeText( std::string const& text, XmlFormatting fmt) { - if( !text.empty() ){ + XmlWriter& XmlWriter::writeText(std::string const& text, + XmlFormatting fmt) { + if (!text.empty()) { bool tagWasOpen = m_tagIsOpen; ensureTagClosed(); if (tagWasOpen && shouldIndent(fmt)) { m_os << m_indent; } - m_os << XmlEncode( text ); + m_os << XmlEncode(text); applyFormatting(fmt); } return *this; } - XmlWriter& XmlWriter::writeComment( std::string const& text, XmlFormatting fmt) { + XmlWriter& XmlWriter::writeComment(std::string const& text, + XmlFormatting fmt) { ensureTagClosed(); if (shouldIndent(fmt)) { m_os << m_indent; @@ -15715,7 +17344,7 @@ return *this; } - void XmlWriter::writeStylesheetRef( std::string const& url ) { + void XmlWriter::writeStylesheetRef(std::string const& url) { m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n"; } @@ -15726,7 +17355,7 @@ } void XmlWriter::ensureTagClosed() { - if( m_tagIsOpen ) { + if (m_tagIsOpen) { m_os << '>' << std::flush; newlineIfNecessary(); m_tagIsOpen = false; @@ -15742,12 +17371,12 @@ } void XmlWriter::newlineIfNecessary() { - if( m_needsNewline ) { + if (m_needsNewline) { m_os << std::endl; m_needsNewline = false; } } -} +} // namespace Catch // end catch_xmlwriter.cpp // start catch_reporter_bases.cpp @@ -15762,9 +17391,10 @@ result.getExpandedExpression(); } - // Because formatting using c++ streams is stateful, drop down to C is required - // Alternatively we could use stringstream, but its performance is... not good. - std::string getFormattedDuration( double duration ) { + // Because formatting using c++ streams is stateful, drop down to C is + // required Alternatively we could use stringstream, but its performance + // is... not good. + std::string getFormattedDuration(double duration) { // Max exponent + 1 is required to represent the whole part // + 1 for decimal point // + 3 for the 3 decimal places @@ -15782,22 +17412,21 @@ return std::string(buffer); } - bool shouldShowDuration( IConfig const& config, double duration ) { - if ( config.showDurations() == ShowDurations::Always ) { + bool shouldShowDuration(IConfig const& config, double duration) { + if (config.showDurations() == ShowDurations::Always) { return true; } - if ( config.showDurations() == ShowDurations::Never ) { + if (config.showDurations() == ShowDurations::Never) { return false; } const double min = config.minDuration(); return min >= 0 && duration >= min; } - std::string serializeFilters( std::vector<std::string> const& container ) { + std::string serializeFilters(std::vector<std::string> const& container) { ReusableStringStream oss; bool first = true; - for (auto&& filter : container) - { + for (auto&& filter : container) { if (!first) oss << ' '; else @@ -15808,16 +17437,17 @@ return oss.str(); } - TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config) - :StreamingReporterBase(_config) {} + TestEventListenerBase::TestEventListenerBase( + ReporterConfig const& _config) : + StreamingReporterBase(_config) {} std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() { - return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High }; + return {Verbosity::Quiet, Verbosity::Normal, Verbosity::High}; } - void TestEventListenerBase::assertionStarting(AssertionInfo const &) {} + void TestEventListenerBase::assertionStarting(AssertionInfo const&) {} - bool TestEventListenerBase::assertionEnded(AssertionStats const &) { + bool TestEventListenerBase::assertionEnded(AssertionStats const&) { return false; } @@ -15838,268 +17468,280 @@ // Colour::LightGrey Catch::Colour::Code dimColour() { return Catch::Colour::FileName; } - std::string bothOrAll( std::size_t count ) { - return count == 1 ? std::string() : - count == 2 ? "both " : "all " ; + std::string bothOrAll(std::size_t count) { + return count == 1 ? std::string() : count == 2 ? "both " : "all "; } -} // anon namespace +} // namespace namespace Catch { -namespace { -// Colour, message variants: -// - white: No tests ran. -// - red: Failed [both/all] N test cases, failed [both/all] M assertions. -// - white: Passed [both/all] N test cases (no assertions). -// - red: Failed N tests cases, failed M assertions. -// - green: Passed [both/all] N tests cases with M assertions. -void printTotals(std::ostream& out, const Totals& totals) { - if (totals.testCases.total() == 0) { - out << "No tests ran."; - } else if (totals.testCases.failed == totals.testCases.total()) { - Colour colour(Colour::ResultError); - const std::string qualify_assertions_failed = - totals.assertions.failed == totals.assertions.total() ? - bothOrAll(totals.assertions.failed) : std::string(); - out << - "Failed " << bothOrAll(totals.testCases.failed) - << pluralise(totals.testCases.failed, "test case") << ", " - "failed " << qualify_assertions_failed << - pluralise(totals.assertions.failed, "assertion") << '.'; - } else if (totals.assertions.total() == 0) { - out << - "Passed " << bothOrAll(totals.testCases.total()) - << pluralise(totals.testCases.total(), "test case") - << " (no assertions)."; - } else if (totals.assertions.failed) { - Colour colour(Colour::ResultError); - out << - "Failed " << pluralise(totals.testCases.failed, "test case") << ", " - "failed " << pluralise(totals.assertions.failed, "assertion") << '.'; - } else { - Colour colour(Colour::ResultSuccess); - out << - "Passed " << bothOrAll(totals.testCases.passed) - << pluralise(totals.testCases.passed, "test case") << - " with " << pluralise(totals.assertions.passed, "assertion") << '.'; - } -} - -// Implementation of CompactReporter formatting -class AssertionPrinter { -public: - AssertionPrinter& operator= (AssertionPrinter const&) = delete; - AssertionPrinter(AssertionPrinter const&) = delete; - AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages) - : stream(_stream) - , result(_stats.assertionResult) - , messages(_stats.infoMessages) - , itMessage(_stats.infoMessages.begin()) - , printInfoMessages(_printInfoMessages) {} - - void print() { - printSourceInfo(); - - itMessage = messages.begin(); - - switch (result.getResultType()) { - case ResultWas::Ok: - printResultType(Colour::ResultSuccess, passedString()); - printOriginalExpression(); - printReconstructedExpression(); - if (!result.hasExpression()) - printRemainingMessages(Colour::None); - else - printRemainingMessages(); - break; - case ResultWas::ExpressionFailed: - if (result.isOk()) - printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok")); - else - printResultType(Colour::Error, failedString()); - printOriginalExpression(); - printReconstructedExpression(); - printRemainingMessages(); - break; - case ResultWas::ThrewException: - printResultType(Colour::Error, failedString()); - printIssue("unexpected exception with message:"); - printMessage(); - printExpressionWas(); - printRemainingMessages(); - break; - case ResultWas::FatalErrorCondition: - printResultType(Colour::Error, failedString()); - printIssue("fatal error condition with message:"); - printMessage(); - printExpressionWas(); - printRemainingMessages(); - break; - case ResultWas::DidntThrowException: - printResultType(Colour::Error, failedString()); - printIssue("expected exception, got none"); - printExpressionWas(); - printRemainingMessages(); - break; - case ResultWas::Info: - printResultType(Colour::None, "info"); - printMessage(); - printRemainingMessages(); - break; - case ResultWas::Warning: - printResultType(Colour::None, "warning"); - printMessage(); - printRemainingMessages(); - break; - case ResultWas::ExplicitFailure: - printResultType(Colour::Error, failedString()); - printIssue("explicitly"); - printRemainingMessages(Colour::None); - break; - // These cases are here to prevent compiler warnings - case ResultWas::Unknown: - case ResultWas::FailureBit: - case ResultWas::Exception: - printResultType(Colour::Error, "** internal error **"); - break; - } - } - -private: - void printSourceInfo() const { - Colour colourGuard(Colour::FileName); - stream << result.getSourceInfo() << ':'; - } - - void printResultType(Colour::Code colour, std::string const& passOrFail) const { - if (!passOrFail.empty()) { - { - Colour colourGuard(colour); - stream << ' ' << passOrFail; + namespace { + // Colour, message variants: + // - white: No tests ran. + // - red: Failed [both/all] N test cases, failed [both/all] M + // assertions. + // - white: Passed [both/all] N test cases (no assertions). + // - red: Failed N tests cases, failed M assertions. + // - green: Passed [both/all] N tests cases with M assertions. + void printTotals(std::ostream& out, const Totals& totals) { + if (totals.testCases.total() == 0) { + out << "No tests ran."; + } else if (totals.testCases.failed == totals.testCases.total()) { + Colour colour(Colour::ResultError); + const std::string qualify_assertions_failed = + totals.assertions.failed == totals.assertions.total() + ? bothOrAll(totals.assertions.failed) + : std::string(); + out << "Failed " << bothOrAll(totals.testCases.failed) + << pluralise(totals.testCases.failed, "test case") + << ", " + "failed " + << qualify_assertions_failed + << pluralise(totals.assertions.failed, "assertion") << '.'; + } else if (totals.assertions.total() == 0) { + out << "Passed " << bothOrAll(totals.testCases.total()) + << pluralise(totals.testCases.total(), "test case") + << " (no assertions)."; + } else if (totals.assertions.failed) { + Colour colour(Colour::ResultError); + out << "Failed " + << pluralise(totals.testCases.failed, "test case") + << ", " + "failed " + << pluralise(totals.assertions.failed, "assertion") << '.'; + } else { + Colour colour(Colour::ResultSuccess); + out << "Passed " << bothOrAll(totals.testCases.passed) + << pluralise(totals.testCases.passed, "test case") + << " with " + << pluralise(totals.assertions.passed, "assertion") << '.'; } - stream << ':'; - } - } - - void printIssue(std::string const& issue) const { - stream << ' ' << issue; - } - - void printExpressionWas() { - if (result.hasExpression()) { - stream << ';'; - { - Colour colour(dimColour()); - stream << " expression was:"; - } - printOriginalExpression(); - } - } - - void printOriginalExpression() const { - if (result.hasExpression()) { - stream << ' ' << result.getExpression(); - } - } - - void printReconstructedExpression() const { - if (result.hasExpandedExpression()) { - { - Colour colour(dimColour()); - stream << " for: "; - } - stream << result.getExpandedExpression(); - } - } - - void printMessage() { - if (itMessage != messages.end()) { - stream << " '" << itMessage->message << '\''; - ++itMessage; - } - } - - void printRemainingMessages(Colour::Code colour = dimColour()) { - if (itMessage == messages.end()) - return; - - const auto itEnd = messages.cend(); - const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd)); - - { - Colour colourGuard(colour); - stream << " with " << pluralise(N, "message") << ':'; } - while (itMessage != itEnd) { - // If this assertion is a warning ignore any INFO messages - if (printInfoMessages || itMessage->type != ResultWas::Info) { - printMessage(); - if (itMessage != itEnd) { - Colour colourGuard(dimColour()); - stream << " and"; + // Implementation of CompactReporter formatting + class AssertionPrinter { + public: + AssertionPrinter& operator=(AssertionPrinter const&) = delete; + AssertionPrinter(AssertionPrinter const&) = delete; + AssertionPrinter(std::ostream& _stream, + AssertionStats const& _stats, + bool _printInfoMessages) : + stream(_stream), + result(_stats.assertionResult), + messages(_stats.infoMessages), + itMessage(_stats.infoMessages.begin()), + printInfoMessages(_printInfoMessages) {} + + void print() { + printSourceInfo(); + + itMessage = messages.begin(); + + switch (result.getResultType()) { + case ResultWas::Ok: + printResultType(Colour::ResultSuccess, passedString()); + printOriginalExpression(); + printReconstructedExpression(); + if (!result.hasExpression()) + printRemainingMessages(Colour::None); + else + printRemainingMessages(); + break; + case ResultWas::ExpressionFailed: + if (result.isOk()) + printResultType(Colour::ResultSuccess, + failedString() + + std::string(" - but was ok")); + else + printResultType(Colour::Error, failedString()); + printOriginalExpression(); + printReconstructedExpression(); + printRemainingMessages(); + break; + case ResultWas::ThrewException: + printResultType(Colour::Error, failedString()); + printIssue("unexpected exception with message:"); + printMessage(); + printExpressionWas(); + printRemainingMessages(); + break; + case ResultWas::FatalErrorCondition: + printResultType(Colour::Error, failedString()); + printIssue("fatal error condition with message:"); + printMessage(); + printExpressionWas(); + printRemainingMessages(); + break; + case ResultWas::DidntThrowException: + printResultType(Colour::Error, failedString()); + printIssue("expected exception, got none"); + printExpressionWas(); + printRemainingMessages(); + break; + case ResultWas::Info: + printResultType(Colour::None, "info"); + printMessage(); + printRemainingMessages(); + break; + case ResultWas::Warning: + printResultType(Colour::None, "warning"); + printMessage(); + printRemainingMessages(); + break; + case ResultWas::ExplicitFailure: + printResultType(Colour::Error, failedString()); + printIssue("explicitly"); + printRemainingMessages(Colour::None); + break; + // These cases are here to prevent compiler warnings + case ResultWas::Unknown: + case ResultWas::FailureBit: + case ResultWas::Exception: + printResultType(Colour::Error, "** internal error **"); + break; } - continue; } - ++itMessage; + + private: + void printSourceInfo() const { + Colour colourGuard(Colour::FileName); + stream << result.getSourceInfo() << ':'; + } + + void printResultType(Colour::Code colour, + std::string const& passOrFail) const { + if (!passOrFail.empty()) { + { + Colour colourGuard(colour); + stream << ' ' << passOrFail; + } + stream << ':'; + } + } + + void printIssue(std::string const& issue) const { + stream << ' ' << issue; + } + + void printExpressionWas() { + if (result.hasExpression()) { + stream << ';'; + { + Colour colour(dimColour()); + stream << " expression was:"; + } + printOriginalExpression(); + } + } + + void printOriginalExpression() const { + if (result.hasExpression()) { + stream << ' ' << result.getExpression(); + } + } + + void printReconstructedExpression() const { + if (result.hasExpandedExpression()) { + { + Colour colour(dimColour()); + stream << " for: "; + } + stream << result.getExpandedExpression(); + } + } + + void printMessage() { + if (itMessage != messages.end()) { + stream << " '" << itMessage->message << '\''; + ++itMessage; + } + } + + void printRemainingMessages(Colour::Code colour = dimColour()) { + if (itMessage == messages.end()) + return; + + const auto itEnd = messages.cend(); + const auto N = + static_cast<std::size_t>(std::distance(itMessage, itEnd)); + + { + Colour colourGuard(colour); + stream << " with " << pluralise(N, "message") << ':'; + } + + while (itMessage != itEnd) { + // If this assertion is a warning ignore any INFO messages + if (printInfoMessages || itMessage->type != ResultWas::Info) + { + printMessage(); + if (itMessage != itEnd) { + Colour colourGuard(dimColour()); + stream << " and"; + } + continue; + } + ++itMessage; + } + } + + private: + std::ostream& stream; + AssertionResult const& result; + std::vector<MessageInfo> messages; + std::vector<MessageInfo>::const_iterator itMessage; + bool printInfoMessages; + }; + + } // namespace + + std::string CompactReporter::getDescription() { + return "Reports test results on a single line, suitable for IDEs"; + } + + void CompactReporter::noMatchingTestCases(std::string const& spec) { + stream << "No test cases matched '" << spec << '\'' << std::endl; + } + + void CompactReporter::assertionStarting(AssertionInfo const&) {} + + bool + CompactReporter::assertionEnded(AssertionStats const& _assertionStats) { + AssertionResult const& result = _assertionStats.assertionResult; + + bool printInfoMessages = true; + + // Drop out if result was successful and we're not printing those + if (!m_config->includeSuccessfulResults() && result.isOk()) { + if (result.getResultType() != ResultWas::Warning) + return false; + printInfoMessages = false; + } + + AssertionPrinter printer(stream, _assertionStats, printInfoMessages); + printer.print(); + + stream << std::endl; + return true; + } + + void CompactReporter::sectionEnded(SectionStats const& _sectionStats) { + double dur = _sectionStats.durationInSeconds; + if (shouldShowDuration(*m_config, dur)) { + stream << getFormattedDuration(dur) + << " s: " << _sectionStats.sectionInfo.name << std::endl; } } -private: - std::ostream& stream; - AssertionResult const& result; - std::vector<MessageInfo> messages; - std::vector<MessageInfo>::const_iterator itMessage; - bool printInfoMessages; -}; + void CompactReporter::testRunEnded(TestRunStats const& _testRunStats) { + printTotals(stream, _testRunStats.totals); + stream << '\n' << std::endl; + StreamingReporterBase::testRunEnded(_testRunStats); + } -} // anon namespace + CompactReporter::~CompactReporter() {} - std::string CompactReporter::getDescription() { - return "Reports test results on a single line, suitable for IDEs"; - } - - void CompactReporter::noMatchingTestCases( std::string const& spec ) { - stream << "No test cases matched '" << spec << '\'' << std::endl; - } - - void CompactReporter::assertionStarting( AssertionInfo const& ) {} - - bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) { - AssertionResult const& result = _assertionStats.assertionResult; - - bool printInfoMessages = true; - - // Drop out if result was successful and we're not printing those - if( !m_config->includeSuccessfulResults() && result.isOk() ) { - if( result.getResultType() != ResultWas::Warning ) - return false; - printInfoMessages = false; - } - - AssertionPrinter printer( stream, _assertionStats, printInfoMessages ); - printer.print(); - - stream << std::endl; - return true; - } - - void CompactReporter::sectionEnded(SectionStats const& _sectionStats) { - double dur = _sectionStats.durationInSeconds; - if ( shouldShowDuration( *m_config, dur ) ) { - stream << getFormattedDuration( dur ) << " s: " << _sectionStats.sectionInfo.name << std::endl; - } - } - - void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) { - printTotals( stream, _testRunStats.totals ); - stream << '\n' << std::endl; - StreamingReporterBase::testRunEnded( _testRunStats ); - } - - CompactReporter::~CompactReporter() {} - - CATCH_REGISTER_REPORTER( "compact", CompactReporter ) + CATCH_REGISTER_REPORTER("compact", CompactReporter) } // end namespace Catch // end catch_reporter_compact.cpp @@ -16110,672 +17752,717 @@ #if defined(_MSC_VER) #pragma warning(push) -#pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch - // Note that 4062 (not all labels are handled and default is missing) is enabled +#pragma warning( \ + disable : 4061) // Not all labels are EXPLICITLY handled in switch + // Note that 4062 (not all labels are handled and default is missing) is + // enabled #endif #if defined(__clang__) -# pragma clang diagnostic push +#pragma clang diagnostic push // For simplicity, benchmarking-only helpers are always enabled -# pragma clang diagnostic ignored "-Wunused-function" +#pragma clang diagnostic ignored "-Wunused-function" #endif namespace Catch { -namespace { + namespace { -// Formatter impl for ConsoleReporter -class ConsoleAssertionPrinter { -public: - ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete; - ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete; - ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages) - : stream(_stream), - stats(_stats), - result(_stats.assertionResult), - colour(Colour::None), - message(result.getMessage()), - messages(_stats.infoMessages), - printInfoMessages(_printInfoMessages) { - switch (result.getResultType()) { - case ResultWas::Ok: - colour = Colour::Success; - passOrFail = "PASSED"; - //if( result.hasMessage() ) - if (_stats.infoMessages.size() == 1) - messageLabel = "with message"; - if (_stats.infoMessages.size() > 1) - messageLabel = "with messages"; - break; - case ResultWas::ExpressionFailed: - if (result.isOk()) { - colour = Colour::Success; - passOrFail = "FAILED - but was ok"; - } else { - colour = Colour::Error; - passOrFail = "FAILED"; + // Formatter impl for ConsoleReporter + class ConsoleAssertionPrinter { + public: + ConsoleAssertionPrinter& + operator=(ConsoleAssertionPrinter const&) = delete; + ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete; + ConsoleAssertionPrinter(std::ostream& _stream, + AssertionStats const& _stats, + bool _printInfoMessages) : + stream(_stream), + stats(_stats), + result(_stats.assertionResult), + colour(Colour::None), + message(result.getMessage()), + messages(_stats.infoMessages), + printInfoMessages(_printInfoMessages) { + switch (result.getResultType()) { + case ResultWas::Ok: + colour = Colour::Success; + passOrFail = "PASSED"; + // if( result.hasMessage() ) + if (_stats.infoMessages.size() == 1) + messageLabel = "with message"; + if (_stats.infoMessages.size() > 1) + messageLabel = "with messages"; + break; + case ResultWas::ExpressionFailed: + if (result.isOk()) { + colour = Colour::Success; + passOrFail = "FAILED - but was ok"; + } else { + colour = Colour::Error; + passOrFail = "FAILED"; + } + if (_stats.infoMessages.size() == 1) + messageLabel = "with message"; + if (_stats.infoMessages.size() > 1) + messageLabel = "with messages"; + break; + case ResultWas::ThrewException: + colour = Colour::Error; + passOrFail = "FAILED"; + messageLabel = "due to unexpected exception with "; + if (_stats.infoMessages.size() == 1) + messageLabel += "message"; + if (_stats.infoMessages.size() > 1) + messageLabel += "messages"; + break; + case ResultWas::FatalErrorCondition: + colour = Colour::Error; + passOrFail = "FAILED"; + messageLabel = "due to a fatal error condition"; + break; + case ResultWas::DidntThrowException: + colour = Colour::Error; + passOrFail = "FAILED"; + messageLabel = "because no exception was thrown where " + "one was expected"; + break; + case ResultWas::Info: + messageLabel = "info"; + break; + case ResultWas::Warning: + messageLabel = "warning"; + break; + case ResultWas::ExplicitFailure: + passOrFail = "FAILED"; + colour = Colour::Error; + if (_stats.infoMessages.size() == 1) + messageLabel = "explicitly with message"; + if (_stats.infoMessages.size() > 1) + messageLabel = "explicitly with messages"; + break; + // These cases are here to prevent compiler warnings + case ResultWas::Unknown: + case ResultWas::FailureBit: + case ResultWas::Exception: + passOrFail = "** internal error **"; + colour = Colour::Error; + break; + } } - if (_stats.infoMessages.size() == 1) - messageLabel = "with message"; - if (_stats.infoMessages.size() > 1) - messageLabel = "with messages"; - break; - case ResultWas::ThrewException: - colour = Colour::Error; - passOrFail = "FAILED"; - messageLabel = "due to unexpected exception with "; - if (_stats.infoMessages.size() == 1) - messageLabel += "message"; - if (_stats.infoMessages.size() > 1) - messageLabel += "messages"; - break; - case ResultWas::FatalErrorCondition: - colour = Colour::Error; - passOrFail = "FAILED"; - messageLabel = "due to a fatal error condition"; - break; - case ResultWas::DidntThrowException: - colour = Colour::Error; - passOrFail = "FAILED"; - messageLabel = "because no exception was thrown where one was expected"; - break; - case ResultWas::Info: - messageLabel = "info"; - break; - case ResultWas::Warning: - messageLabel = "warning"; - break; - case ResultWas::ExplicitFailure: - passOrFail = "FAILED"; - colour = Colour::Error; - if (_stats.infoMessages.size() == 1) - messageLabel = "explicitly with message"; - if (_stats.infoMessages.size() > 1) - messageLabel = "explicitly with messages"; - break; - // These cases are here to prevent compiler warnings - case ResultWas::Unknown: - case ResultWas::FailureBit: - case ResultWas::Exception: - passOrFail = "** internal error **"; - colour = Colour::Error; - break; + + void print() const { + printSourceInfo(); + if (stats.totals.assertions.total() > 0) { + printResultType(); + printOriginalExpression(); + printReconstructedExpression(); + } else { + stream << '\n'; + } + printMessage(); + } + + private: + void printResultType() const { + if (!passOrFail.empty()) { + Colour colourGuard(colour); + stream << passOrFail << ":\n"; + } + } + void printOriginalExpression() const { + if (result.hasExpression()) { + Colour colourGuard(Colour::OriginalExpression); + stream << " "; + stream << result.getExpressionInMacro(); + stream << '\n'; + } + } + void printReconstructedExpression() const { + if (result.hasExpandedExpression()) { + stream << "with expansion:\n"; + Colour colourGuard(Colour::ReconstructedExpression); + stream << Column(result.getExpandedExpression()).indent(2) + << '\n'; + } + } + void printMessage() const { + if (!messageLabel.empty()) + stream << messageLabel << ':' << '\n'; + for (auto const& msg : messages) { + // If this assertion is a warning ignore any INFO messages + if (printInfoMessages || msg.type != ResultWas::Info) + stream << Column(msg.message).indent(2) << '\n'; + } + } + void printSourceInfo() const { + Colour colourGuard(Colour::FileName); + stream << result.getSourceInfo() << ": "; + } + + std::ostream& stream; + AssertionStats const& stats; + AssertionResult const& result; + Colour::Code colour; + std::string passOrFail; + std::string messageLabel; + std::string message; + std::vector<MessageInfo> messages; + bool printInfoMessages; + }; + + std::size_t makeRatio(std::size_t number, std::size_t total) { + std::size_t ratio = + total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0; + return (ratio == 0 && number > 0) ? 1 : ratio; } - } - void print() const { - printSourceInfo(); - if (stats.totals.assertions.total() > 0) { - printResultType(); - printOriginalExpression(); - printReconstructedExpression(); - } else { - stream << '\n'; - } - printMessage(); - } - -private: - void printResultType() const { - if (!passOrFail.empty()) { - Colour colourGuard(colour); - stream << passOrFail << ":\n"; - } - } - void printOriginalExpression() const { - if (result.hasExpression()) { - Colour colourGuard(Colour::OriginalExpression); - stream << " "; - stream << result.getExpressionInMacro(); - stream << '\n'; - } - } - void printReconstructedExpression() const { - if (result.hasExpandedExpression()) { - stream << "with expansion:\n"; - Colour colourGuard(Colour::ReconstructedExpression); - stream << Column(result.getExpandedExpression()).indent(2) << '\n'; - } - } - void printMessage() const { - if (!messageLabel.empty()) - stream << messageLabel << ':' << '\n'; - for (auto const& msg : messages) { - // If this assertion is a warning ignore any INFO messages - if (printInfoMessages || msg.type != ResultWas::Info) - stream << Column(msg.message).indent(2) << '\n'; - } - } - void printSourceInfo() const { - Colour colourGuard(Colour::FileName); - stream << result.getSourceInfo() << ": "; - } - - std::ostream& stream; - AssertionStats const& stats; - AssertionResult const& result; - Colour::Code colour; - std::string passOrFail; - std::string messageLabel; - std::string message; - std::vector<MessageInfo> messages; - bool printInfoMessages; -}; - -std::size_t makeRatio(std::size_t number, std::size_t total) { - std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0; - return (ratio == 0 && number > 0) ? 1 : ratio; -} - -std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) { - if (i > j && i > k) - return i; - else if (j > k) - return j; - else - return k; -} - -struct ColumnInfo { - enum Justification { Left, Right }; - std::string name; - int width; - Justification justification; -}; -struct ColumnBreak {}; -struct RowBreak {}; - -class Duration { - enum class Unit { - Auto, - Nanoseconds, - Microseconds, - Milliseconds, - Seconds, - Minutes - }; - static const uint64_t s_nanosecondsInAMicrosecond = 1000; - static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond; - static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond; - static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond; - - double m_inNanoseconds; - Unit m_units; - -public: - explicit Duration(double inNanoseconds, Unit units = Unit::Auto) - : m_inNanoseconds(inNanoseconds), - m_units(units) { - if (m_units == Unit::Auto) { - if (m_inNanoseconds < s_nanosecondsInAMicrosecond) - m_units = Unit::Nanoseconds; - else if (m_inNanoseconds < s_nanosecondsInAMillisecond) - m_units = Unit::Microseconds; - else if (m_inNanoseconds < s_nanosecondsInASecond) - m_units = Unit::Milliseconds; - else if (m_inNanoseconds < s_nanosecondsInAMinute) - m_units = Unit::Seconds; + std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) { + if (i > j && i > k) + return i; + else if (j > k) + return j; else - m_units = Unit::Minutes; + return k; } - } + struct ColumnInfo { + enum Justification { Left, Right }; + std::string name; + int width; + Justification justification; + }; + struct ColumnBreak {}; + struct RowBreak {}; - auto value() const -> double { - switch (m_units) { - case Unit::Microseconds: - return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond); - case Unit::Milliseconds: - return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond); - case Unit::Seconds: - return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond); - case Unit::Minutes: - return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute); - default: - return m_inNanoseconds; - } - } - auto unitsAsString() const -> std::string { - switch (m_units) { - case Unit::Nanoseconds: - return "ns"; - case Unit::Microseconds: - return "us"; - case Unit::Milliseconds: - return "ms"; - case Unit::Seconds: - return "s"; - case Unit::Minutes: - return "m"; - default: - return "** internal error **"; - } - - } - friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& { - return os << duration.value() << ' ' << duration.unitsAsString(); - } -}; -} // end anon namespace - -class TablePrinter { - std::ostream& m_os; - std::vector<ColumnInfo> m_columnInfos; - std::ostringstream m_oss; - int m_currentColumn = -1; - bool m_isOpen = false; - -public: - TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos ) - : m_os( os ), - m_columnInfos( std::move( columnInfos ) ) {} - - auto columnInfos() const -> std::vector<ColumnInfo> const& { - return m_columnInfos; - } - - void open() { - if (!m_isOpen) { - m_isOpen = true; - *this << RowBreak(); - - Columns headerCols; - Spacer spacer(2); - for (auto const& info : m_columnInfos) { - headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2)); - headerCols += spacer; - } - m_os << headerCols << '\n'; - - m_os << Catch::getLineOfChars<'-'>() << '\n'; - } - } - void close() { - if (m_isOpen) { - *this << RowBreak(); - m_os << std::endl; - m_isOpen = false; - } - } - - template<typename T> - friend TablePrinter& operator << (TablePrinter& tp, T const& value) { - tp.m_oss << value; - return tp; - } - - friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) { - auto colStr = tp.m_oss.str(); - const auto strSize = colStr.size(); - tp.m_oss.str(""); - tp.open(); - if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) { - tp.m_currentColumn = -1; - tp.m_os << '\n'; - } - tp.m_currentColumn++; - - auto colInfo = tp.m_columnInfos[tp.m_currentColumn]; - auto padding = (strSize + 1 < static_cast<std::size_t>(colInfo.width)) - ? std::string(colInfo.width - (strSize + 1), ' ') - : std::string(); - if (colInfo.justification == ColumnInfo::Left) - tp.m_os << colStr << padding << ' '; - else - tp.m_os << padding << colStr << ' '; - return tp; - } - - friend TablePrinter& operator << (TablePrinter& tp, RowBreak) { - if (tp.m_currentColumn > 0) { - tp.m_os << '\n'; - tp.m_currentColumn = -1; - } - return tp; - } -}; - -ConsoleReporter::ConsoleReporter(ReporterConfig const& config) - : StreamingReporterBase(config), - m_tablePrinter(new TablePrinter(config.stream(), - [&config]() -> std::vector<ColumnInfo> { - if (config.fullConfig()->benchmarkNoAnalysis()) - { - return{ - { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left }, - { " samples", 14, ColumnInfo::Right }, - { " iterations", 14, ColumnInfo::Right }, - { " mean", 14, ColumnInfo::Right } + class Duration { + enum class Unit { + Auto, + Nanoseconds, + Microseconds, + Milliseconds, + Seconds, + Minutes }; + static const uint64_t s_nanosecondsInAMicrosecond = 1000; + static const uint64_t s_nanosecondsInAMillisecond = + 1000 * s_nanosecondsInAMicrosecond; + static const uint64_t s_nanosecondsInASecond = + 1000 * s_nanosecondsInAMillisecond; + static const uint64_t s_nanosecondsInAMinute = + 60 * s_nanosecondsInASecond; + + double m_inNanoseconds; + Unit m_units; + + public: + explicit Duration(double inNanoseconds, Unit units = Unit::Auto) : + m_inNanoseconds(inNanoseconds), m_units(units) { + if (m_units == Unit::Auto) { + if (m_inNanoseconds < s_nanosecondsInAMicrosecond) + m_units = Unit::Nanoseconds; + else if (m_inNanoseconds < s_nanosecondsInAMillisecond) + m_units = Unit::Microseconds; + else if (m_inNanoseconds < s_nanosecondsInASecond) + m_units = Unit::Milliseconds; + else if (m_inNanoseconds < s_nanosecondsInAMinute) + m_units = Unit::Seconds; + else + m_units = Unit::Minutes; + } + } + + auto value() const -> double { + switch (m_units) { + case Unit::Microseconds: + return m_inNanoseconds / + static_cast<double>(s_nanosecondsInAMicrosecond); + case Unit::Milliseconds: + return m_inNanoseconds / + static_cast<double>(s_nanosecondsInAMillisecond); + case Unit::Seconds: + return m_inNanoseconds / + static_cast<double>(s_nanosecondsInASecond); + case Unit::Minutes: + return m_inNanoseconds / + static_cast<double>(s_nanosecondsInAMinute); + default: + return m_inNanoseconds; + } + } + auto unitsAsString() const -> std::string { + switch (m_units) { + case Unit::Nanoseconds: + return "ns"; + case Unit::Microseconds: + return "us"; + case Unit::Milliseconds: + return "ms"; + case Unit::Seconds: + return "s"; + case Unit::Minutes: + return "m"; + default: + return "** internal error **"; + } + } + friend auto operator<<(std::ostream& os, Duration const& duration) + -> std::ostream& { + return os << duration.value() << ' ' + << duration.unitsAsString(); + } + }; + } // namespace + + class TablePrinter { + std::ostream& m_os; + std::vector<ColumnInfo> m_columnInfos; + std::ostringstream m_oss; + int m_currentColumn = -1; + bool m_isOpen = false; + + public: + TablePrinter(std::ostream& os, std::vector<ColumnInfo> columnInfos) : + m_os(os), m_columnInfos(std::move(columnInfos)) {} + + auto columnInfos() const -> std::vector<ColumnInfo> const& { + return m_columnInfos; } - else - { - return{ - { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left }, - { "samples mean std dev", 14, ColumnInfo::Right }, - { "iterations low mean low std dev", 14, ColumnInfo::Right }, - { "estimated high mean high std dev", 14, ColumnInfo::Right } - }; + + void open() { + if (!m_isOpen) { + m_isOpen = true; + *this << RowBreak(); + + Columns headerCols; + Spacer spacer(2); + for (auto const& info : m_columnInfos) { + headerCols += Column(info.name).width( + static_cast<std::size_t>(info.width - 2)); + headerCols += spacer; + } + m_os << headerCols << '\n'; + + m_os << Catch::getLineOfChars<'-'>() << '\n'; + } } - }())) {} -ConsoleReporter::~ConsoleReporter() = default; + void close() { + if (m_isOpen) { + *this << RowBreak(); + m_os << std::endl; + m_isOpen = false; + } + } -std::string ConsoleReporter::getDescription() { - return "Reports test results as plain lines of text"; -} + template <typename T> + friend TablePrinter& operator<<(TablePrinter& tp, T const& value) { + tp.m_oss << value; + return tp; + } -void ConsoleReporter::noMatchingTestCases(std::string const& spec) { - stream << "No test cases matched '" << spec << '\'' << std::endl; -} + friend TablePrinter& operator<<(TablePrinter& tp, ColumnBreak) { + auto colStr = tp.m_oss.str(); + const auto strSize = colStr.size(); + tp.m_oss.str(""); + tp.open(); + if (tp.m_currentColumn == + static_cast<int>(tp.m_columnInfos.size() - 1)) { + tp.m_currentColumn = -1; + tp.m_os << '\n'; + } + tp.m_currentColumn++; -void ConsoleReporter::reportInvalidArguments(std::string const&arg){ - stream << "Invalid Filter: " << arg << std::endl; -} + auto colInfo = tp.m_columnInfos[tp.m_currentColumn]; + auto padding = + (strSize + 1 < static_cast<std::size_t>(colInfo.width)) + ? std::string(colInfo.width - (strSize + 1), ' ') + : std::string(); + if (colInfo.justification == ColumnInfo::Left) + tp.m_os << colStr << padding << ' '; + else + tp.m_os << padding << colStr << ' '; + return tp; + } -void ConsoleReporter::assertionStarting(AssertionInfo const&) {} + friend TablePrinter& operator<<(TablePrinter& tp, RowBreak) { + if (tp.m_currentColumn > 0) { + tp.m_os << '\n'; + tp.m_currentColumn = -1; + } + return tp; + } + }; -bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) { - AssertionResult const& result = _assertionStats.assertionResult; + ConsoleReporter::ConsoleReporter(ReporterConfig const& config) : + StreamingReporterBase(config), + m_tablePrinter(new TablePrinter( + config.stream(), [&config]() -> std::vector<ColumnInfo> { + if (config.fullConfig()->benchmarkNoAnalysis()) { + return {{"benchmark name", + CATCH_CONFIG_CONSOLE_WIDTH - 43, + ColumnInfo::Left}, + {" samples", 14, ColumnInfo::Right}, + {" iterations", 14, ColumnInfo::Right}, + {" mean", 14, ColumnInfo::Right}}; + } else { + return {{"benchmark name", + CATCH_CONFIG_CONSOLE_WIDTH - 43, + ColumnInfo::Left}, + {"samples mean std dev", + 14, + ColumnInfo::Right}, + {"iterations low mean low std dev", + 14, + ColumnInfo::Right}, + {"estimated high mean high std dev", + 14, + ColumnInfo::Right}}; + } + }())) {} + ConsoleReporter::~ConsoleReporter() = default; - bool includeResults = m_config->includeSuccessfulResults() || !result.isOk(); + std::string ConsoleReporter::getDescription() { + return "Reports test results as plain lines of text"; + } - // Drop out if result was successful but we're not printing them. - if (!includeResults && result.getResultType() != ResultWas::Warning) - return false; + void ConsoleReporter::noMatchingTestCases(std::string const& spec) { + stream << "No test cases matched '" << spec << '\'' << std::endl; + } - lazyPrint(); + void ConsoleReporter::reportInvalidArguments(std::string const& arg) { + stream << "Invalid Filter: " << arg << std::endl; + } - ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults); - printer.print(); - stream << std::endl; - return true; -} + void ConsoleReporter::assertionStarting(AssertionInfo const&) {} -void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) { - m_tablePrinter->close(); - m_headerPrinted = false; - StreamingReporterBase::sectionStarting(_sectionInfo); -} -void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) { - m_tablePrinter->close(); - if (_sectionStats.missingAssertions) { + bool + ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) { + AssertionResult const& result = _assertionStats.assertionResult; + + bool includeResults = + m_config->includeSuccessfulResults() || !result.isOk(); + + // Drop out if result was successful but we're not printing them. + if (!includeResults && result.getResultType() != ResultWas::Warning) + return false; + lazyPrint(); - Colour colour(Colour::ResultError); - if (m_sectionStack.size() > 1) - stream << "\nNo assertions in section"; - else - stream << "\nNo assertions in test case"; - stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl; + + ConsoleAssertionPrinter printer( + stream, _assertionStats, includeResults); + printer.print(); + stream << std::endl; + return true; } - double dur = _sectionStats.durationInSeconds; - if (shouldShowDuration(*m_config, dur)) { - stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name << std::endl; - } - if (m_headerPrinted) { + + void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) { + m_tablePrinter->close(); m_headerPrinted = false; + StreamingReporterBase::sectionStarting(_sectionInfo); } - StreamingReporterBase::sectionEnded(_sectionStats); -} + void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) { + m_tablePrinter->close(); + if (_sectionStats.missingAssertions) { + lazyPrint(); + Colour colour(Colour::ResultError); + if (m_sectionStack.size() > 1) + stream << "\nNo assertions in section"; + else + stream << "\nNo assertions in test case"; + stream << " '" << _sectionStats.sectionInfo.name << "'\n" + << std::endl; + } + double dur = _sectionStats.durationInSeconds; + if (shouldShowDuration(*m_config, dur)) { + stream << getFormattedDuration(dur) + << " s: " << _sectionStats.sectionInfo.name << std::endl; + } + if (m_headerPrinted) { + m_headerPrinted = false; + } + StreamingReporterBase::sectionEnded(_sectionStats); + } #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) -void ConsoleReporter::benchmarkPreparing(std::string const& name) { - lazyPrintWithoutClosingBenchmarkTable(); + void ConsoleReporter::benchmarkPreparing(std::string const& name) { + lazyPrintWithoutClosingBenchmarkTable(); - auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2)); + auto nameCol = Column(name).width(static_cast<std::size_t>( + m_tablePrinter->columnInfos()[0].width - 2)); - bool firstLine = true; - for (auto line : nameCol) { - if (!firstLine) - (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak(); - else - firstLine = false; + bool firstLine = true; + for (auto line : nameCol) { + if (!firstLine) + (*m_tablePrinter) + << ColumnBreak() << ColumnBreak() << ColumnBreak(); + else + firstLine = false; - (*m_tablePrinter) << line << ColumnBreak(); - } -} - -void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) { - (*m_tablePrinter) << info.samples << ColumnBreak() - << info.iterations << ColumnBreak(); - if (!m_config->benchmarkNoAnalysis()) - (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak(); -} -void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) { - if (m_config->benchmarkNoAnalysis()) - { - (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak(); + (*m_tablePrinter) << line << ColumnBreak(); + } } - else - { - (*m_tablePrinter) << ColumnBreak() - << Duration(stats.mean.point.count()) << ColumnBreak() - << Duration(stats.mean.lower_bound.count()) << ColumnBreak() - << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak() - << Duration(stats.standardDeviation.point.count()) << ColumnBreak() - << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak() - << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak(); - } -} -void ConsoleReporter::benchmarkFailed(std::string const& error) { - Colour colour(Colour::Red); - (*m_tablePrinter) - << "Benchmark failed (" << error << ')' - << ColumnBreak() << RowBreak(); -} + void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) { + (*m_tablePrinter) << info.samples << ColumnBreak() << info.iterations + << ColumnBreak(); + if (!m_config->benchmarkNoAnalysis()) + (*m_tablePrinter) + << Duration(info.estimatedDuration) << ColumnBreak(); + } + void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) { + if (m_config->benchmarkNoAnalysis()) { + (*m_tablePrinter) + << Duration(stats.mean.point.count()) << ColumnBreak(); + } else { + (*m_tablePrinter) + << ColumnBreak() << Duration(stats.mean.point.count()) + << ColumnBreak() << Duration(stats.mean.lower_bound.count()) + << ColumnBreak() << Duration(stats.mean.upper_bound.count()) + << ColumnBreak() << ColumnBreak() + << Duration(stats.standardDeviation.point.count()) + << ColumnBreak() + << Duration(stats.standardDeviation.lower_bound.count()) + << ColumnBreak() + << Duration(stats.standardDeviation.upper_bound.count()) + << ColumnBreak() << ColumnBreak() << ColumnBreak() + << ColumnBreak() << ColumnBreak(); + } + } + + void ConsoleReporter::benchmarkFailed(std::string const& error) { + Colour colour(Colour::Red); + (*m_tablePrinter) << "Benchmark failed (" << error << ')' + << ColumnBreak() << RowBreak(); + } #endif // CATCH_CONFIG_ENABLE_BENCHMARKING -void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) { - m_tablePrinter->close(); - StreamingReporterBase::testCaseEnded(_testCaseStats); - m_headerPrinted = false; -} -void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) { - if (currentGroupInfo.used) { - printSummaryDivider(); - stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n"; - printTotals(_testGroupStats.totals); - stream << '\n' << std::endl; + void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) { + m_tablePrinter->close(); + StreamingReporterBase::testCaseEnded(_testCaseStats); + m_headerPrinted = false; } - StreamingReporterBase::testGroupEnded(_testGroupStats); -} -void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) { - printTotalsDivider(_testRunStats.totals); - printTotals(_testRunStats.totals); - stream << std::endl; - StreamingReporterBase::testRunEnded(_testRunStats); -} -void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) { - StreamingReporterBase::testRunStarting(_testInfo); - printTestFilters(); -} - -void ConsoleReporter::lazyPrint() { - - m_tablePrinter->close(); - lazyPrintWithoutClosingBenchmarkTable(); -} - -void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() { - - if (!currentTestRunInfo.used) - lazyPrintRunInfo(); - if (!currentGroupInfo.used) - lazyPrintGroupInfo(); - - if (!m_headerPrinted) { - printTestCaseAndSectionHeader(); - m_headerPrinted = true; - } -} -void ConsoleReporter::lazyPrintRunInfo() { - stream << '\n' << getLineOfChars<'~'>() << '\n'; - Colour colour(Colour::SecondaryText); - stream << currentTestRunInfo->name - << " is a Catch v" << libraryVersion() << " host application.\n" - << "Run with -? for options\n\n"; - - if (m_config->rngSeed() != 0) - stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n"; - - currentTestRunInfo.used = true; -} -void ConsoleReporter::lazyPrintGroupInfo() { - if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) { - printClosedHeader("Group: " + currentGroupInfo->name); - currentGroupInfo.used = true; - } -} -void ConsoleReporter::printTestCaseAndSectionHeader() { - assert(!m_sectionStack.empty()); - printOpenHeader(currentTestCaseInfo->name); - - if (m_sectionStack.size() > 1) { - Colour colourGuard(Colour::Headers); - - auto - it = m_sectionStack.begin() + 1, // Skip first section (test case) - itEnd = m_sectionStack.end(); - for (; it != itEnd; ++it) - printHeaderString(it->name, 2); - } - - SourceLineInfo lineInfo = m_sectionStack.back().lineInfo; - - stream << getLineOfChars<'-'>() << '\n'; - Colour colourGuard(Colour::FileName); - stream << lineInfo << '\n'; - stream << getLineOfChars<'.'>() << '\n' << std::endl; -} - -void ConsoleReporter::printClosedHeader(std::string const& _name) { - printOpenHeader(_name); - stream << getLineOfChars<'.'>() << '\n'; -} -void ConsoleReporter::printOpenHeader(std::string const& _name) { - stream << getLineOfChars<'-'>() << '\n'; - { - Colour colourGuard(Colour::Headers); - printHeaderString(_name); - } -} - -// if string has a : in first line will set indent to follow it on -// subsequent lines -void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) { - std::size_t i = _string.find(": "); - if (i != std::string::npos) - i += 2; - else - i = 0; - stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n'; -} - -struct SummaryColumn { - - SummaryColumn( std::string _label, Colour::Code _colour ) - : label( std::move( _label ) ), - colour( _colour ) {} - SummaryColumn addRow( std::size_t count ) { - ReusableStringStream rss; - rss << count; - std::string row = rss.str(); - for (auto& oldRow : rows) { - while (oldRow.size() < row.size()) - oldRow = ' ' + oldRow; - while (oldRow.size() > row.size()) - row = ' ' + row; + void + ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) { + if (currentGroupInfo.used) { + printSummaryDivider(); + stream << "Summary for group '" << _testGroupStats.groupInfo.name + << "':\n"; + printTotals(_testGroupStats.totals); + stream << '\n' << std::endl; } - rows.push_back(row); - return *this; + StreamingReporterBase::testGroupEnded(_testGroupStats); + } + void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) { + printTotalsDivider(_testRunStats.totals); + printTotals(_testRunStats.totals); + stream << std::endl; + StreamingReporterBase::testRunEnded(_testRunStats); + } + void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) { + StreamingReporterBase::testRunStarting(_testInfo); + printTestFilters(); } - std::string label; - Colour::Code colour; - std::vector<std::string> rows; + void ConsoleReporter::lazyPrint() { -}; - -void ConsoleReporter::printTotals( Totals const& totals ) { - if (totals.testCases.total() == 0) { - stream << Colour(Colour::Warning) << "No tests ran\n"; - } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) { - stream << Colour(Colour::ResultSuccess) << "All tests passed"; - stream << " (" - << pluralise(totals.assertions.passed, "assertion") << " in " - << pluralise(totals.testCases.passed, "test case") << ')' - << '\n'; - } else { - - std::vector<SummaryColumn> columns; - columns.push_back(SummaryColumn("", Colour::None) - .addRow(totals.testCases.total()) - .addRow(totals.assertions.total())); - columns.push_back(SummaryColumn("passed", Colour::Success) - .addRow(totals.testCases.passed) - .addRow(totals.assertions.passed)); - columns.push_back(SummaryColumn("failed", Colour::ResultError) - .addRow(totals.testCases.failed) - .addRow(totals.assertions.failed)); - columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure) - .addRow(totals.testCases.failedButOk) - .addRow(totals.assertions.failedButOk)); - - printSummaryRow("test cases", columns, 0); - printSummaryRow("assertions", columns, 1); + m_tablePrinter->close(); + lazyPrintWithoutClosingBenchmarkTable(); } -} -void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) { - for (auto col : cols) { - std::string value = col.rows[row]; - if (col.label.empty()) { - stream << label << ": "; - if (value != "0") - stream << value; - else - stream << Colour(Colour::Warning) << "- none -"; - } else if (value != "0") { - stream << Colour(Colour::LightGrey) << " | "; - stream << Colour(col.colour) - << value << ' ' << col.label; + + void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() { + + if (!currentTestRunInfo.used) + lazyPrintRunInfo(); + if (!currentGroupInfo.used) + lazyPrintGroupInfo(); + + if (!m_headerPrinted) { + printTestCaseAndSectionHeader(); + m_headerPrinted = true; } } - stream << '\n'; -} + void ConsoleReporter::lazyPrintRunInfo() { + stream << '\n' << getLineOfChars<'~'>() << '\n'; + Colour colour(Colour::SecondaryText); + stream << currentTestRunInfo->name << " is a Catch v" + << libraryVersion() << " host application.\n" + << "Run with -? for options\n\n"; -void ConsoleReporter::printTotalsDivider(Totals const& totals) { - if (totals.testCases.total() > 0) { - std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total()); - std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total()); - std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total()); - while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1) - findMax(failedRatio, failedButOkRatio, passedRatio)++; - while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1) - findMax(failedRatio, failedButOkRatio, passedRatio)--; + if (m_config->rngSeed() != 0) + stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n"; - stream << Colour(Colour::Error) << std::string(failedRatio, '='); - stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '='); - if (totals.testCases.allPassed()) - stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '='); + currentTestRunInfo.used = true; + } + void ConsoleReporter::lazyPrintGroupInfo() { + if (!currentGroupInfo->name.empty() && + currentGroupInfo->groupsCounts > 1) { + printClosedHeader("Group: " + currentGroupInfo->name); + currentGroupInfo.used = true; + } + } + void ConsoleReporter::printTestCaseAndSectionHeader() { + assert(!m_sectionStack.empty()); + printOpenHeader(currentTestCaseInfo->name); + + if (m_sectionStack.size() > 1) { + Colour colourGuard(Colour::Headers); + + auto it = m_sectionStack.begin() + + 1, // Skip first section (test case) + itEnd = m_sectionStack.end(); + for (; it != itEnd; ++it) + printHeaderString(it->name, 2); + } + + SourceLineInfo lineInfo = m_sectionStack.back().lineInfo; + + stream << getLineOfChars<'-'>() << '\n'; + Colour colourGuard(Colour::FileName); + stream << lineInfo << '\n'; + stream << getLineOfChars<'.'>() << '\n' << std::endl; + } + + void ConsoleReporter::printClosedHeader(std::string const& _name) { + printOpenHeader(_name); + stream << getLineOfChars<'.'>() << '\n'; + } + void ConsoleReporter::printOpenHeader(std::string const& _name) { + stream << getLineOfChars<'-'>() << '\n'; + { + Colour colourGuard(Colour::Headers); + printHeaderString(_name); + } + } + + // if string has a : in first line will set indent to follow it on + // subsequent lines + void ConsoleReporter::printHeaderString(std::string const& _string, + std::size_t indent) { + std::size_t i = _string.find(": "); + if (i != std::string::npos) + i += 2; else - stream << Colour(Colour::Success) << std::string(passedRatio, '='); - } else { - stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '='); + i = 0; + stream << Column(_string).indent(indent + i).initialIndent(indent) + << '\n'; } - stream << '\n'; -} -void ConsoleReporter::printSummaryDivider() { - stream << getLineOfChars<'-'>() << '\n'; -} -void ConsoleReporter::printTestFilters() { - if (m_config->testSpec().hasFilters()) { - Colour guard(Colour::BrightYellow); - stream << "Filters: " << serializeFilters(m_config->getTestsOrTags()) << '\n'; + struct SummaryColumn { + + SummaryColumn(std::string _label, Colour::Code _colour) : + label(std::move(_label)), colour(_colour) {} + SummaryColumn addRow(std::size_t count) { + ReusableStringStream rss; + rss << count; + std::string row = rss.str(); + for (auto& oldRow : rows) { + while (oldRow.size() < row.size()) + oldRow = ' ' + oldRow; + while (oldRow.size() > row.size()) + row = ' ' + row; + } + rows.push_back(row); + return *this; + } + + std::string label; + Colour::Code colour; + std::vector<std::string> rows; + }; + + void ConsoleReporter::printTotals(Totals const& totals) { + if (totals.testCases.total() == 0) { + stream << Colour(Colour::Warning) << "No tests ran\n"; + } else if (totals.assertions.total() > 0 && + totals.testCases.allPassed()) { + stream << Colour(Colour::ResultSuccess) << "All tests passed"; + stream << " (" << pluralise(totals.assertions.passed, "assertion") + << " in " << pluralise(totals.testCases.passed, "test case") + << ')' << '\n'; + } else { + + std::vector<SummaryColumn> columns; + columns.push_back(SummaryColumn("", Colour::None) + .addRow(totals.testCases.total()) + .addRow(totals.assertions.total())); + columns.push_back(SummaryColumn("passed", Colour::Success) + .addRow(totals.testCases.passed) + .addRow(totals.assertions.passed)); + columns.push_back(SummaryColumn("failed", Colour::ResultError) + .addRow(totals.testCases.failed) + .addRow(totals.assertions.failed)); + columns.push_back(SummaryColumn("failed as expected", + Colour::ResultExpectedFailure) + .addRow(totals.testCases.failedButOk) + .addRow(totals.assertions.failedButOk)); + + printSummaryRow("test cases", columns, 0); + printSummaryRow("assertions", columns, 1); + } } -} + void + ConsoleReporter::printSummaryRow(std::string const& label, + std::vector<SummaryColumn> const& cols, + std::size_t row) { + for (auto col : cols) { + std::string value = col.rows[row]; + if (col.label.empty()) { + stream << label << ": "; + if (value != "0") + stream << value; + else + stream << Colour(Colour::Warning) << "- none -"; + } else if (value != "0") { + stream << Colour(Colour::LightGrey) << " | "; + stream << Colour(col.colour) << value << ' ' << col.label; + } + } + stream << '\n'; + } -CATCH_REGISTER_REPORTER("console", ConsoleReporter) + void ConsoleReporter::printTotalsDivider(Totals const& totals) { + if (totals.testCases.total() > 0) { + std::size_t failedRatio = + makeRatio(totals.testCases.failed, totals.testCases.total()); + std::size_t failedButOkRatio = makeRatio( + totals.testCases.failedButOk, totals.testCases.total()); + std::size_t passedRatio = + makeRatio(totals.testCases.passed, totals.testCases.total()); + while (failedRatio + failedButOkRatio + passedRatio < + CATCH_CONFIG_CONSOLE_WIDTH - 1) + findMax(failedRatio, failedButOkRatio, passedRatio)++; + while (failedRatio + failedButOkRatio + passedRatio > + CATCH_CONFIG_CONSOLE_WIDTH - 1) + findMax(failedRatio, failedButOkRatio, passedRatio)--; + + stream << Colour(Colour::Error) << std::string(failedRatio, '='); + stream << Colour(Colour::ResultExpectedFailure) + << std::string(failedButOkRatio, '='); + if (totals.testCases.allPassed()) + stream << Colour(Colour::ResultSuccess) + << std::string(passedRatio, '='); + else + stream << Colour(Colour::Success) + << std::string(passedRatio, '='); + } else { + stream << Colour(Colour::Warning) + << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '='); + } + stream << '\n'; + } + void ConsoleReporter::printSummaryDivider() { + stream << getLineOfChars<'-'>() << '\n'; + } + + void ConsoleReporter::printTestFilters() { + if (m_config->testSpec().hasFilters()) { + Colour guard(Colour::BrightYellow); + stream << "Filters: " + << serializeFilters(m_config->getTestsOrTags()) << '\n'; + } + } + + CATCH_REGISTER_REPORTER("console", ConsoleReporter) } // end namespace Catch @@ -16784,7 +18471,7 @@ #endif #if defined(__clang__) -# pragma clang diagnostic pop +#pragma clang diagnostic pop #endif // end catch_reporter_console.cpp // start catch_reporter_junit.cpp @@ -16799,8 +18486,9 @@ namespace { std::string getCurrentTimestamp() { - // Beware, this is not reentrant because of backward compatibility issues - // Also, UTC only, again because of backward compatibility (%z is C++11) + // Beware, this is not reentrant because of backward compatibility + // issues Also, UTC only, again because of backward compatibility + // (%z is C++11) time_t rawtime; std::time(&rawtime); auto const timeStampSize = sizeof("2017-01-16T17:06:45Z"); @@ -16814,20 +18502,21 @@ #endif char timeStamp[timeStampSize]; - const char * const fmt = "%Y-%m-%dT%H:%M:%SZ"; + const char* const fmt = "%Y-%m-%dT%H:%M:%SZ"; #ifdef _MSC_VER std::strftime(timeStamp, timeStampSize, fmt, &timeInfo); #else std::strftime(timeStamp, timeStampSize, fmt, timeInfo); #endif - return std::string(timeStamp, timeStampSize-1); + return std::string(timeStamp, timeStampSize - 1); } - std::string fileNameTag(const std::vector<std::string> &tags) { - auto it = std::find_if(begin(tags), - end(tags), - [] (std::string const& tag) {return tag.front() == '#'; }); + std::string fileNameTag(const std::vector<std::string>& tags) { + auto it = std::find_if( + begin(tags), end(tags), [](std::string const& tag) { + return tag.front() == '#'; + }); if (it != tags.end()) return it->substr(1); return std::string(); @@ -16837,83 +18526,84 @@ // This is done because some genius defined Maven Surefire schema // in a way that only accepts 3 decimal places, and tools like // Jenkins use that schema for validation JUnit reporter output. - std::string formatDuration( double seconds ) { + std::string formatDuration(double seconds) { ReusableStringStream rss; - rss << std::fixed << std::setprecision( 3 ) << seconds; + rss << std::fixed << std::setprecision(3) << seconds; return rss.str(); } } // anonymous namespace - JunitReporter::JunitReporter( ReporterConfig const& _config ) - : CumulativeReporterBase( _config ), - xml( _config.stream() ) - { - m_reporterPrefs.shouldRedirectStdOut = true; - m_reporterPrefs.shouldReportAllAssertions = true; - } + JunitReporter::JunitReporter(ReporterConfig const& _config) : + CumulativeReporterBase(_config), xml(_config.stream()) { + m_reporterPrefs.shouldRedirectStdOut = true; + m_reporterPrefs.shouldReportAllAssertions = true; + } JunitReporter::~JunitReporter() {} std::string JunitReporter::getDescription() { - return "Reports test results in an XML format that looks like Ant's junitreport target"; + return "Reports test results in an XML format that looks like Ant's " + "junitreport target"; } - void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {} + void JunitReporter::noMatchingTestCases(std::string const& /*spec*/) {} - void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) { - CumulativeReporterBase::testRunStarting( runInfo ); - xml.startElement( "testsuites" ); + void JunitReporter::testRunStarting(TestRunInfo const& runInfo) { + CumulativeReporterBase::testRunStarting(runInfo); + xml.startElement("testsuites"); } - void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) { + void JunitReporter::testGroupStarting(GroupInfo const& groupInfo) { suiteTimer.start(); stdOutForSuite.clear(); stdErrForSuite.clear(); unexpectedExceptions = 0; - CumulativeReporterBase::testGroupStarting( groupInfo ); + CumulativeReporterBase::testGroupStarting(groupInfo); } - void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) { + void JunitReporter::testCaseStarting(TestCaseInfo const& testCaseInfo) { m_okToFail = testCaseInfo.okToFail(); } - bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) { - if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail ) + bool JunitReporter::assertionEnded(AssertionStats const& assertionStats) { + if (assertionStats.assertionResult.getResultType() == + ResultWas::ThrewException && + !m_okToFail) unexpectedExceptions++; - return CumulativeReporterBase::assertionEnded( assertionStats ); + return CumulativeReporterBase::assertionEnded(assertionStats); } - void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) { + void JunitReporter::testCaseEnded(TestCaseStats const& testCaseStats) { stdOutForSuite += testCaseStats.stdOut; stdErrForSuite += testCaseStats.stdErr; - CumulativeReporterBase::testCaseEnded( testCaseStats ); + CumulativeReporterBase::testCaseEnded(testCaseStats); } - void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) { + void JunitReporter::testGroupEnded(TestGroupStats const& testGroupStats) { double suiteTime = suiteTimer.getElapsedSeconds(); - CumulativeReporterBase::testGroupEnded( testGroupStats ); - writeGroup( *m_testGroups.back(), suiteTime ); + CumulativeReporterBase::testGroupEnded(testGroupStats); + writeGroup(*m_testGroups.back(), suiteTime); } - void JunitReporter::testRunEndedCumulative() { - xml.endElement(); - } + void JunitReporter::testRunEndedCumulative() { xml.endElement(); } - void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) { - XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" ); + void JunitReporter::writeGroup(TestGroupNode const& groupNode, + double suiteTime) { + XmlWriter::ScopedElement e = xml.scopedElement("testsuite"); TestGroupStats const& stats = groupNode.value; - xml.writeAttribute( "name", stats.groupInfo.name ); - xml.writeAttribute( "errors", unexpectedExceptions ); - xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions ); - xml.writeAttribute( "tests", stats.totals.assertions.total() ); - xml.writeAttribute( "hostname", "tbd" ); // !TBD - if( m_config->showDurations() == ShowDurations::Never ) - xml.writeAttribute( "time", "" ); + xml.writeAttribute("name", stats.groupInfo.name); + xml.writeAttribute("errors", unexpectedExceptions); + xml.writeAttribute( + "failures", stats.totals.assertions.failed - unexpectedExceptions); + xml.writeAttribute("tests", stats.totals.assertions.total()); + xml.writeAttribute("hostname", "tbd"); // !TBD + if (m_config->showDurations() == ShowDurations::Never) + xml.writeAttribute("time", ""); else - xml.writeAttribute( "time", formatDuration( suiteTime ) ); - xml.writeAttribute( "timestamp", getCurrentTimestamp() ); + xml.writeAttribute("time", formatDuration(suiteTime)); + xml.writeAttribute("timestamp", getCurrentTimestamp()); // Write properties if there are any if (m_config->hasTestFilters() || m_config->rngSeed() != 0) { @@ -16921,7 +18611,8 @@ if (m_config->hasTestFilters()) { xml.scopedElement("property") .writeAttribute("name", "filters") - .writeAttribute("value", serializeFilters(m_config->getTestsOrTags())); + .writeAttribute( + "value", serializeFilters(m_config->getTestsOrTags())); } if (m_config->rngSeed() != 0) { xml.scopedElement("property") @@ -16931,91 +18622,97 @@ } // Write test cases - for( auto const& child : groupNode.children ) - writeTestCase( *child ); + for (auto const& child : groupNode.children) + writeTestCase(*child); - xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), XmlFormatting::Newline ); - xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), XmlFormatting::Newline ); + xml.scopedElement("system-out") + .writeText(trim(stdOutForSuite), XmlFormatting::Newline); + xml.scopedElement("system-err") + .writeText(trim(stdErrForSuite), XmlFormatting::Newline); } - void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) { + void JunitReporter::writeTestCase(TestCaseNode const& testCaseNode) { TestCaseStats const& stats = testCaseNode.value; // All test cases have exactly one section - which represents the // test case itself. That section may have 0-n nested sections - assert( testCaseNode.children.size() == 1 ); + assert(testCaseNode.children.size() == 1); SectionNode const& rootSection = *testCaseNode.children.front(); std::string className = stats.testInfo.className; - if( className.empty() ) { + if (className.empty()) { className = fileNameTag(stats.testInfo.tags); - if ( className.empty() ) + if (className.empty()) className = "global"; } - if ( !m_config->name().empty() ) + if (!m_config->name().empty()) className = m_config->name() + "." + className; - writeSection( className, "", rootSection, stats.testInfo.okToFail() ); + writeSection(className, "", rootSection, stats.testInfo.okToFail()); } - void JunitReporter::writeSection( std::string const& className, - std::string const& rootName, - SectionNode const& sectionNode, - bool testOkToFail) { - std::string name = trim( sectionNode.stats.sectionInfo.name ); - if( !rootName.empty() ) + void JunitReporter::writeSection(std::string const& className, + std::string const& rootName, + SectionNode const& sectionNode, + bool testOkToFail) { + std::string name = trim(sectionNode.stats.sectionInfo.name); + if (!rootName.empty()) name = rootName + '/' + name; - if( !sectionNode.assertions.empty() || - !sectionNode.stdOut.empty() || - !sectionNode.stdErr.empty() ) { - XmlWriter::ScopedElement e = xml.scopedElement( "testcase" ); - if( className.empty() ) { - xml.writeAttribute( "classname", name ); - xml.writeAttribute( "name", "root" ); + if (!sectionNode.assertions.empty() || !sectionNode.stdOut.empty() || + !sectionNode.stdErr.empty()) + { + XmlWriter::ScopedElement e = xml.scopedElement("testcase"); + if (className.empty()) { + xml.writeAttribute("classname", name); + xml.writeAttribute("name", "root"); + } else { + xml.writeAttribute("classname", className); + xml.writeAttribute("name", name); } - else { - xml.writeAttribute( "classname", className ); - xml.writeAttribute( "name", name ); - } - xml.writeAttribute( "time", formatDuration( sectionNode.stats.durationInSeconds ) ); + xml.writeAttribute( + "time", formatDuration(sectionNode.stats.durationInSeconds)); // This is not ideal, but it should be enough to mimic gtest's // junit output. // Ideally the JUnit reporter would also handle `skipTest` // events and write those out appropriately. - xml.writeAttribute( "status", "run" ); + xml.writeAttribute("status", "run"); if (sectionNode.stats.assertions.failedButOk) { - xml.scopedElement("skipped") - .writeAttribute("message", "TEST_CASE tagged with !mayfail"); + xml.scopedElement("skipped").writeAttribute( + "message", "TEST_CASE tagged with !mayfail"); } - writeAssertions( sectionNode ); + writeAssertions(sectionNode); - if( !sectionNode.stdOut.empty() ) - xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), XmlFormatting::Newline ); - if( !sectionNode.stdErr.empty() ) - xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), XmlFormatting::Newline ); + if (!sectionNode.stdOut.empty()) + xml.scopedElement("system-out") + .writeText(trim(sectionNode.stdOut), + XmlFormatting::Newline); + if (!sectionNode.stdErr.empty()) + xml.scopedElement("system-err") + .writeText(trim(sectionNode.stdErr), + XmlFormatting::Newline); } - for( auto const& childNode : sectionNode.childSections ) - if( className.empty() ) - writeSection( name, "", *childNode, testOkToFail ); + for (auto const& childNode : sectionNode.childSections) + if (className.empty()) + writeSection(name, "", *childNode, testOkToFail); else - writeSection( className, name, *childNode, testOkToFail ); + writeSection(className, name, *childNode, testOkToFail); } - void JunitReporter::writeAssertions( SectionNode const& sectionNode ) { - for( auto const& assertion : sectionNode.assertions ) - writeAssertion( assertion ); + void JunitReporter::writeAssertions(SectionNode const& sectionNode) { + for (auto const& assertion : sectionNode.assertions) + writeAssertion(assertion); } - void JunitReporter::writeAssertion( AssertionStats const& stats ) { + void JunitReporter::writeAssertion(AssertionStats const& stats) { AssertionResult const& result = stats.assertionResult; - if( !result.isOk() ) { + if (!result.isOk()) { std::string elementName; - switch( result.getResultType() ) { + switch (result.getResultType()) { case ResultWas::ThrewException: case ResultWas::FatalErrorCondition: elementName = "error"; @@ -17037,14 +18734,15 @@ break; } - XmlWriter::ScopedElement e = xml.scopedElement( elementName ); + XmlWriter::ScopedElement e = xml.scopedElement(elementName); - xml.writeAttribute( "message", result.getExpression() ); - xml.writeAttribute( "type", result.getTestMacroName() ); + xml.writeAttribute("message", result.getExpression()); + xml.writeAttribute("type", result.getTestMacroName()); ReusableStringStream rss; if (stats.totals.assertions.total() > 0) { - rss << "FAILED" << ":\n"; + rss << "FAILED" + << ":\n"; if (result.hasExpression()) { rss << " "; rss << result.getExpressionInMacro(); @@ -17052,24 +18750,25 @@ } if (result.hasExpandedExpression()) { rss << "with expansion:\n"; - rss << Column(result.getExpandedExpression()).indent(2) << '\n'; + rss << Column(result.getExpandedExpression()).indent(2) + << '\n'; } } else { rss << '\n'; } - if( !result.getMessage().empty() ) + if (!result.getMessage().empty()) rss << result.getMessage() << '\n'; - for( auto const& msg : stats.infoMessages ) - if( msg.type == ResultWas::Info ) + for (auto const& msg : stats.infoMessages) + if (msg.type == ResultWas::Info) rss << msg.message << '\n'; rss << "at " << result.getSourceInfo(); - xml.writeText( rss.str(), XmlFormatting::Newline ); + xml.writeText(rss.str(), XmlFormatting::Newline); } } - CATCH_REGISTER_REPORTER( "junit", JunitReporter ) + CATCH_REGISTER_REPORTER("junit", JunitReporter) } // end namespace Catch // end catch_reporter_junit.cpp @@ -17084,14 +18783,16 @@ m_preferences.shouldReportAllAssertions = true; } - void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) { - m_listeners.push_back( std::move( listener ) ); + void ListeningReporter::addListener(IStreamingReporterPtr&& listener) { + m_listeners.push_back(std::move(listener)); } void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) { - assert(!m_reporter && "Listening reporter can wrap only 1 real reporter"); - m_reporter = std::move( reporter ); - m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut; + assert(!m_reporter && + "Listening reporter can wrap only 1 real reporter"); + m_reporter = std::move(reporter); + m_preferences.shouldRedirectStdOut = + m_reporter->getPreferences().shouldRedirectStdOut; } ReporterPreferences ListeningReporter::getPreferences() const { @@ -17099,132 +18800,135 @@ } std::set<Verbosity> ListeningReporter::getSupportedVerbosities() { - return std::set<Verbosity>{ }; + return std::set<Verbosity>{}; } - void ListeningReporter::noMatchingTestCases( std::string const& spec ) { - for ( auto const& listener : m_listeners ) { - listener->noMatchingTestCases( spec ); + void ListeningReporter::noMatchingTestCases(std::string const& spec) { + for (auto const& listener : m_listeners) { + listener->noMatchingTestCases(spec); } - m_reporter->noMatchingTestCases( spec ); + m_reporter->noMatchingTestCases(spec); } - void ListeningReporter::reportInvalidArguments(std::string const&arg){ - for ( auto const& listener : m_listeners ) { - listener->reportInvalidArguments( arg ); + void ListeningReporter::reportInvalidArguments(std::string const& arg) { + for (auto const& listener : m_listeners) { + listener->reportInvalidArguments(arg); } - m_reporter->reportInvalidArguments( arg ); + m_reporter->reportInvalidArguments(arg); } #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) - void ListeningReporter::benchmarkPreparing( std::string const& name ) { - for (auto const& listener : m_listeners) { - listener->benchmarkPreparing(name); - } - m_reporter->benchmarkPreparing(name); - } - void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) { - for ( auto const& listener : m_listeners ) { - listener->benchmarkStarting( benchmarkInfo ); + void ListeningReporter::benchmarkPreparing(std::string const& name) { + for (auto const& listener : m_listeners) { + listener->benchmarkPreparing(name); } - m_reporter->benchmarkStarting( benchmarkInfo ); + m_reporter->benchmarkPreparing(name); } - void ListeningReporter::benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) { - for ( auto const& listener : m_listeners ) { - listener->benchmarkEnded( benchmarkStats ); + void + ListeningReporter::benchmarkStarting(BenchmarkInfo const& benchmarkInfo) { + for (auto const& listener : m_listeners) { + listener->benchmarkStarting(benchmarkInfo); } - m_reporter->benchmarkEnded( benchmarkStats ); + m_reporter->benchmarkStarting(benchmarkInfo); + } + void + ListeningReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) { + for (auto const& listener : m_listeners) { + listener->benchmarkEnded(benchmarkStats); + } + m_reporter->benchmarkEnded(benchmarkStats); } - void ListeningReporter::benchmarkFailed( std::string const& error ) { - for (auto const& listener : m_listeners) { - listener->benchmarkFailed(error); - } - m_reporter->benchmarkFailed(error); - } + void ListeningReporter::benchmarkFailed(std::string const& error) { + for (auto const& listener : m_listeners) { + listener->benchmarkFailed(error); + } + m_reporter->benchmarkFailed(error); + } #endif // CATCH_CONFIG_ENABLE_BENCHMARKING - void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) { - for ( auto const& listener : m_listeners ) { - listener->testRunStarting( testRunInfo ); + void ListeningReporter::testRunStarting(TestRunInfo const& testRunInfo) { + for (auto const& listener : m_listeners) { + listener->testRunStarting(testRunInfo); } - m_reporter->testRunStarting( testRunInfo ); + m_reporter->testRunStarting(testRunInfo); } - void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) { - for ( auto const& listener : m_listeners ) { - listener->testGroupStarting( groupInfo ); + void ListeningReporter::testGroupStarting(GroupInfo const& groupInfo) { + for (auto const& listener : m_listeners) { + listener->testGroupStarting(groupInfo); } - m_reporter->testGroupStarting( groupInfo ); + m_reporter->testGroupStarting(groupInfo); } - void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) { - for ( auto const& listener : m_listeners ) { - listener->testCaseStarting( testInfo ); + void ListeningReporter::testCaseStarting(TestCaseInfo const& testInfo) { + for (auto const& listener : m_listeners) { + listener->testCaseStarting(testInfo); } - m_reporter->testCaseStarting( testInfo ); + m_reporter->testCaseStarting(testInfo); } - void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) { - for ( auto const& listener : m_listeners ) { - listener->sectionStarting( sectionInfo ); + void ListeningReporter::sectionStarting(SectionInfo const& sectionInfo) { + for (auto const& listener : m_listeners) { + listener->sectionStarting(sectionInfo); } - m_reporter->sectionStarting( sectionInfo ); + m_reporter->sectionStarting(sectionInfo); } - void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) { - for ( auto const& listener : m_listeners ) { - listener->assertionStarting( assertionInfo ); + void + ListeningReporter::assertionStarting(AssertionInfo const& assertionInfo) { + for (auto const& listener : m_listeners) { + listener->assertionStarting(assertionInfo); } - m_reporter->assertionStarting( assertionInfo ); + m_reporter->assertionStarting(assertionInfo); } // The return value indicates if the messages buffer should be cleared: - bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) { - for( auto const& listener : m_listeners ) { - static_cast<void>( listener->assertionEnded( assertionStats ) ); + bool + ListeningReporter::assertionEnded(AssertionStats const& assertionStats) { + for (auto const& listener : m_listeners) { + static_cast<void>(listener->assertionEnded(assertionStats)); } - return m_reporter->assertionEnded( assertionStats ); + return m_reporter->assertionEnded(assertionStats); } - void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) { - for ( auto const& listener : m_listeners ) { - listener->sectionEnded( sectionStats ); + void ListeningReporter::sectionEnded(SectionStats const& sectionStats) { + for (auto const& listener : m_listeners) { + listener->sectionEnded(sectionStats); } - m_reporter->sectionEnded( sectionStats ); + m_reporter->sectionEnded(sectionStats); } - void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) { - for ( auto const& listener : m_listeners ) { - listener->testCaseEnded( testCaseStats ); + void ListeningReporter::testCaseEnded(TestCaseStats const& testCaseStats) { + for (auto const& listener : m_listeners) { + listener->testCaseEnded(testCaseStats); } - m_reporter->testCaseEnded( testCaseStats ); + m_reporter->testCaseEnded(testCaseStats); } - void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) { - for ( auto const& listener : m_listeners ) { - listener->testGroupEnded( testGroupStats ); + void + ListeningReporter::testGroupEnded(TestGroupStats const& testGroupStats) { + for (auto const& listener : m_listeners) { + listener->testGroupEnded(testGroupStats); } - m_reporter->testGroupEnded( testGroupStats ); + m_reporter->testGroupEnded(testGroupStats); } - void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) { - for ( auto const& listener : m_listeners ) { - listener->testRunEnded( testRunStats ); + void ListeningReporter::testRunEnded(TestRunStats const& testRunStats) { + for (auto const& listener : m_listeners) { + listener->testRunEnded(testRunStats); } - m_reporter->testRunEnded( testRunStats ); + m_reporter->testRunEnded(testRunStats); } - void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) { - for ( auto const& listener : m_listeners ) { - listener->skipTest( testInfo ); + void ListeningReporter::skipTest(TestCaseInfo const& testInfo) { + for (auto const& listener : m_listeners) { + listener->skipTest(testInfo); } - m_reporter->skipTest( testInfo ); + m_reporter->skipTest(testInfo); } - bool ListeningReporter::isMulti() const { - return true; - } + bool ListeningReporter::isMulti() const { return true; } } // end namespace Catch // end catch_reporter_listening.cpp @@ -17232,16 +18936,14 @@ #if defined(_MSC_VER) #pragma warning(push) -#pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch - // Note that 4062 (not all labels are handled - // and default is missing) is enabled +#pragma warning(disable : 4061) // Not all labels are EXPLICITLY handled in + // switch Note that 4062 (not all labels are + // handled and default is missing) is enabled #endif namespace Catch { - XmlReporter::XmlReporter( ReporterConfig const& _config ) - : StreamingReporterBase( _config ), - m_xml(_config.stream()) - { + XmlReporter::XmlReporter(ReporterConfig const& _config) : + StreamingReporterBase(_config), m_xml(_config.stream()) { m_reporterPrefs.shouldRedirectStdOut = true; m_reporterPrefs.shouldReportAllAssertions = true; } @@ -17252,206 +18954,209 @@ return "Reports test results as an XML document"; } - std::string XmlReporter::getStylesheetRef() const { - return std::string(); + std::string XmlReporter::getStylesheetRef() const { return std::string(); } + + void XmlReporter::writeSourceInfo(SourceLineInfo const& sourceInfo) { + m_xml.writeAttribute("filename", sourceInfo.file) + .writeAttribute("line", sourceInfo.line); } - void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) { - m_xml - .writeAttribute( "filename", sourceInfo.file ) - .writeAttribute( "line", sourceInfo.line ); + void XmlReporter::noMatchingTestCases(std::string const& s) { + StreamingReporterBase::noMatchingTestCases(s); } - void XmlReporter::noMatchingTestCases( std::string const& s ) { - StreamingReporterBase::noMatchingTestCases( s ); - } - - void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) { - StreamingReporterBase::testRunStarting( testInfo ); + void XmlReporter::testRunStarting(TestRunInfo const& testInfo) { + StreamingReporterBase::testRunStarting(testInfo); std::string stylesheetRef = getStylesheetRef(); - if( !stylesheetRef.empty() ) - m_xml.writeStylesheetRef( stylesheetRef ); - m_xml.startElement( "Catch" ); - if( !m_config->name().empty() ) - m_xml.writeAttribute( "name", m_config->name() ); + if (!stylesheetRef.empty()) + m_xml.writeStylesheetRef(stylesheetRef); + m_xml.startElement("Catch"); + if (!m_config->name().empty()) + m_xml.writeAttribute("name", m_config->name()); if (m_config->testSpec().hasFilters()) - m_xml.writeAttribute( "filters", serializeFilters( m_config->getTestsOrTags() ) ); - if( m_config->rngSeed() != 0 ) - m_xml.scopedElement( "Randomness" ) - .writeAttribute( "seed", m_config->rngSeed() ); + m_xml.writeAttribute("filters", + serializeFilters(m_config->getTestsOrTags())); + if (m_config->rngSeed() != 0) + m_xml.scopedElement("Randomness") + .writeAttribute("seed", m_config->rngSeed()); } - void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) { - StreamingReporterBase::testGroupStarting( groupInfo ); - m_xml.startElement( "Group" ) - .writeAttribute( "name", groupInfo.name ); + void XmlReporter::testGroupStarting(GroupInfo const& groupInfo) { + StreamingReporterBase::testGroupStarting(groupInfo); + m_xml.startElement("Group").writeAttribute("name", groupInfo.name); } - void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) { + void XmlReporter::testCaseStarting(TestCaseInfo const& testInfo) { StreamingReporterBase::testCaseStarting(testInfo); - m_xml.startElement( "TestCase" ) - .writeAttribute( "name", trim( testInfo.name ) ) - .writeAttribute( "description", testInfo.description ) - .writeAttribute( "tags", testInfo.tagsAsString() ); + m_xml.startElement("TestCase") + .writeAttribute("name", trim(testInfo.name)) + .writeAttribute("description", testInfo.description) + .writeAttribute("tags", testInfo.tagsAsString()); - writeSourceInfo( testInfo.lineInfo ); + writeSourceInfo(testInfo.lineInfo); - if ( m_config->showDurations() == ShowDurations::Always ) + if (m_config->showDurations() == ShowDurations::Always) m_testCaseTimer.start(); m_xml.ensureTagClosed(); } - void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) { - StreamingReporterBase::sectionStarting( sectionInfo ); - if( m_sectionDepth++ > 0 ) { - m_xml.startElement( "Section" ) - .writeAttribute( "name", trim( sectionInfo.name ) ); - writeSourceInfo( sectionInfo.lineInfo ); + void XmlReporter::sectionStarting(SectionInfo const& sectionInfo) { + StreamingReporterBase::sectionStarting(sectionInfo); + if (m_sectionDepth++ > 0) { + m_xml.startElement("Section").writeAttribute( + "name", trim(sectionInfo.name)); + writeSourceInfo(sectionInfo.lineInfo); m_xml.ensureTagClosed(); } } - void XmlReporter::assertionStarting( AssertionInfo const& ) { } + void XmlReporter::assertionStarting(AssertionInfo const&) {} - bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) { + bool XmlReporter::assertionEnded(AssertionStats const& assertionStats) { AssertionResult const& result = assertionStats.assertionResult; - bool includeResults = m_config->includeSuccessfulResults() || !result.isOk(); + bool includeResults = + m_config->includeSuccessfulResults() || !result.isOk(); - if( includeResults || result.getResultType() == ResultWas::Warning ) { + if (includeResults || result.getResultType() == ResultWas::Warning) { // Print any info messages in <Info> tags. - for( auto const& msg : assertionStats.infoMessages ) { - if( msg.type == ResultWas::Info && includeResults ) { - m_xml.scopedElement( "Info" ) - .writeText( msg.message ); - } else if ( msg.type == ResultWas::Warning ) { - m_xml.scopedElement( "Warning" ) - .writeText( msg.message ); + for (auto const& msg : assertionStats.infoMessages) { + if (msg.type == ResultWas::Info && includeResults) { + m_xml.scopedElement("Info").writeText(msg.message); + } else if (msg.type == ResultWas::Warning) { + m_xml.scopedElement("Warning").writeText(msg.message); } } } // Drop out if result was successful but we're not printing them. - if( !includeResults && result.getResultType() != ResultWas::Warning ) + if (!includeResults && result.getResultType() != ResultWas::Warning) return true; // Print the expression if there is one. - if( result.hasExpression() ) { - m_xml.startElement( "Expression" ) - .writeAttribute( "success", result.succeeded() ) - .writeAttribute( "type", result.getTestMacroName() ); + if (result.hasExpression()) { + m_xml.startElement("Expression") + .writeAttribute("success", result.succeeded()) + .writeAttribute("type", result.getTestMacroName()); - writeSourceInfo( result.getSourceInfo() ); + writeSourceInfo(result.getSourceInfo()); - m_xml.scopedElement( "Original" ) - .writeText( result.getExpression() ); - m_xml.scopedElement( "Expanded" ) - .writeText( result.getExpandedExpression() ); + m_xml.scopedElement("Original").writeText(result.getExpression()); + m_xml.scopedElement("Expanded") + .writeText(result.getExpandedExpression()); } // And... Print a result applicable to each result type. - switch( result.getResultType() ) { + switch (result.getResultType()) { case ResultWas::ThrewException: - m_xml.startElement( "Exception" ); - writeSourceInfo( result.getSourceInfo() ); - m_xml.writeText( result.getMessage() ); + m_xml.startElement("Exception"); + writeSourceInfo(result.getSourceInfo()); + m_xml.writeText(result.getMessage()); m_xml.endElement(); break; case ResultWas::FatalErrorCondition: - m_xml.startElement( "FatalErrorCondition" ); - writeSourceInfo( result.getSourceInfo() ); - m_xml.writeText( result.getMessage() ); + m_xml.startElement("FatalErrorCondition"); + writeSourceInfo(result.getSourceInfo()); + m_xml.writeText(result.getMessage()); m_xml.endElement(); break; case ResultWas::Info: - m_xml.scopedElement( "Info" ) - .writeText( result.getMessage() ); + m_xml.scopedElement("Info").writeText(result.getMessage()); break; case ResultWas::Warning: // Warning will already have been written break; case ResultWas::ExplicitFailure: - m_xml.startElement( "Failure" ); - writeSourceInfo( result.getSourceInfo() ); - m_xml.writeText( result.getMessage() ); + m_xml.startElement("Failure"); + writeSourceInfo(result.getSourceInfo()); + m_xml.writeText(result.getMessage()); m_xml.endElement(); break; default: break; } - if( result.hasExpression() ) + if (result.hasExpression()) m_xml.endElement(); return true; } - void XmlReporter::sectionEnded( SectionStats const& sectionStats ) { - StreamingReporterBase::sectionEnded( sectionStats ); - if( --m_sectionDepth > 0 ) { - XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" ); - e.writeAttribute( "successes", sectionStats.assertions.passed ); - e.writeAttribute( "failures", sectionStats.assertions.failed ); - e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk ); + void XmlReporter::sectionEnded(SectionStats const& sectionStats) { + StreamingReporterBase::sectionEnded(sectionStats); + if (--m_sectionDepth > 0) { + XmlWriter::ScopedElement e = m_xml.scopedElement("OverallResults"); + e.writeAttribute("successes", sectionStats.assertions.passed); + e.writeAttribute("failures", sectionStats.assertions.failed); + e.writeAttribute("expectedFailures", + sectionStats.assertions.failedButOk); - if ( m_config->showDurations() == ShowDurations::Always ) - e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds ); + if (m_config->showDurations() == ShowDurations::Always) + e.writeAttribute("durationInSeconds", + sectionStats.durationInSeconds); m_xml.endElement(); } } - void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) { - StreamingReporterBase::testCaseEnded( testCaseStats ); - XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" ); - e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() ); + void XmlReporter::testCaseEnded(TestCaseStats const& testCaseStats) { + StreamingReporterBase::testCaseEnded(testCaseStats); + XmlWriter::ScopedElement e = m_xml.scopedElement("OverallResult"); + e.writeAttribute("success", testCaseStats.totals.assertions.allOk()); - if ( m_config->showDurations() == ShowDurations::Always ) - e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() ); + if (m_config->showDurations() == ShowDurations::Always) + e.writeAttribute("durationInSeconds", + m_testCaseTimer.getElapsedSeconds()); - if( !testCaseStats.stdOut.empty() ) - m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), XmlFormatting::Newline ); - if( !testCaseStats.stdErr.empty() ) - m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), XmlFormatting::Newline ); + if (!testCaseStats.stdOut.empty()) + m_xml.scopedElement("StdOut").writeText(trim(testCaseStats.stdOut), + XmlFormatting::Newline); + if (!testCaseStats.stdErr.empty()) + m_xml.scopedElement("StdErr").writeText(trim(testCaseStats.stdErr), + XmlFormatting::Newline); m_xml.endElement(); } - void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) { - StreamingReporterBase::testGroupEnded( testGroupStats ); + void XmlReporter::testGroupEnded(TestGroupStats const& testGroupStats) { + StreamingReporterBase::testGroupEnded(testGroupStats); // TODO: Check testGroupStats.aborting and act accordingly. - m_xml.scopedElement( "OverallResults" ) - .writeAttribute( "successes", testGroupStats.totals.assertions.passed ) - .writeAttribute( "failures", testGroupStats.totals.assertions.failed ) - .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk ); - m_xml.scopedElement( "OverallResultsCases") - .writeAttribute( "successes", testGroupStats.totals.testCases.passed ) - .writeAttribute( "failures", testGroupStats.totals.testCases.failed ) - .writeAttribute( "expectedFailures", testGroupStats.totals.testCases.failedButOk ); + m_xml.scopedElement("OverallResults") + .writeAttribute("successes", + testGroupStats.totals.assertions.passed) + .writeAttribute("failures", testGroupStats.totals.assertions.failed) + .writeAttribute("expectedFailures", + testGroupStats.totals.assertions.failedButOk); + m_xml.scopedElement("OverallResultsCases") + .writeAttribute("successes", testGroupStats.totals.testCases.passed) + .writeAttribute("failures", testGroupStats.totals.testCases.failed) + .writeAttribute("expectedFailures", + testGroupStats.totals.testCases.failedButOk); m_xml.endElement(); } - void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) { - StreamingReporterBase::testRunEnded( testRunStats ); - m_xml.scopedElement( "OverallResults" ) - .writeAttribute( "successes", testRunStats.totals.assertions.passed ) - .writeAttribute( "failures", testRunStats.totals.assertions.failed ) - .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk ); - m_xml.scopedElement( "OverallResultsCases") - .writeAttribute( "successes", testRunStats.totals.testCases.passed ) - .writeAttribute( "failures", testRunStats.totals.testCases.failed ) - .writeAttribute( "expectedFailures", testRunStats.totals.testCases.failedButOk ); + void XmlReporter::testRunEnded(TestRunStats const& testRunStats) { + StreamingReporterBase::testRunEnded(testRunStats); + m_xml.scopedElement("OverallResults") + .writeAttribute("successes", testRunStats.totals.assertions.passed) + .writeAttribute("failures", testRunStats.totals.assertions.failed) + .writeAttribute("expectedFailures", + testRunStats.totals.assertions.failedButOk); + m_xml.scopedElement("OverallResultsCases") + .writeAttribute("successes", testRunStats.totals.testCases.passed) + .writeAttribute("failures", testRunStats.totals.testCases.failed) + .writeAttribute("expectedFailures", + testRunStats.totals.testCases.failedButOk); m_xml.endElement(); } #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) void XmlReporter::benchmarkPreparing(std::string const& name) { - m_xml.startElement("BenchmarkResults") - .writeAttribute("name", name); + m_xml.startElement("BenchmarkResults").writeAttribute("name", name); } - void XmlReporter::benchmarkStarting(BenchmarkInfo const &info) { + void XmlReporter::benchmarkStarting(BenchmarkInfo const& info) { m_xml.writeAttribute("samples", info.samples) .writeAttribute("resamples", info.resamples) .writeAttribute("iterations", info.iterations) @@ -17463,15 +19168,23 @@ void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) { m_xml.startElement("mean") .writeAttribute("value", benchmarkStats.mean.point.count()) - .writeAttribute("lowerBound", benchmarkStats.mean.lower_bound.count()) - .writeAttribute("upperBound", benchmarkStats.mean.upper_bound.count()) + .writeAttribute("lowerBound", + benchmarkStats.mean.lower_bound.count()) + .writeAttribute("upperBound", + benchmarkStats.mean.upper_bound.count()) .writeAttribute("ci", benchmarkStats.mean.confidence_interval); m_xml.endElement(); m_xml.startElement("standardDeviation") - .writeAttribute("value", benchmarkStats.standardDeviation.point.count()) - .writeAttribute("lowerBound", benchmarkStats.standardDeviation.lower_bound.count()) - .writeAttribute("upperBound", benchmarkStats.standardDeviation.upper_bound.count()) - .writeAttribute("ci", benchmarkStats.standardDeviation.confidence_interval); + .writeAttribute("value", + benchmarkStats.standardDeviation.point.count()) + .writeAttribute( + "lowerBound", + benchmarkStats.standardDeviation.lower_bound.count()) + .writeAttribute( + "upperBound", + benchmarkStats.standardDeviation.upper_bound.count()) + .writeAttribute( + "ci", benchmarkStats.standardDeviation.confidence_interval); m_xml.endElement(); m_xml.startElement("outliers") .writeAttribute("variance", benchmarkStats.outlierVariance) @@ -17483,14 +19196,13 @@ m_xml.endElement(); } - void XmlReporter::benchmarkFailed(std::string const &error) { - m_xml.scopedElement("failed"). - writeAttribute("message", error); + void XmlReporter::benchmarkFailed(std::string const& error) { + m_xml.scopedElement("failed").writeAttribute("message", error); m_xml.endElement(); } #endif // CATCH_CONFIG_ENABLE_BENCHMARKING - CATCH_REGISTER_REPORTER( "xml", XmlReporter ) + CATCH_REGISTER_REPORTER("xml", XmlReporter) } // end namespace Catch @@ -17515,27 +19227,28 @@ #ifndef __OBJC__ -#if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN) +#if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && \ + defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN) // Standard C/C++ Win32 Unicode wmain entry point -extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) { +extern "C" int wmain(int argc, wchar_t* argv[], wchar_t*[]) { #else // Standard C/C++ main entry point -int main (int argc, char * argv[]) { +int main(int argc, char* argv[]) { #endif - return Catch::Session().run( argc, argv ); + return Catch::Session().run(argc, argv); } #else // __OBJC__ // Objective-C entry point -int main (int argc, char * const argv[]) { +int main(int argc, char* const argv[]) { #if !CATCH_ARC_ENABLED - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; #endif Catch::registerTestMethods(); - int result = Catch::Session().run( argc, (char**)argv ); + int result = Catch::Session().run(argc, (char**)argv); #if !CATCH_ARC_ENABLED [pool drain]; @@ -17552,209 +19265,463 @@ #if !defined(CATCH_CONFIG_IMPL_ONLY) #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED -# undef CLARA_CONFIG_MAIN +#undef CLARA_CONFIG_MAIN #endif #if !defined(CATCH_CONFIG_DISABLE) ////// -// If this config identifier is defined then all CATCH macros are prefixed with CATCH_ +// If this config identifier is defined then all CATCH macros are prefixed with +// CATCH_ #ifdef CATCH_CONFIG_PREFIX_ALL -#define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ ) -#define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) +#define CATCH_REQUIRE(...) \ + INTERNAL_CATCH_TEST( \ + "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__) +#define CATCH_REQUIRE_FALSE(...) \ + INTERNAL_CATCH_TEST("CATCH_REQUIRE_FALSE", \ + Catch::ResultDisposition::Normal | \ + Catch::ResultDisposition::FalseTest, \ + __VA_ARGS__) -#define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ ) -#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr ) -#define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) +#define CATCH_REQUIRE_THROWS(...) \ + INTERNAL_CATCH_THROWS( \ + "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__) +#define CATCH_REQUIRE_THROWS_AS(expr, exceptionType) \ + INTERNAL_CATCH_THROWS_AS("CATCH_REQUIRE_THROWS_AS", \ + exceptionType, \ + Catch::ResultDisposition::Normal, \ + expr) +#define CATCH_REQUIRE_THROWS_WITH(expr, matcher) \ + INTERNAL_CATCH_THROWS_STR_MATCHES("CATCH_REQUIRE_THROWS_WITH", \ + Catch::ResultDisposition::Normal, \ + matcher, \ + expr) #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) -#define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr ) -#endif// CATCH_CONFIG_DISABLE_MATCHERS -#define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ ) - -#define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) -#define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) -#define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) -#define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) -#define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ ) - -#define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) -#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr ) -#define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) -#if !defined(CATCH_CONFIG_DISABLE_MATCHERS) -#define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) +#define CATCH_REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) \ + INTERNAL_CATCH_THROWS_MATCHES("CATCH_REQUIRE_THROWS_MATCHES", \ + exceptionType, \ + Catch::ResultDisposition::Normal, \ + matcher, \ + expr) #endif // CATCH_CONFIG_DISABLE_MATCHERS -#define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) +#define CATCH_REQUIRE_NOTHROW(...) \ + INTERNAL_CATCH_NO_THROW("CATCH_REQUIRE_NOTHROW", \ + Catch::ResultDisposition::Normal, \ + __VA_ARGS__) + +#define CATCH_CHECK(...) \ + INTERNAL_CATCH_TEST("CATCH_CHECK", \ + Catch::ResultDisposition::ContinueOnFailure, \ + __VA_ARGS__) +#define CATCH_CHECK_FALSE(...) \ + INTERNAL_CATCH_TEST("CATCH_CHECK_FALSE", \ + Catch::ResultDisposition::ContinueOnFailure | \ + Catch::ResultDisposition::FalseTest, \ + __VA_ARGS__) +#define CATCH_CHECKED_IF(...) \ + INTERNAL_CATCH_IF("CATCH_CHECKED_IF", \ + Catch::ResultDisposition::ContinueOnFailure, \ + __VA_ARGS__) +#define CATCH_CHECKED_ELSE(...) \ + INTERNAL_CATCH_ELSE("CATCH_CHECKED_ELSE", \ + Catch::ResultDisposition::ContinueOnFailure, \ + __VA_ARGS__) +#define CATCH_CHECK_NOFAIL(...) \ + INTERNAL_CATCH_TEST("CATCH_CHECK_NOFAIL", \ + Catch::ResultDisposition::ContinueOnFailure | \ + Catch::ResultDisposition::SuppressFail, \ + __VA_ARGS__) + +#define CATCH_CHECK_THROWS(...) \ + INTERNAL_CATCH_THROWS("CATCH_CHECK_THROWS", \ + Catch::ResultDisposition::ContinueOnFailure, \ + __VA_ARGS__) +#define CATCH_CHECK_THROWS_AS(expr, exceptionType) \ + INTERNAL_CATCH_THROWS_AS("CATCH_CHECK_THROWS_AS", \ + exceptionType, \ + Catch::ResultDisposition::ContinueOnFailure, \ + expr) +#define CATCH_CHECK_THROWS_WITH(expr, matcher) \ + INTERNAL_CATCH_THROWS_STR_MATCHES( \ + "CATCH_CHECK_THROWS_WITH", \ + Catch::ResultDisposition::ContinueOnFailure, \ + matcher, \ + expr) +#if !defined(CATCH_CONFIG_DISABLE_MATCHERS) +#define CATCH_CHECK_THROWS_MATCHES(expr, exceptionType, matcher) \ + INTERNAL_CATCH_THROWS_MATCHES("CATCH_CHECK_THROWS_MATCHES", \ + exceptionType, \ + Catch::ResultDisposition::ContinueOnFailure, \ + matcher, \ + expr) +#endif // CATCH_CONFIG_DISABLE_MATCHERS +#define CATCH_CHECK_NOTHROW(...) \ + INTERNAL_CATCH_NO_THROW("CATCH_CHECK_NOTHROW", \ + Catch::ResultDisposition::ContinueOnFailure, \ + __VA_ARGS__) #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) -#define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg ) +#define CATCH_CHECK_THAT(arg, matcher) \ + INTERNAL_CHECK_THAT("CATCH_CHECK_THAT", \ + matcher, \ + Catch::ResultDisposition::ContinueOnFailure, \ + arg) -#define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) +#define CATCH_REQUIRE_THAT(arg, matcher) \ + INTERNAL_CHECK_THAT( \ + "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg) #endif // CATCH_CONFIG_DISABLE_MATCHERS -#define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg ) -#define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg ) -#define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg ) -#define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ ) +#define CATCH_INFO(msg) INTERNAL_CATCH_INFO("CATCH_INFO", msg) +#define CATCH_UNSCOPED_INFO(msg) \ + INTERNAL_CATCH_UNSCOPED_INFO("CATCH_UNSCOPED_INFO", msg) +#define CATCH_WARN(msg) \ + INTERNAL_CATCH_MSG("CATCH_WARN", \ + Catch::ResultWas::Warning, \ + Catch::ResultDisposition::ContinueOnFailure, \ + msg) +#define CATCH_CAPTURE(...) \ + INTERNAL_CATCH_CAPTURE( \ + INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE", __VA_ARGS__) -#define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) -#define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) -#define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) -#define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) -#define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) -#define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ ) -#define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ ) -#define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) -#define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) +#define CATCH_TEST_CASE(...) INTERNAL_CATCH_TESTCASE(__VA_ARGS__) +#define CATCH_TEST_CASE_METHOD(className, ...) \ + INTERNAL_CATCH_TEST_CASE_METHOD(className, __VA_ARGS__) +#define CATCH_METHOD_AS_TEST_CASE(method, ...) \ + INTERNAL_CATCH_METHOD_AS_TEST_CASE(method, __VA_ARGS__) +#define CATCH_REGISTER_TEST_CASE(Function, ...) \ + INTERNAL_CATCH_REGISTER_TESTCASE(Function, __VA_ARGS__) +#define CATCH_SECTION(...) INTERNAL_CATCH_SECTION(__VA_ARGS__) +#define CATCH_DYNAMIC_SECTION(...) INTERNAL_CATCH_DYNAMIC_SECTION(__VA_ARGS__) +#define CATCH_FAIL(...) \ + INTERNAL_CATCH_MSG("CATCH_FAIL", \ + Catch::ResultWas::ExplicitFailure, \ + Catch::ResultDisposition::Normal, \ + __VA_ARGS__) +#define CATCH_FAIL_CHECK(...) \ + INTERNAL_CATCH_MSG("CATCH_FAIL_CHECK", \ + Catch::ResultWas::ExplicitFailure, \ + Catch::ResultDisposition::ContinueOnFailure, \ + __VA_ARGS__) +#define CATCH_SUCCEED(...) \ + INTERNAL_CATCH_MSG("CATCH_SUCCEED", \ + Catch::ResultWas::Ok, \ + Catch::ResultDisposition::ContinueOnFailure, \ + __VA_ARGS__) #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE() #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR -#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) -#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) -#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) -#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) -#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) -#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) -#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) -#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) +#define CATCH_TEMPLATE_TEST_CASE(...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__) +#define CATCH_TEMPLATE_TEST_CASE_SIG(...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__) +#define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__) +#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...) \ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...) \ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, __VA_ARGS__) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, __VA_ARGS__) #else -#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) ) -#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) ) -#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) -#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) -#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) ) -#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) ) -#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) -#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) +#define CATCH_TEMPLATE_TEST_CASE(...) \ + INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)) +#define CATCH_TEMPLATE_TEST_CASE_SIG(...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__)) +#define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)) +#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__)) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__)) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__)) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, \ + __VA_ARGS__)) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, \ + __VA_ARGS__)) #endif #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE) -#define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ ) -#define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ ) +#define CATCH_STATIC_REQUIRE(...) \ + static_assert(__VA_ARGS__, #__VA_ARGS__); \ + CATCH_SUCCEED(#__VA_ARGS__) +#define CATCH_STATIC_REQUIRE_FALSE(...) \ + static_assert(!(__VA_ARGS__), "!(" #__VA_ARGS__ ")"); \ + CATCH_SUCCEED(#__VA_ARGS__) #else -#define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ ) -#define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ ) +#define CATCH_STATIC_REQUIRE(...) CATCH_REQUIRE(__VA_ARGS__) +#define CATCH_STATIC_REQUIRE_FALSE(...) CATCH_REQUIRE_FALSE(__VA_ARGS__) #endif // "BDD-style" convenience wrappers -#define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ ) -#define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) -#define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc ) -#define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc ) -#define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc ) -#define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc ) -#define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc ) -#define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc ) +#define CATCH_SCENARIO(...) CATCH_TEST_CASE("Scenario: " __VA_ARGS__) +#define CATCH_SCENARIO_METHOD(className, ...) \ + INTERNAL_CATCH_TEST_CASE_METHOD(className, "Scenario: " __VA_ARGS__) +#define CATCH_GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" Given: " << desc) +#define CATCH_AND_GIVEN(desc) \ + INTERNAL_CATCH_DYNAMIC_SECTION("And given: " << desc) +#define CATCH_WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" When: " << desc) +#define CATCH_AND_WHEN(desc) \ + INTERNAL_CATCH_DYNAMIC_SECTION(" And when: " << desc) +#define CATCH_THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" Then: " << desc) +#define CATCH_AND_THEN(desc) \ + INTERNAL_CATCH_DYNAMIC_SECTION(" And: " << desc) #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) -#define CATCH_BENCHMARK(...) \ - INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,)) -#define CATCH_BENCHMARK_ADVANCED(name) \ - INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name) +#define CATCH_BENCHMARK(...) \ + INTERNAL_CATCH_BENCHMARK( \ + INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), \ + INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__, , ), \ + INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__, , )) +#define CATCH_BENCHMARK_ADVANCED(name) \ + INTERNAL_CATCH_BENCHMARK_ADVANCED( \ + INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name) #endif // CATCH_CONFIG_ENABLE_BENCHMARKING -// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required +// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not +// required #else -#define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ ) -#define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) +#define REQUIRE(...) \ + INTERNAL_CATCH_TEST( \ + "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__) +#define REQUIRE_FALSE(...) \ + INTERNAL_CATCH_TEST("REQUIRE_FALSE", \ + Catch::ResultDisposition::Normal | \ + Catch::ResultDisposition::FalseTest, \ + __VA_ARGS__) -#define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ ) -#define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr ) -#define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) +#define REQUIRE_THROWS(...) \ + INTERNAL_CATCH_THROWS( \ + "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__) +#define REQUIRE_THROWS_AS(expr, exceptionType) \ + INTERNAL_CATCH_THROWS_AS("REQUIRE_THROWS_AS", \ + exceptionType, \ + Catch::ResultDisposition::Normal, \ + expr) +#define REQUIRE_THROWS_WITH(expr, matcher) \ + INTERNAL_CATCH_THROWS_STR_MATCHES("REQUIRE_THROWS_WITH", \ + Catch::ResultDisposition::Normal, \ + matcher, \ + expr) #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) -#define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr ) +#define REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) \ + INTERNAL_CATCH_THROWS_MATCHES("REQUIRE_THROWS_MATCHES", \ + exceptionType, \ + Catch::ResultDisposition::Normal, \ + matcher, \ + expr) #endif // CATCH_CONFIG_DISABLE_MATCHERS -#define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ ) +#define REQUIRE_NOTHROW(...) \ + INTERNAL_CATCH_NO_THROW( \ + "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__) -#define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) -#define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) -#define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) -#define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) -#define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ ) +#define CHECK(...) \ + INTERNAL_CATCH_TEST( \ + "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__) +#define CHECK_FALSE(...) \ + INTERNAL_CATCH_TEST("CHECK_FALSE", \ + Catch::ResultDisposition::ContinueOnFailure | \ + Catch::ResultDisposition::FalseTest, \ + __VA_ARGS__) +#define CHECKED_IF(...) \ + INTERNAL_CATCH_IF("CHECKED_IF", \ + Catch::ResultDisposition::ContinueOnFailure, \ + __VA_ARGS__) +#define CHECKED_ELSE(...) \ + INTERNAL_CATCH_ELSE("CHECKED_ELSE", \ + Catch::ResultDisposition::ContinueOnFailure, \ + __VA_ARGS__) +#define CHECK_NOFAIL(...) \ + INTERNAL_CATCH_TEST("CHECK_NOFAIL", \ + Catch::ResultDisposition::ContinueOnFailure | \ + Catch::ResultDisposition::SuppressFail, \ + __VA_ARGS__) -#define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) -#define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr ) -#define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) +#define CHECK_THROWS(...) \ + INTERNAL_CATCH_THROWS("CHECK_THROWS", \ + Catch::ResultDisposition::ContinueOnFailure, \ + __VA_ARGS__) +#define CHECK_THROWS_AS(expr, exceptionType) \ + INTERNAL_CATCH_THROWS_AS("CHECK_THROWS_AS", \ + exceptionType, \ + Catch::ResultDisposition::ContinueOnFailure, \ + expr) +#define CHECK_THROWS_WITH(expr, matcher) \ + INTERNAL_CATCH_THROWS_STR_MATCHES( \ + "CHECK_THROWS_WITH", \ + Catch::ResultDisposition::ContinueOnFailure, \ + matcher, \ + expr) #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) -#define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) +#define CHECK_THROWS_MATCHES(expr, exceptionType, matcher) \ + INTERNAL_CATCH_THROWS_MATCHES("CHECK_THROWS_MATCHES", \ + exceptionType, \ + Catch::ResultDisposition::ContinueOnFailure, \ + matcher, \ + expr) #endif // CATCH_CONFIG_DISABLE_MATCHERS -#define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) +#define CHECK_NOTHROW(...) \ + INTERNAL_CATCH_NO_THROW("CHECK_NOTHROW", \ + Catch::ResultDisposition::ContinueOnFailure, \ + __VA_ARGS__) #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) -#define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg ) +#define CHECK_THAT(arg, matcher) \ + INTERNAL_CHECK_THAT("CHECK_THAT", \ + matcher, \ + Catch::ResultDisposition::ContinueOnFailure, \ + arg) -#define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) +#define REQUIRE_THAT(arg, matcher) \ + INTERNAL_CHECK_THAT( \ + "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg) #endif // CATCH_CONFIG_DISABLE_MATCHERS -#define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg ) -#define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg ) -#define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg ) -#define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ ) +#define INFO(msg) INTERNAL_CATCH_INFO("INFO", msg) +#define UNSCOPED_INFO(msg) INTERNAL_CATCH_UNSCOPED_INFO("UNSCOPED_INFO", msg) +#define WARN(msg) \ + INTERNAL_CATCH_MSG("WARN", \ + Catch::ResultWas::Warning, \ + Catch::ResultDisposition::ContinueOnFailure, \ + msg) +#define CAPTURE(...) \ + INTERNAL_CATCH_CAPTURE( \ + INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE", __VA_ARGS__) -#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) -#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) -#define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) -#define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) -#define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) -#define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ ) -#define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ ) -#define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) -#define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) +#define TEST_CASE(...) INTERNAL_CATCH_TESTCASE(__VA_ARGS__) +#define TEST_CASE_METHOD(className, ...) \ + INTERNAL_CATCH_TEST_CASE_METHOD(className, __VA_ARGS__) +#define METHOD_AS_TEST_CASE(method, ...) \ + INTERNAL_CATCH_METHOD_AS_TEST_CASE(method, __VA_ARGS__) +#define REGISTER_TEST_CASE(Function, ...) \ + INTERNAL_CATCH_REGISTER_TESTCASE(Function, __VA_ARGS__) +#define SECTION(...) INTERNAL_CATCH_SECTION(__VA_ARGS__) +#define DYNAMIC_SECTION(...) INTERNAL_CATCH_DYNAMIC_SECTION(__VA_ARGS__) +#define FAIL(...) \ + INTERNAL_CATCH_MSG("FAIL", \ + Catch::ResultWas::ExplicitFailure, \ + Catch::ResultDisposition::Normal, \ + __VA_ARGS__) +#define FAIL_CHECK(...) \ + INTERNAL_CATCH_MSG("FAIL_CHECK", \ + Catch::ResultWas::ExplicitFailure, \ + Catch::ResultDisposition::ContinueOnFailure, \ + __VA_ARGS__) +#define SUCCEED(...) \ + INTERNAL_CATCH_MSG("SUCCEED", \ + Catch::ResultWas::Ok, \ + Catch::ResultDisposition::ContinueOnFailure, \ + __VA_ARGS__) #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE() #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR -#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) -#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) -#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) -#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) -#define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) -#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) -#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) -#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) -#define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__) -#define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) +#define TEMPLATE_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__) +#define TEMPLATE_TEST_CASE_SIG(...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__) +#define TEMPLATE_TEST_CASE_METHOD(className, ...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__) +#define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__) +#define TEMPLATE_PRODUCT_TEST_CASE(...) \ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__) +#define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) \ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__) +#define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, __VA_ARGS__) +#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, __VA_ARGS__) +#define TEMPLATE_LIST_TEST_CASE(...) \ + INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__) +#define TEMPLATE_LIST_TEST_CASE_METHOD(className, ...) \ + INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(className, __VA_ARGS__) #else -#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) ) -#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) ) -#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) -#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) -#define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) ) -#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) ) -#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) -#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) -#define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) ) -#define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) +#define TEMPLATE_TEST_CASE(...) \ + INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)) +#define TEMPLATE_TEST_CASE_SIG(...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__)) +#define TEMPLATE_TEST_CASE_METHOD(className, ...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)) +#define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__)) +#define TEMPLATE_PRODUCT_TEST_CASE(...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__)) +#define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__)) +#define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, \ + __VA_ARGS__)) +#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, \ + __VA_ARGS__)) +#define TEMPLATE_LIST_TEST_CASE(...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)) +#define TEMPLATE_LIST_TEST_CASE_METHOD(className, ...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(className, __VA_ARGS__)) #endif #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE) -#define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ ) -#define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" ) +#define STATIC_REQUIRE(...) \ + static_assert(__VA_ARGS__, #__VA_ARGS__); \ + SUCCEED(#__VA_ARGS__) +#define STATIC_REQUIRE_FALSE(...) \ + static_assert(!(__VA_ARGS__), "!(" #__VA_ARGS__ ")"); \ + SUCCEED("!(" #__VA_ARGS__ ")") #else -#define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ ) -#define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ ) +#define STATIC_REQUIRE(...) REQUIRE(__VA_ARGS__) +#define STATIC_REQUIRE_FALSE(...) REQUIRE_FALSE(__VA_ARGS__) #endif #endif -#define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) +#define CATCH_TRANSLATE_EXCEPTION(signature) \ + INTERNAL_CATCH_TRANSLATE_EXCEPTION(signature) // "BDD-style" convenience wrappers -#define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ ) -#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) +#define SCENARIO(...) TEST_CASE("Scenario: " __VA_ARGS__) +#define SCENARIO_METHOD(className, ...) \ + INTERNAL_CATCH_TEST_CASE_METHOD(className, "Scenario: " __VA_ARGS__) -#define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc ) -#define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc ) -#define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc ) -#define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc ) -#define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc ) -#define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc ) +#define GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" Given: " << desc) +#define AND_GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION("And given: " << desc) +#define WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" When: " << desc) +#define AND_WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" And when: " << desc) +#define THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" Then: " << desc) +#define AND_THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" And: " << desc) #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) -#define BENCHMARK(...) \ - INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,)) -#define BENCHMARK_ADVANCED(name) \ - INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name) +#define BENCHMARK(...) \ + INTERNAL_CATCH_BENCHMARK( \ + INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), \ + INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__, , ), \ + INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__, , )) +#define BENCHMARK_ADVANCED(name) \ + INTERNAL_CATCH_BENCHMARK_ADVANCED( \ + INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name) #endif // CATCH_CONFIG_ENABLE_BENCHMARKING using Catch::Detail::Approx; @@ -17762,177 +19729,246 @@ #else // CATCH_CONFIG_DISABLE ////// -// If this config identifier is defined then all CATCH macros are prefixed with CATCH_ +// If this config identifier is defined then all CATCH macros are prefixed with +// CATCH_ #ifdef CATCH_CONFIG_PREFIX_ALL -#define CATCH_REQUIRE( ... ) (void)(0) -#define CATCH_REQUIRE_FALSE( ... ) (void)(0) +#define CATCH_REQUIRE(...) (void)(0) +#define CATCH_REQUIRE_FALSE(...) (void)(0) -#define CATCH_REQUIRE_THROWS( ... ) (void)(0) -#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0) -#define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0) +#define CATCH_REQUIRE_THROWS(...) (void)(0) +#define CATCH_REQUIRE_THROWS_AS(expr, exceptionType) (void)(0) +#define CATCH_REQUIRE_THROWS_WITH(expr, matcher) (void)(0) #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) -#define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) -#endif// CATCH_CONFIG_DISABLE_MATCHERS -#define CATCH_REQUIRE_NOTHROW( ... ) (void)(0) - -#define CATCH_CHECK( ... ) (void)(0) -#define CATCH_CHECK_FALSE( ... ) (void)(0) -#define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__) -#define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__)) -#define CATCH_CHECK_NOFAIL( ... ) (void)(0) - -#define CATCH_CHECK_THROWS( ... ) (void)(0) -#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0) -#define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0) -#if !defined(CATCH_CONFIG_DISABLE_MATCHERS) -#define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) +#define CATCH_REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0) #endif // CATCH_CONFIG_DISABLE_MATCHERS -#define CATCH_CHECK_NOTHROW( ... ) (void)(0) +#define CATCH_REQUIRE_NOTHROW(...) (void)(0) + +#define CATCH_CHECK(...) (void)(0) +#define CATCH_CHECK_FALSE(...) (void)(0) +#define CATCH_CHECKED_IF(...) if (__VA_ARGS__) +#define CATCH_CHECKED_ELSE(...) if (!(__VA_ARGS__)) +#define CATCH_CHECK_NOFAIL(...) (void)(0) + +#define CATCH_CHECK_THROWS(...) (void)(0) +#define CATCH_CHECK_THROWS_AS(expr, exceptionType) (void)(0) +#define CATCH_CHECK_THROWS_WITH(expr, matcher) (void)(0) +#if !defined(CATCH_CONFIG_DISABLE_MATCHERS) +#define CATCH_CHECK_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0) +#endif // CATCH_CONFIG_DISABLE_MATCHERS +#define CATCH_CHECK_NOTHROW(...) (void)(0) #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) -#define CATCH_CHECK_THAT( arg, matcher ) (void)(0) +#define CATCH_CHECK_THAT(arg, matcher) (void)(0) -#define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0) +#define CATCH_REQUIRE_THAT(arg, matcher) (void)(0) #endif // CATCH_CONFIG_DISABLE_MATCHERS -#define CATCH_INFO( msg ) (void)(0) -#define CATCH_UNSCOPED_INFO( msg ) (void)(0) -#define CATCH_WARN( msg ) (void)(0) -#define CATCH_CAPTURE( msg ) (void)(0) +#define CATCH_INFO(msg) (void)(0) +#define CATCH_UNSCOPED_INFO(msg) (void)(0) +#define CATCH_WARN(msg) (void)(0) +#define CATCH_CAPTURE(msg) (void)(0) -#define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) -#define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) -#define CATCH_METHOD_AS_TEST_CASE( method, ... ) -#define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0) -#define CATCH_SECTION( ... ) -#define CATCH_DYNAMIC_SECTION( ... ) -#define CATCH_FAIL( ... ) (void)(0) -#define CATCH_FAIL_CHECK( ... ) (void)(0) -#define CATCH_SUCCEED( ... ) (void)(0) +#define CATCH_TEST_CASE(...) \ + INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \ + INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____)) +#define CATCH_TEST_CASE_METHOD(className, ...) \ + INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \ + INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____)) +#define CATCH_METHOD_AS_TEST_CASE(method, ...) +#define CATCH_REGISTER_TEST_CASE(Function, ...) (void)(0) +#define CATCH_SECTION(...) +#define CATCH_DYNAMIC_SECTION(...) +#define CATCH_FAIL(...) (void)(0) +#define CATCH_FAIL_CHECK(...) (void)(0) +#define CATCH_SUCCEED(...) (void)(0) -#define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) +#define CATCH_ANON_TEST_CASE() \ + INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \ + INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____)) #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR -#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) -#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) -#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__) -#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) -#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) -#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) -#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) -#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) +#define CATCH_TEMPLATE_TEST_CASE(...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) +#define CATCH_TEMPLATE_TEST_CASE_SIG(...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) +#define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, \ + __VA_ARGS__) +#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, \ + __VA_ARGS__) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...) \ + CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...) \ + CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \ + CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \ + CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__) #else -#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) ) -#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) ) -#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) ) -#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) ) -#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) -#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) -#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) -#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) +#define CATCH_TEMPLATE_TEST_CASE(...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)) +#define CATCH_TEMPLATE_TEST_CASE_SIG(...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)) +#define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, \ + __VA_ARGS__)) +#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( \ + className, __VA_ARGS__)) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...) \ + CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...) \ + CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \ + CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \ + CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__) #endif // "BDD-style" convenience wrappers -#define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) -#define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className ) -#define CATCH_GIVEN( desc ) -#define CATCH_AND_GIVEN( desc ) -#define CATCH_WHEN( desc ) -#define CATCH_AND_WHEN( desc ) -#define CATCH_THEN( desc ) -#define CATCH_AND_THEN( desc ) +#define CATCH_SCENARIO(...) \ + INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \ + INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____)) +#define CATCH_SCENARIO_METHOD(className, ...) \ + INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( \ + INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____), className) +#define CATCH_GIVEN(desc) +#define CATCH_AND_GIVEN(desc) +#define CATCH_WHEN(desc) +#define CATCH_AND_WHEN(desc) +#define CATCH_THEN(desc) +#define CATCH_AND_THEN(desc) -#define CATCH_STATIC_REQUIRE( ... ) (void)(0) -#define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0) +#define CATCH_STATIC_REQUIRE(...) (void)(0) +#define CATCH_STATIC_REQUIRE_FALSE(...) (void)(0) -// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required +// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not +// required #else -#define REQUIRE( ... ) (void)(0) -#define REQUIRE_FALSE( ... ) (void)(0) +#define REQUIRE(...) (void)(0) +#define REQUIRE_FALSE(...) (void)(0) -#define REQUIRE_THROWS( ... ) (void)(0) -#define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0) -#define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0) +#define REQUIRE_THROWS(...) (void)(0) +#define REQUIRE_THROWS_AS(expr, exceptionType) (void)(0) +#define REQUIRE_THROWS_WITH(expr, matcher) (void)(0) #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) -#define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) +#define REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0) #endif // CATCH_CONFIG_DISABLE_MATCHERS -#define REQUIRE_NOTHROW( ... ) (void)(0) +#define REQUIRE_NOTHROW(...) (void)(0) -#define CHECK( ... ) (void)(0) -#define CHECK_FALSE( ... ) (void)(0) -#define CHECKED_IF( ... ) if (__VA_ARGS__) -#define CHECKED_ELSE( ... ) if (!(__VA_ARGS__)) -#define CHECK_NOFAIL( ... ) (void)(0) +#define CHECK(...) (void)(0) +#define CHECK_FALSE(...) (void)(0) +#define CHECKED_IF(...) if (__VA_ARGS__) +#define CHECKED_ELSE(...) if (!(__VA_ARGS__)) +#define CHECK_NOFAIL(...) (void)(0) -#define CHECK_THROWS( ... ) (void)(0) -#define CHECK_THROWS_AS( expr, exceptionType ) (void)(0) -#define CHECK_THROWS_WITH( expr, matcher ) (void)(0) +#define CHECK_THROWS(...) (void)(0) +#define CHECK_THROWS_AS(expr, exceptionType) (void)(0) +#define CHECK_THROWS_WITH(expr, matcher) (void)(0) #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) -#define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) +#define CHECK_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0) #endif // CATCH_CONFIG_DISABLE_MATCHERS -#define CHECK_NOTHROW( ... ) (void)(0) +#define CHECK_NOTHROW(...) (void)(0) #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) -#define CHECK_THAT( arg, matcher ) (void)(0) +#define CHECK_THAT(arg, matcher) (void)(0) -#define REQUIRE_THAT( arg, matcher ) (void)(0) +#define REQUIRE_THAT(arg, matcher) (void)(0) #endif // CATCH_CONFIG_DISABLE_MATCHERS -#define INFO( msg ) (void)(0) -#define UNSCOPED_INFO( msg ) (void)(0) -#define WARN( msg ) (void)(0) -#define CAPTURE( msg ) (void)(0) +#define INFO(msg) (void)(0) +#define UNSCOPED_INFO(msg) (void)(0) +#define WARN(msg) (void)(0) +#define CAPTURE(msg) (void)(0) -#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) -#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) -#define METHOD_AS_TEST_CASE( method, ... ) -#define REGISTER_TEST_CASE( Function, ... ) (void)(0) -#define SECTION( ... ) -#define DYNAMIC_SECTION( ... ) -#define FAIL( ... ) (void)(0) -#define FAIL_CHECK( ... ) (void)(0) -#define SUCCEED( ... ) (void)(0) -#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) +#define TEST_CASE(...) \ + INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \ + INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____)) +#define TEST_CASE_METHOD(className, ...) \ + INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \ + INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____)) +#define METHOD_AS_TEST_CASE(method, ...) +#define REGISTER_TEST_CASE(Function, ...) (void)(0) +#define SECTION(...) +#define DYNAMIC_SECTION(...) +#define FAIL(...) (void)(0) +#define FAIL_CHECK(...) (void)(0) +#define SUCCEED(...) (void)(0) +#define ANON_TEST_CASE() \ + INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \ + INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____)) #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR -#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) -#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) -#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__) -#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) -#define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) -#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) -#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) -#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) +#define TEMPLATE_TEST_CASE(...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) +#define TEMPLATE_TEST_CASE_SIG(...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) +#define TEMPLATE_TEST_CASE_METHOD(className, ...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, \ + __VA_ARGS__) +#define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, \ + __VA_ARGS__) +#define TEMPLATE_PRODUCT_TEST_CASE(...) TEMPLATE_TEST_CASE(__VA_ARGS__) +#define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) TEMPLATE_TEST_CASE(__VA_ARGS__) +#define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \ + TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__) +#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \ + TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__) #else -#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) ) -#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) ) -#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) ) -#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) ) -#define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) -#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) -#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) -#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) +#define TEMPLATE_TEST_CASE(...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)) +#define TEMPLATE_TEST_CASE_SIG(...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)) +#define TEMPLATE_TEST_CASE_METHOD(className, ...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, \ + __VA_ARGS__)) +#define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \ + INTERNAL_CATCH_EXPAND_VARGS( \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( \ + className, __VA_ARGS__)) +#define TEMPLATE_PRODUCT_TEST_CASE(...) TEMPLATE_TEST_CASE(__VA_ARGS__) +#define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) TEMPLATE_TEST_CASE(__VA_ARGS__) +#define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \ + TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__) +#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \ + TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__) #endif -#define STATIC_REQUIRE( ... ) (void)(0) -#define STATIC_REQUIRE_FALSE( ... ) (void)(0) +#define STATIC_REQUIRE(...) (void)(0) +#define STATIC_REQUIRE_FALSE(...) (void)(0) #endif -#define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature ) +#define CATCH_TRANSLATE_EXCEPTION(signature) \ + INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( \ + INTERNAL_CATCH_UNIQUE_NAME(catch_internal_ExceptionTranslator), \ + signature) // "BDD-style" convenience wrappers -#define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) ) -#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className ) +#define SCENARIO(...) \ + INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \ + INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____)) +#define SCENARIO_METHOD(className, ...) \ + INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( \ + INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____), className) -#define GIVEN( desc ) -#define AND_GIVEN( desc ) -#define WHEN( desc ) -#define AND_WHEN( desc ) -#define THEN( desc ) -#define AND_THEN( desc ) +#define GIVEN(desc) +#define AND_GIVEN(desc) +#define WHEN(desc) +#define AND_WHEN(desc) +#define THEN(desc) +#define AND_THEN(desc) using Catch::Detail::Approx; @@ -17942,18 +19978,16 @@ // start catch_reenable_warnings.h - #ifdef __clang__ -# ifdef __ICC // icpc defines the __clang__ macro -# pragma warning(pop) -# else -# pragma clang diagnostic pop -# endif +#ifdef __ICC // icpc defines the __clang__ macro +#pragma warning(pop) +#else +#pragma clang diagnostic pop +#endif #elif defined __GNUC__ -# pragma GCC diagnostic pop +#pragma GCC diagnostic pop #endif // end catch_reenable_warnings.h // end catch.hpp #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED -
diff --git a/include/rive/animation/animation.hpp b/include/rive/animation/animation.hpp index 39da5c9..ef84548 100644 --- a/include/rive/animation/animation.hpp +++ b/include/rive/animation/animation.hpp
@@ -1,11 +1,8 @@ #ifndef _RIVE_ANIMATION_HPP_ #define _RIVE_ANIMATION_HPP_ #include "rive/generated/animation/animation_base.hpp" -namespace rive -{ - class Animation : public AnimationBase - { - }; +namespace rive { + class Animation : public AnimationBase {}; } // namespace rive #endif \ No newline at end of file
diff --git a/include/rive/animation/animation_state.hpp b/include/rive/animation/animation_state.hpp index 5a12f29..178d287 100644 --- a/include/rive/animation/animation_state.hpp +++ b/include/rive/animation/animation_state.hpp
@@ -2,14 +2,12 @@ #define _RIVE_ANIMATION_STATE_HPP_ #include "rive/generated/animation/animation_state_base.hpp" #include <stdio.h> -namespace rive -{ +namespace rive { class LinearAnimation; class Artboard; class StateMachineLayerImporter; - class AnimationState : public AnimationStateBase - { + class AnimationState : public AnimationStateBase { friend class StateMachineLayerImporter; private:
diff --git a/include/rive/animation/animation_state_instance.hpp b/include/rive/animation/animation_state_instance.hpp index 7f27138..8c6244a 100644 --- a/include/rive/animation/animation_state_instance.hpp +++ b/include/rive/animation/animation_state_instance.hpp
@@ -5,13 +5,11 @@ #include "rive/animation/state_instance.hpp" #include "rive/animation/linear_animation_instance.hpp" -namespace rive -{ +namespace rive { class AnimationState; /// Represents an instance of an animation state. - class AnimationStateInstance : public StateInstance - { + class AnimationStateInstance : public StateInstance { private: LinearAnimationInstance m_AnimationInstance; bool m_KeepGoing; @@ -24,13 +22,11 @@ bool keepGoing() const override; - const LinearAnimationInstance* animationInstance() const - { + const LinearAnimationInstance* animationInstance() const { return &m_AnimationInstance; } - LinearAnimationInstance* animationInstance() - { + LinearAnimationInstance* animationInstance() { return &m_AnimationInstance; } };
diff --git a/include/rive/animation/any_state.hpp b/include/rive/animation/any_state.hpp index 12aa76d..faf5195 100644 --- a/include/rive/animation/any_state.hpp +++ b/include/rive/animation/any_state.hpp
@@ -2,10 +2,8 @@ #define _RIVE_ANY_STATE_HPP_ #include "rive/generated/animation/any_state_base.hpp" #include <stdio.h> -namespace rive -{ - class AnyState : public AnyStateBase - { +namespace rive { + class AnyState : public AnyStateBase { public: }; } // namespace rive
diff --git a/include/rive/animation/blend_animation.hpp b/include/rive/animation/blend_animation.hpp index edb94ea..29937a6 100644 --- a/include/rive/animation/blend_animation.hpp +++ b/include/rive/animation/blend_animation.hpp
@@ -1,11 +1,9 @@ #ifndef _RIVE_BLEND_ANIMATION_HPP_ #define _RIVE_BLEND_ANIMATION_HPP_ #include "rive/generated/animation/blend_animation_base.hpp" -namespace rive -{ +namespace rive { class LinearAnimation; - class BlendAnimation : public BlendAnimationBase - { + class BlendAnimation : public BlendAnimationBase { private: LinearAnimation* m_Animation = nullptr;
diff --git a/include/rive/animation/blend_animation_1d.hpp b/include/rive/animation/blend_animation_1d.hpp index ac1fe64..efaaa33 100644 --- a/include/rive/animation/blend_animation_1d.hpp +++ b/include/rive/animation/blend_animation_1d.hpp
@@ -2,10 +2,8 @@ #define _RIVE_BLEND_ANIMATION1_D_HPP_ #include "rive/generated/animation/blend_animation_1d_base.hpp" #include <stdio.h> -namespace rive -{ - class BlendAnimation1D : public BlendAnimation1DBase - { +namespace rive { + class BlendAnimation1D : public BlendAnimation1DBase { public: StatusCode onAddedDirty(CoreContext* context) override; StatusCode onAddedClean(CoreContext* context) override;
diff --git a/include/rive/animation/blend_animation_direct.hpp b/include/rive/animation/blend_animation_direct.hpp index ca05b66..686a900 100644 --- a/include/rive/animation/blend_animation_direct.hpp +++ b/include/rive/animation/blend_animation_direct.hpp
@@ -2,10 +2,8 @@ #define _RIVE_BLEND_ANIMATION_DIRECT_HPP_ #include "rive/generated/animation/blend_animation_direct_base.hpp" #include <stdio.h> -namespace rive -{ - class BlendAnimationDirect : public BlendAnimationDirectBase - { +namespace rive { + class BlendAnimationDirect : public BlendAnimationDirectBase { public: StatusCode onAddedDirty(CoreContext* context) override; StatusCode onAddedClean(CoreContext* context) override;
diff --git a/include/rive/animation/blend_state.hpp b/include/rive/animation/blend_state.hpp index 988a053..779d822 100644 --- a/include/rive/animation/blend_state.hpp +++ b/include/rive/animation/blend_state.hpp
@@ -5,13 +5,11 @@ #include <vector> #include <algorithm> -namespace rive -{ +namespace rive { class BlendAnimation; class LayerStateImporter; - class BlendState : public BlendStateBase - { + class BlendState : public BlendStateBase { friend class LayerStateImporter; private: @@ -20,8 +18,7 @@ public: ~BlendState(); - inline const std::vector<BlendAnimation*>& animations() const - { + inline const std::vector<BlendAnimation*>& animations() const { return m_Animations; }
diff --git a/include/rive/animation/blend_state_1d.hpp b/include/rive/animation/blend_state_1d.hpp index c72e9b2..78ed6b4 100644 --- a/include/rive/animation/blend_state_1d.hpp +++ b/include/rive/animation/blend_state_1d.hpp
@@ -2,10 +2,8 @@ #define _RIVE_BLEND_STATE1_D_HPP_ #include "rive/generated/animation/blend_state_1d_base.hpp" -namespace rive -{ - class BlendState1D : public BlendState1DBase - { +namespace rive { + class BlendState1D : public BlendState1DBase { public: StatusCode import(ImportStack& importStack) override;
diff --git a/include/rive/animation/blend_state_1d_instance.hpp b/include/rive/animation/blend_state_1d_instance.hpp index b7568a19..51a2beb 100644 --- a/include/rive/animation/blend_state_1d_instance.hpp +++ b/include/rive/animation/blend_state_1d_instance.hpp
@@ -5,11 +5,9 @@ #include "rive/animation/blend_state_1d.hpp" #include "rive/animation/blend_animation_1d.hpp" -namespace rive -{ +namespace rive { class BlendState1DInstance - : public BlendStateInstance<BlendState1D, BlendAnimation1D> - { + : public BlendStateInstance<BlendState1D, BlendAnimation1D> { private: BlendStateAnimationInstance<BlendAnimation1D>* m_From = nullptr; BlendStateAnimationInstance<BlendAnimation1D>* m_To = nullptr;
diff --git a/include/rive/animation/blend_state_direct.hpp b/include/rive/animation/blend_state_direct.hpp index b82d272..4dcb101 100644 --- a/include/rive/animation/blend_state_direct.hpp +++ b/include/rive/animation/blend_state_direct.hpp
@@ -2,10 +2,8 @@ #define _RIVE_BLEND_STATE_DIRECT_HPP_ #include "rive/generated/animation/blend_state_direct_base.hpp" #include <stdio.h> -namespace rive -{ - class BlendStateDirect : public BlendStateDirectBase - { +namespace rive { + class BlendStateDirect : public BlendStateDirectBase { public: StateInstance* makeInstance() const override; };
diff --git a/include/rive/animation/blend_state_direct_instance.hpp b/include/rive/animation/blend_state_direct_instance.hpp index 76a5d81..032788d 100644 --- a/include/rive/animation/blend_state_direct_instance.hpp +++ b/include/rive/animation/blend_state_direct_instance.hpp
@@ -5,11 +5,9 @@ #include "rive/animation/blend_state_direct.hpp" #include "rive/animation/blend_animation_direct.hpp" -namespace rive -{ +namespace rive { class BlendStateDirectInstance - : public BlendStateInstance<BlendStateDirect, BlendAnimationDirect> - { + : public BlendStateInstance<BlendStateDirect, BlendAnimationDirect> { public: BlendStateDirectInstance(const BlendStateDirect* blendState); void advance(float seconds, SMIInput** inputs) override;
diff --git a/include/rive/animation/blend_state_instance.hpp b/include/rive/animation/blend_state_instance.hpp index 2f4980c..717aed9 100644 --- a/include/rive/animation/blend_state_instance.hpp +++ b/include/rive/animation/blend_state_instance.hpp
@@ -7,13 +7,11 @@ #include "rive/animation/blend_state.hpp" #include "rive/animation/linear_animation_instance.hpp" -namespace rive -{ +namespace rive { class AnimationState; template <class K, class T> class BlendStateInstance; - template <class T> class BlendStateAnimationInstance - { + template <class T> class BlendStateAnimationInstance { template <class A, class B> friend class BlendStateInstance; private: @@ -23,31 +21,26 @@ public: const T* blendAnimation() const { return m_BlendAnimation; } - const LinearAnimationInstance* animationInstance() const - { + const LinearAnimationInstance* animationInstance() const { return &m_AnimationInstance; } BlendStateAnimationInstance(const T* blendAnimation) : m_BlendAnimation(blendAnimation), - m_AnimationInstance(blendAnimation->animation()) - { - } + m_AnimationInstance(blendAnimation->animation()) {} void mix(float value) { m_Mix = value; } }; - template <class K, class T> class BlendStateInstance : public StateInstance - { + template <class K, class T> + class BlendStateInstance : public StateInstance { protected: std::vector<BlendStateAnimationInstance<T>> m_AnimationInstances; bool m_KeepGoing = true; public: - BlendStateInstance(const K* blendState) : StateInstance(blendState) - { - for (auto blendAnimation : blendState->animations()) - { + BlendStateInstance(const K* blendState) : StateInstance(blendState) { + for (auto blendAnimation : blendState->animations()) { m_AnimationInstances.emplace_back( BlendStateAnimationInstance<T>( static_cast<T*>(blendAnimation))); @@ -56,22 +49,17 @@ bool keepGoing() const override { return m_KeepGoing; } - void advance(float seconds, SMIInput** inputs) override - { + void advance(float seconds, SMIInput** inputs) override { m_KeepGoing = false; - for (auto& animation : m_AnimationInstances) - { - if (animation.m_AnimationInstance.advance(seconds)) - { + for (auto& animation : m_AnimationInstances) { + if (animation.m_AnimationInstance.advance(seconds)) { m_KeepGoing = true; } } } - void apply(Artboard* artboard, float mix) override - { - for (auto& animation : m_AnimationInstances) - { + void apply(Artboard* artboard, float mix) override { + for (auto& animation : m_AnimationInstances) { float m = mix * animation.m_Mix; animation.m_AnimationInstance.apply(artboard, m); } @@ -79,12 +67,9 @@ // Find the animationInstance that corresponds to the blendAnimation. const LinearAnimationInstance* - animationInstance(const BlendAnimation* blendAnimation) const - { - for (auto& animation : m_AnimationInstances) - { - if (animation.m_BlendAnimation == blendAnimation) - { + animationInstance(const BlendAnimation* blendAnimation) const { + for (auto& animation : m_AnimationInstances) { + if (animation.m_BlendAnimation == blendAnimation) { return animation.animationInstance(); } }
diff --git a/include/rive/animation/blend_state_transition.hpp b/include/rive/animation/blend_state_transition.hpp index f59f35f..2ecbf49 100644 --- a/include/rive/animation/blend_state_transition.hpp +++ b/include/rive/animation/blend_state_transition.hpp
@@ -2,20 +2,17 @@ #define _RIVE_BLEND_STATE_TRANSITION_HPP_ #include "rive/generated/animation/blend_state_transition_base.hpp" #include <stdio.h> -namespace rive -{ +namespace rive { class BlendAnimation; class LayerStateImporter; - class BlendStateTransition : public BlendStateTransitionBase - { + class BlendStateTransition : public BlendStateTransitionBase { friend class LayerStateImporter; private: BlendAnimation* m_ExitBlendAnimation = nullptr; public: - BlendAnimation* exitBlendAnimation() const - { + BlendAnimation* exitBlendAnimation() const { return m_ExitBlendAnimation; }
diff --git a/include/rive/animation/cubic_interpolator.hpp b/include/rive/animation/cubic_interpolator.hpp index d8e7dfd..0be1302 100644 --- a/include/rive/animation/cubic_interpolator.hpp +++ b/include/rive/animation/cubic_interpolator.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_CUBIC_INTERPOLATOR_HPP_ #define _RIVE_CUBIC_INTERPOLATOR_HPP_ #include "rive/generated/animation/cubic_interpolator_base.hpp" -namespace rive -{ - class CubicInterpolator : public CubicInterpolatorBase - { +namespace rive { + class CubicInterpolator : public CubicInterpolatorBase { private: static constexpr int SplineTableSize = 11; static constexpr float SampleStepSize = 1.0f / (SplineTableSize - 1.0f);
diff --git a/include/rive/animation/entry_state.hpp b/include/rive/animation/entry_state.hpp index 2b88fbb..ef16315 100644 --- a/include/rive/animation/entry_state.hpp +++ b/include/rive/animation/entry_state.hpp
@@ -2,10 +2,8 @@ #define _RIVE_ENTRY_STATE_HPP_ #include "rive/generated/animation/entry_state_base.hpp" #include <stdio.h> -namespace rive -{ - class EntryState : public EntryStateBase - { +namespace rive { + class EntryState : public EntryStateBase { public: }; } // namespace rive
diff --git a/include/rive/animation/exit_state.hpp b/include/rive/animation/exit_state.hpp index d3ef24f..62ce595 100644 --- a/include/rive/animation/exit_state.hpp +++ b/include/rive/animation/exit_state.hpp
@@ -2,10 +2,8 @@ #define _RIVE_EXIT_STATE_HPP_ #include "rive/generated/animation/exit_state_base.hpp" #include <stdio.h> -namespace rive -{ - class ExitState : public ExitStateBase - { +namespace rive { + class ExitState : public ExitStateBase { public: }; } // namespace rive
diff --git a/include/rive/animation/keyed_object.hpp b/include/rive/animation/keyed_object.hpp index db253f2..b22c9a5 100644 --- a/include/rive/animation/keyed_object.hpp +++ b/include/rive/animation/keyed_object.hpp
@@ -2,12 +2,10 @@ #define _RIVE_KEYED_OBJECT_HPP_ #include "rive/generated/animation/keyed_object_base.hpp" #include <vector> -namespace rive -{ +namespace rive { class Artboard; class KeyedProperty; - class KeyedObject : public KeyedObjectBase - { + class KeyedObject : public KeyedObjectBase { private: std::vector<KeyedProperty*> m_KeyedProperties;
diff --git a/include/rive/animation/keyed_property.hpp b/include/rive/animation/keyed_property.hpp index 0640180..3470683 100644 --- a/include/rive/animation/keyed_property.hpp +++ b/include/rive/animation/keyed_property.hpp
@@ -2,11 +2,9 @@ #define _RIVE_KEYED_PROPERTY_HPP_ #include "rive/generated/animation/keyed_property_base.hpp" #include <vector> -namespace rive -{ +namespace rive { class KeyFrame; - class KeyedProperty : public KeyedPropertyBase - { + class KeyedProperty : public KeyedPropertyBase { private: std::vector<KeyFrame*> m_KeyFrames;
diff --git a/include/rive/animation/keyframe.hpp b/include/rive/animation/keyframe.hpp index 0747da6..e8bd6db 100644 --- a/include/rive/animation/keyframe.hpp +++ b/include/rive/animation/keyframe.hpp
@@ -1,20 +1,17 @@ #ifndef _RIVE_KEY_FRAME_HPP_ #define _RIVE_KEY_FRAME_HPP_ #include "rive/generated/animation/keyframe_base.hpp" -namespace rive -{ +namespace rive { class CubicInterpolator; - class KeyFrame : public KeyFrameBase - { + class KeyFrame : public KeyFrameBase { private: CubicInterpolator* m_Interpolator = nullptr; float m_Seconds; public: inline float seconds() const { return m_Seconds; } - inline CubicInterpolator* interpolator() const - { + inline CubicInterpolator* interpolator() const { return m_Interpolator; }
diff --git a/include/rive/animation/keyframe_bool.hpp b/include/rive/animation/keyframe_bool.hpp index 9f0d026..6910315 100644 --- a/include/rive/animation/keyframe_bool.hpp +++ b/include/rive/animation/keyframe_bool.hpp
@@ -2,10 +2,8 @@ #define _RIVE_KEY_FRAME_BOOL_HPP_ #include "rive/generated/animation/keyframe_bool_base.hpp" #include <stdio.h> -namespace rive -{ - class KeyFrameBool : public KeyFrameBoolBase - { +namespace rive { + class KeyFrameBool : public KeyFrameBoolBase { public: void apply(Core* object, int propertyKey, float mix) override; void applyInterpolation(Core* object,
diff --git a/include/rive/animation/keyframe_color.hpp b/include/rive/animation/keyframe_color.hpp index 2062f41..72463b2 100644 --- a/include/rive/animation/keyframe_color.hpp +++ b/include/rive/animation/keyframe_color.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_KEY_FRAME_COLOR_HPP_ #define _RIVE_KEY_FRAME_COLOR_HPP_ #include "rive/generated/animation/keyframe_color_base.hpp" -namespace rive -{ - class KeyFrameColor : public KeyFrameColorBase - { +namespace rive { + class KeyFrameColor : public KeyFrameColorBase { public: void apply(Core* object, int propertyKey, float mix) override; void applyInterpolation(Core* object,
diff --git a/include/rive/animation/keyframe_double.hpp b/include/rive/animation/keyframe_double.hpp index 60644ba..35ade77 100644 --- a/include/rive/animation/keyframe_double.hpp +++ b/include/rive/animation/keyframe_double.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_KEY_FRAME_DOUBLE_HPP_ #define _RIVE_KEY_FRAME_DOUBLE_HPP_ #include "rive/generated/animation/keyframe_double_base.hpp" -namespace rive -{ - class KeyFrameDouble : public KeyFrameDoubleBase - { +namespace rive { + class KeyFrameDouble : public KeyFrameDoubleBase { public: void apply(Core* object, int propertyKey, float mix) override; void applyInterpolation(Core* object,
diff --git a/include/rive/animation/keyframe_id.hpp b/include/rive/animation/keyframe_id.hpp index 9f95fc9..7ffc31f 100644 --- a/include/rive/animation/keyframe_id.hpp +++ b/include/rive/animation/keyframe_id.hpp
@@ -2,10 +2,8 @@ #define _RIVE_KEY_FRAME_ID_HPP_ #include "rive/generated/animation/keyframe_id_base.hpp" #include <stdio.h> -namespace rive -{ - class KeyFrameId : public KeyFrameIdBase - { +namespace rive { + class KeyFrameId : public KeyFrameIdBase { public: void apply(Core* object, int propertyKey, float mix) override; void applyInterpolation(Core* object,
diff --git a/include/rive/animation/layer_state.hpp b/include/rive/animation/layer_state.hpp index 1b515f2..3802da8 100644 --- a/include/rive/animation/layer_state.hpp +++ b/include/rive/animation/layer_state.hpp
@@ -4,15 +4,13 @@ #include <stdio.h> #include <vector> -namespace rive -{ +namespace rive { class StateTransition; class LayerStateImporter; class StateMachineLayerImporter; class StateInstance; - class LayerState : public LayerStateBase - { + class LayerState : public LayerStateBase { friend class LayerStateImporter; friend class StateMachineLayerImporter; @@ -28,10 +26,8 @@ StatusCode import(ImportStack& importStack) override; size_t transitionCount() const { return m_Transitions.size(); } - StateTransition* transition(size_t index) const - { - if (index < m_Transitions.size()) - { + StateTransition* transition(size_t index) const { + if (index < m_Transitions.size()) { return m_Transitions[index]; } return nullptr;
diff --git a/include/rive/animation/linear_animation.hpp b/include/rive/animation/linear_animation.hpp index 68e52c1..9871bc6 100644 --- a/include/rive/animation/linear_animation.hpp +++ b/include/rive/animation/linear_animation.hpp
@@ -3,17 +3,16 @@ #include "rive/animation/loop.hpp" #include "rive/generated/animation/linear_animation_base.hpp" #include <vector> -namespace rive -{ +namespace rive { class Artboard; class KeyedObject; - class LinearAnimation : public LinearAnimationBase - { + class LinearAnimation : public LinearAnimationBase { private: std::vector<KeyedObject*> m_KeyedObjects; friend class Artboard; + public: ~LinearAnimation(); StatusCode onAddedDirty(CoreContext* context) override;
diff --git a/include/rive/animation/linear_animation_instance.hpp b/include/rive/animation/linear_animation_instance.hpp index 53f7c93..31c1171 100644 --- a/include/rive/animation/linear_animation_instance.hpp +++ b/include/rive/animation/linear_animation_instance.hpp
@@ -2,12 +2,10 @@ #define _RIVE_LINEAR_ANIMATION_INSTANCE_HPP_ #include "rive/artboard.hpp" -namespace rive -{ +namespace rive { class LinearAnimation; - class LinearAnimationInstance - { + class LinearAnimationInstance { private: const LinearAnimation* m_Animation = nullptr; float m_Time; @@ -37,14 +35,10 @@ // Update the direction of the animation instance, positive value for // forwards Negative for backwards - void direction(int direction) - { - if (direction > 0) - { + void direction(int direction) { + if (direction > 0) { m_Direction = 1; - } - else - { + } else { m_Direction = -1; } } @@ -55,8 +49,7 @@ // Applies the animation instance to an artboard. The mix (a value // between 0 and 1) is the strength at which the animation is mixed with // other animations applied to the artboard. - void apply(Artboard* artboard, float mix = 1.0f) const - { + void apply(Artboard* artboard, float mix = 1.0f) const { m_Animation->apply(artboard, m_Time, mix); }
diff --git a/include/rive/animation/loop.hpp b/include/rive/animation/loop.hpp index f6c86f6..cd9e88c 100644 --- a/include/rive/animation/loop.hpp +++ b/include/rive/animation/loop.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_LOOP_HPP_ #define _RIVE_LOOP_HPP_ -namespace rive -{ +namespace rive { /// Loop options for linear animations. - enum class Loop : unsigned int - { + enum class Loop : unsigned int { /// Play until the duration or end of work area of the animation. oneShot = 0,
diff --git a/include/rive/animation/nested_linear_animation.hpp b/include/rive/animation/nested_linear_animation.hpp index a8c670e..7940c51 100644 --- a/include/rive/animation/nested_linear_animation.hpp +++ b/include/rive/animation/nested_linear_animation.hpp
@@ -2,11 +2,9 @@ #define _RIVE_NESTED_LINEAR_ANIMATION_HPP_ #include "rive/generated/animation/nested_linear_animation_base.hpp" #include <stdio.h> -namespace rive -{ +namespace rive { class LinearAnimationInstance; - class NestedLinearAnimation : public NestedLinearAnimationBase - { + class NestedLinearAnimation : public NestedLinearAnimationBase { protected: LinearAnimationInstance* m_AnimationInstance = nullptr;
diff --git a/include/rive/animation/nested_remap_animation.hpp b/include/rive/animation/nested_remap_animation.hpp index 54030c5..504ac0b 100644 --- a/include/rive/animation/nested_remap_animation.hpp +++ b/include/rive/animation/nested_remap_animation.hpp
@@ -2,10 +2,8 @@ #define _RIVE_NESTED_REMAP_ANIMATION_HPP_ #include "rive/generated/animation/nested_remap_animation_base.hpp" #include <stdio.h> -namespace rive -{ - class NestedRemapAnimation : public NestedRemapAnimationBase - { +namespace rive { + class NestedRemapAnimation : public NestedRemapAnimationBase { public: void timeChanged() override; void advance(float elapsedSeconds, Artboard* artboard) override;
diff --git a/include/rive/animation/nested_simple_animation.hpp b/include/rive/animation/nested_simple_animation.hpp index 75901c4..ceca0ce 100644 --- a/include/rive/animation/nested_simple_animation.hpp +++ b/include/rive/animation/nested_simple_animation.hpp
@@ -2,10 +2,8 @@ #define _RIVE_NESTED_SIMPLE_ANIMATION_HPP_ #include "rive/generated/animation/nested_simple_animation_base.hpp" #include <stdio.h> -namespace rive -{ - class NestedSimpleAnimation : public NestedSimpleAnimationBase - { +namespace rive { + class NestedSimpleAnimation : public NestedSimpleAnimationBase { public: void advance(float elapsedSeconds, Artboard* artboard) override; };
diff --git a/include/rive/animation/nested_state_machine.hpp b/include/rive/animation/nested_state_machine.hpp index c5cdb6a..04893ec 100644 --- a/include/rive/animation/nested_state_machine.hpp +++ b/include/rive/animation/nested_state_machine.hpp
@@ -2,10 +2,8 @@ #define _RIVE_NESTED_STATE_MACHINE_HPP_ #include "rive/generated/animation/nested_state_machine_base.hpp" #include <stdio.h> -namespace rive -{ - class NestedStateMachine : public NestedStateMachineBase - { +namespace rive { + class NestedStateMachine : public NestedStateMachineBase { public: void advance(float elapsedSeconds, Artboard* artboard) override; void initializeAnimation(Artboard* artboard) override;
diff --git a/include/rive/animation/state_instance.hpp b/include/rive/animation/state_instance.hpp index e81aa52..dcdb5f2 100644 --- a/include/rive/animation/state_instance.hpp +++ b/include/rive/animation/state_instance.hpp
@@ -4,15 +4,13 @@ #include <string> #include <stddef.h> -namespace rive -{ +namespace rive { class LayerState; class SMIInput; class Artboard; /// Represents an instance of a state tracked by the State Machine. - class StateInstance - { + class StateInstance { private: const LayerState* m_LayerState;
diff --git a/include/rive/animation/state_machine.hpp b/include/rive/animation/state_machine.hpp index cbc54e9..8f659ea 100644 --- a/include/rive/animation/state_machine.hpp +++ b/include/rive/animation/state_machine.hpp
@@ -4,13 +4,11 @@ #include <stdio.h> #include <vector> -namespace rive -{ +namespace rive { class StateMachineLayer; class StateMachineInput; class StateMachineImporter; - class StateMachine : public StateMachineBase - { + class StateMachine : public StateMachineBase { friend class StateMachineImporter; private:
diff --git a/include/rive/animation/state_machine_bool.hpp b/include/rive/animation/state_machine_bool.hpp index 7545c5e..7517efe 100644 --- a/include/rive/animation/state_machine_bool.hpp +++ b/include/rive/animation/state_machine_bool.hpp
@@ -2,10 +2,8 @@ #define _RIVE_STATE_MACHINE_BOOL_HPP_ #include "rive/generated/animation/state_machine_bool_base.hpp" #include <stdio.h> -namespace rive -{ - class StateMachineBool : public StateMachineBoolBase - { +namespace rive { + class StateMachineBool : public StateMachineBoolBase { public: }; } // namespace rive
diff --git a/include/rive/animation/state_machine_component.hpp b/include/rive/animation/state_machine_component.hpp index c1f02d1..87ea93e 100644 --- a/include/rive/animation/state_machine_component.hpp +++ b/include/rive/animation/state_machine_component.hpp
@@ -2,10 +2,8 @@ #define _RIVE_STATE_MACHINE_COMPONENT_HPP_ #include "rive/generated/animation/state_machine_component_base.hpp" #include <stdio.h> -namespace rive -{ - class StateMachineComponent : public StateMachineComponentBase - { +namespace rive { + class StateMachineComponent : public StateMachineComponentBase { public: }; } // namespace rive
diff --git a/include/rive/animation/state_machine_input.hpp b/include/rive/animation/state_machine_input.hpp index 4de0b32..491e3e8 100644 --- a/include/rive/animation/state_machine_input.hpp +++ b/include/rive/animation/state_machine_input.hpp
@@ -2,10 +2,8 @@ #define _RIVE_STATE_MACHINE_INPUT_HPP_ #include "rive/generated/animation/state_machine_input_base.hpp" #include <stdio.h> -namespace rive -{ - class StateMachineInput : public StateMachineInputBase - { +namespace rive { + class StateMachineInput : public StateMachineInputBase { public: StatusCode onAddedDirty(CoreContext* context) override; StatusCode onAddedClean(CoreContext* context) override;
diff --git a/include/rive/animation/state_machine_input_instance.hpp b/include/rive/animation/state_machine_input_instance.hpp index 6f1b1ca..3744a4b 100644 --- a/include/rive/animation/state_machine_input_instance.hpp +++ b/include/rive/animation/state_machine_input_instance.hpp
@@ -4,8 +4,7 @@ #include <string> #include <stdint.h> -namespace rive -{ +namespace rive { class StateMachineInstance; class StateMachineInput; class StateMachineBool; @@ -14,8 +13,7 @@ class TransitionTriggerCondition; class StateMachineLayerInstance; - class SMIInput - { + class SMIInput { friend class StateMachineInstance; friend class StateMachineLayerInstance; @@ -39,8 +37,7 @@ uint16_t inputCoreType() const; }; - class SMIBool : public SMIInput - { + class SMIBool : public SMIInput { friend class StateMachineInstance; private: @@ -54,8 +51,7 @@ void value(bool newValue); }; - class SMINumber : public SMIInput - { + class SMINumber : public SMIInput { friend class StateMachineInstance; private: @@ -69,8 +65,7 @@ void value(float newValue); }; - class SMITrigger : public SMIInput - { + class SMITrigger : public SMIInput { friend class StateMachineInstance; friend class TransitionTriggerCondition;
diff --git a/include/rive/animation/state_machine_instance.hpp b/include/rive/animation/state_machine_instance.hpp index ff15172..8db2b78 100644 --- a/include/rive/animation/state_machine_instance.hpp +++ b/include/rive/animation/state_machine_instance.hpp
@@ -5,8 +5,7 @@ #include <stddef.h> #include "rive/animation/linear_animation_instance.hpp" -namespace rive -{ +namespace rive { class StateMachine; class LayerState; class SMIInput; @@ -17,8 +16,7 @@ class StateMachineLayerInstance; - class StateMachineInstance - { + class StateMachineInstance { friend class SMIInput; private:
diff --git a/include/rive/animation/state_machine_layer.hpp b/include/rive/animation/state_machine_layer.hpp index 5a9cd5f..8de9443 100644 --- a/include/rive/animation/state_machine_layer.hpp +++ b/include/rive/animation/state_machine_layer.hpp
@@ -4,15 +4,13 @@ #include <stdio.h> #include <vector> -namespace rive -{ +namespace rive { class LayerState; class StateMachineLayerImporter; class AnyState; class EntryState; class ExitState; - class StateMachineLayer : public StateMachineLayerBase - { + class StateMachineLayer : public StateMachineLayerBase { friend class StateMachineLayerImporter; private: @@ -36,10 +34,8 @@ #ifdef TESTING size_t stateCount() const { return m_States.size(); } - LayerState* state(size_t index) const - { - if (index < m_States.size()) - { + LayerState* state(size_t index) const { + if (index < m_States.size()) { return m_States[index]; } return nullptr;
diff --git a/include/rive/animation/state_machine_layer_component.hpp b/include/rive/animation/state_machine_layer_component.hpp index 5147cb5..15303d9 100644 --- a/include/rive/animation/state_machine_layer_component.hpp +++ b/include/rive/animation/state_machine_layer_component.hpp
@@ -2,10 +2,8 @@ #define _RIVE_STATE_MACHINE_LAYER_COMPONENT_HPP_ #include "rive/generated/animation/state_machine_layer_component_base.hpp" #include <stdio.h> -namespace rive -{ - class StateMachineLayerComponent : public StateMachineLayerComponentBase - { +namespace rive { + class StateMachineLayerComponent : public StateMachineLayerComponentBase { public: }; } // namespace rive
diff --git a/include/rive/animation/state_machine_number.hpp b/include/rive/animation/state_machine_number.hpp index cc5858a..955a2dd 100644 --- a/include/rive/animation/state_machine_number.hpp +++ b/include/rive/animation/state_machine_number.hpp
@@ -2,10 +2,8 @@ #define _RIVE_STATE_MACHINE_NUMBER_HPP_ #include "rive/generated/animation/state_machine_number_base.hpp" #include <stdio.h> -namespace rive -{ - class StateMachineNumber : public StateMachineNumberBase - { +namespace rive { + class StateMachineNumber : public StateMachineNumberBase { public: }; } // namespace rive
diff --git a/include/rive/animation/state_machine_trigger.hpp b/include/rive/animation/state_machine_trigger.hpp index 3e97da9..bd017ad 100644 --- a/include/rive/animation/state_machine_trigger.hpp +++ b/include/rive/animation/state_machine_trigger.hpp
@@ -2,11 +2,8 @@ #define _RIVE_STATE_MACHINE_TRIGGER_HPP_ #include "rive/generated/animation/state_machine_trigger_base.hpp" #include <stdio.h> -namespace rive -{ - class StateMachineTrigger : public StateMachineTriggerBase - { - }; +namespace rive { + class StateMachineTrigger : public StateMachineTriggerBase {}; } // namespace rive #endif \ No newline at end of file
diff --git a/include/rive/animation/state_transition.hpp b/include/rive/animation/state_transition.hpp index b6983d0..53339b3 100644 --- a/include/rive/animation/state_transition.hpp +++ b/include/rive/animation/state_transition.hpp
@@ -5,8 +5,7 @@ #include <stdio.h> #include <vector> -namespace rive -{ +namespace rive { class LayerState; class StateMachineLayerImporter; class StateTransitionImporter; @@ -16,21 +15,14 @@ class LinearAnimation; class LinearAnimationInstance; - enum class AllowTransition : unsigned char - { - no, - waitingForExit, - yes - }; + enum class AllowTransition : unsigned char { no, waitingForExit, yes }; - class StateTransition : public StateTransitionBase - { + class StateTransition : public StateTransitionBase { friend class StateMachineLayerImporter; friend class StateTransitionImporter; private: - StateTransitionFlags transitionFlags() const - { + StateTransitionFlags transitionFlags() const { return static_cast<StateTransitionFlags>(flags()); } LayerState* m_StateTo = nullptr; @@ -47,8 +39,7 @@ /// Whether the transition is marked disabled (usually done in the /// editor). - bool isDisabled() const - { + bool isDisabled() const { return (transitionFlags() & StateTransitionFlags::Disabled) == StateTransitionFlags::Disabled; } @@ -61,16 +52,14 @@ /// Whether the animation is held at exit or if it keeps advancing /// during mixing. - bool pauseOnExit() const - { + bool pauseOnExit() const { return (transitionFlags() & StateTransitionFlags::PauseOnExit) == StateTransitionFlags::PauseOnExit; } /// Whether exit time is enabled. All other conditions still apply, the /// exit time is effectively an AND with the rest of the conditions. - bool enableExitTime() const - { + bool enableExitTime() const { return (transitionFlags() & StateTransitionFlags::EnableExitTime) == StateTransitionFlags::EnableExitTime; } @@ -78,10 +67,8 @@ StatusCode import(ImportStack& importStack) override; size_t conditionCount() const { return m_Conditions.size(); } - TransitionCondition* condition(size_t index) const - { - if (index < m_Conditions.size()) - { + TransitionCondition* condition(size_t index) const { + if (index < m_Conditions.size()) { return m_Conditions[index]; } return nullptr;
diff --git a/include/rive/animation/state_transition_flags.hpp b/include/rive/animation/state_transition_flags.hpp index 56626a4..e55cb01 100644 --- a/include/rive/animation/state_transition_flags.hpp +++ b/include/rive/animation/state_transition_flags.hpp
@@ -3,10 +3,8 @@ #include <type_traits> -namespace rive -{ - enum class StateTransitionFlags : unsigned char - { +namespace rive { + enum class StateTransitionFlags : unsigned char { None = 0, /// Whether the transition is disabled. @@ -28,39 +26,34 @@ }; inline constexpr StateTransitionFlags operator&(StateTransitionFlags lhs, - StateTransitionFlags rhs) - { + StateTransitionFlags rhs) { return static_cast<StateTransitionFlags>( static_cast<std::underlying_type<StateTransitionFlags>::type>(lhs) & static_cast<std::underlying_type<StateTransitionFlags>::type>(rhs)); } inline constexpr StateTransitionFlags operator^(StateTransitionFlags lhs, - StateTransitionFlags rhs) - { + StateTransitionFlags rhs) { return static_cast<StateTransitionFlags>( static_cast<std::underlying_type<StateTransitionFlags>::type>(lhs) ^ static_cast<std::underlying_type<StateTransitionFlags>::type>(rhs)); } inline constexpr StateTransitionFlags operator|(StateTransitionFlags lhs, - StateTransitionFlags rhs) - { + StateTransitionFlags rhs) { return static_cast<StateTransitionFlags>( static_cast<std::underlying_type<StateTransitionFlags>::type>(lhs) | static_cast<std::underlying_type<StateTransitionFlags>::type>(rhs)); } - inline constexpr StateTransitionFlags operator~(StateTransitionFlags rhs) - { + inline constexpr StateTransitionFlags operator~(StateTransitionFlags rhs) { return static_cast<StateTransitionFlags>( ~static_cast<std::underlying_type<StateTransitionFlags>::type>( rhs)); } inline StateTransitionFlags& operator|=(StateTransitionFlags& lhs, - StateTransitionFlags rhs) - { + StateTransitionFlags rhs) { lhs = static_cast<StateTransitionFlags>( static_cast<std::underlying_type<StateTransitionFlags>::type>(lhs) | static_cast<std::underlying_type<StateTransitionFlags>::type>(rhs)); @@ -69,8 +62,7 @@ } inline StateTransitionFlags& operator&=(StateTransitionFlags& lhs, - StateTransitionFlags rhs) - { + StateTransitionFlags rhs) { lhs = static_cast<StateTransitionFlags>( static_cast<std::underlying_type<StateTransitionFlags>::type>(lhs) & static_cast<std::underlying_type<StateTransitionFlags>::type>(rhs)); @@ -79,8 +71,7 @@ } inline StateTransitionFlags& operator^=(StateTransitionFlags& lhs, - StateTransitionFlags rhs) - { + StateTransitionFlags rhs) { lhs = static_cast<StateTransitionFlags>( static_cast<std::underlying_type<StateTransitionFlags>::type>(lhs) ^ static_cast<std::underlying_type<StateTransitionFlags>::type>(rhs));
diff --git a/include/rive/animation/system_state_instance.hpp b/include/rive/animation/system_state_instance.hpp index abdba7d..50ae376 100644 --- a/include/rive/animation/system_state_instance.hpp +++ b/include/rive/animation/system_state_instance.hpp
@@ -4,13 +4,11 @@ #include <string> #include "rive/animation/state_instance.hpp" -namespace rive -{ +namespace rive { /// Represents an instance of a system state machine. Basically a /// placeholder that may have meaning to the state machine itself, or is /// just a no-op state (perhaps an unknown to this runtime state-type). - class SystemStateInstance : public StateInstance - { + class SystemStateInstance : public StateInstance { public: SystemStateInstance(const LayerState* layerState);
diff --git a/include/rive/animation/transition_bool_condition.hpp b/include/rive/animation/transition_bool_condition.hpp index b540fd4..2a5a6dc 100644 --- a/include/rive/animation/transition_bool_condition.hpp +++ b/include/rive/animation/transition_bool_condition.hpp
@@ -2,10 +2,8 @@ #define _RIVE_TRANSITION_BOOL_CONDITION_HPP_ #include "rive/generated/animation/transition_bool_condition_base.hpp" #include <stdio.h> -namespace rive -{ - class TransitionBoolCondition : public TransitionBoolConditionBase - { +namespace rive { + class TransitionBoolCondition : public TransitionBoolConditionBase { public: bool evaluate(const SMIInput* inputInstance) const override;
diff --git a/include/rive/animation/transition_condition.hpp b/include/rive/animation/transition_condition.hpp index c40600b..0e6b0b2 100644 --- a/include/rive/animation/transition_condition.hpp +++ b/include/rive/animation/transition_condition.hpp
@@ -2,27 +2,23 @@ #define _RIVE_TRANSITION_CONDITION_HPP_ #include "rive/generated/animation/transition_condition_base.hpp" -namespace rive -{ +namespace rive { class StateMachineInput; class SMIInput; - class TransitionCondition : public TransitionConditionBase - { + class TransitionCondition : public TransitionConditionBase { public: StatusCode onAddedDirty(CoreContext* context) override; StatusCode onAddedClean(CoreContext* context) override; StatusCode import(ImportStack& importStack) override; - virtual bool evaluate(const SMIInput* inputInstance) const - { + virtual bool evaluate(const SMIInput* inputInstance) const { return true; } protected: - virtual bool validateInputType(const StateMachineInput* input) const - { + virtual bool validateInputType(const StateMachineInput* input) const { return true; } };
diff --git a/include/rive/animation/transition_condition_op.hpp b/include/rive/animation/transition_condition_op.hpp index 960d98e..9be74f2 100644 --- a/include/rive/animation/transition_condition_op.hpp +++ b/include/rive/animation/transition_condition_op.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_TRANSITION_CONDITION_OP_HPP_ #define _RIVE_TRANSITION_CONDITION_OP_HPP_ -namespace rive -{ - enum class TransitionConditionOp : int - { +namespace rive { + enum class TransitionConditionOp : int { equal = 0, notEqual = 1, lessThanOrEqual = 2,
diff --git a/include/rive/animation/transition_number_condition.hpp b/include/rive/animation/transition_number_condition.hpp index 8824472..dbaac02 100644 --- a/include/rive/animation/transition_number_condition.hpp +++ b/include/rive/animation/transition_number_condition.hpp
@@ -2,10 +2,8 @@ #define _RIVE_TRANSITION_NUMBER_CONDITION_HPP_ #include "rive/generated/animation/transition_number_condition_base.hpp" #include <stdio.h> -namespace rive -{ - class TransitionNumberCondition : public TransitionNumberConditionBase - { +namespace rive { + class TransitionNumberCondition : public TransitionNumberConditionBase { protected: bool validateInputType(const StateMachineInput* input) const override;
diff --git a/include/rive/animation/transition_trigger_condition.hpp b/include/rive/animation/transition_trigger_condition.hpp index 22110c6..677cd67 100644 --- a/include/rive/animation/transition_trigger_condition.hpp +++ b/include/rive/animation/transition_trigger_condition.hpp
@@ -2,10 +2,8 @@ #define _RIVE_TRANSITION_TRIGGER_CONDITION_HPP_ #include "rive/generated/animation/transition_trigger_condition_base.hpp" #include <stdio.h> -namespace rive -{ - class TransitionTriggerCondition : public TransitionTriggerConditionBase - { +namespace rive { + class TransitionTriggerCondition : public TransitionTriggerConditionBase { public: bool evaluate(const SMIInput* inputInstance) const override;
diff --git a/include/rive/animation/transition_value_condition.hpp b/include/rive/animation/transition_value_condition.hpp index e4b0590..cc362a4 100644 --- a/include/rive/animation/transition_value_condition.hpp +++ b/include/rive/animation/transition_value_condition.hpp
@@ -3,13 +3,10 @@ #include "rive/generated/animation/transition_value_condition_base.hpp" #include "rive/animation/transition_condition_op.hpp" -namespace rive -{ - class TransitionValueCondition : public TransitionValueConditionBase - { +namespace rive { + class TransitionValueCondition : public TransitionValueConditionBase { public: - TransitionConditionOp op() const - { + TransitionConditionOp op() const { return (TransitionConditionOp)opValue(); } };
diff --git a/include/rive/artboard.hpp b/include/rive/artboard.hpp index 8233fa4..6a42bf1 100644 --- a/include/rive/artboard.hpp +++ b/include/rive/artboard.hpp
@@ -8,8 +8,7 @@ #include "rive/renderer.hpp" #include "rive/shapes/shape_paint_container.hpp" #include <vector> -namespace rive -{ +namespace rive { class File; class Drawable; class Node; @@ -19,8 +18,7 @@ class Artboard : public ArtboardBase, public CoreContext, - public ShapePaintContainer - { + public ShapePaintContainer { friend class File; friend class ArtboardImporter; friend class Component; @@ -66,7 +64,7 @@ void onDirty(ComponentDirt dirt) override; bool advance(double elapsedSeconds); - + enum class DrawOption { kNormal, kHideBG, @@ -82,13 +80,10 @@ AABB bounds() const; bool isTranslucent(const LinearAnimation*) const; - template <typename T = Component> T* find(std::string name) - { - for (auto object : m_Objects) - { + template <typename T = Component> T* find(std::string name) { + for (auto object : m_Objects) { if (object != nullptr && object->is<T>() && - object->as<T>()->name() == name) - { + object->as<T>()->name() == name) { return reinterpret_cast<T*>(object); } }
diff --git a/include/rive/assets/asset.hpp b/include/rive/assets/asset.hpp index 5b2b504..9189e29 100644 --- a/include/rive/assets/asset.hpp +++ b/include/rive/assets/asset.hpp
@@ -2,10 +2,8 @@ #define _RIVE_ASSET_HPP_ #include "rive/generated/assets/asset_base.hpp" #include <stdio.h> -namespace rive -{ - class Asset : public AssetBase - { +namespace rive { + class Asset : public AssetBase { public: }; } // namespace rive
diff --git a/include/rive/assets/drawable_asset.hpp b/include/rive/assets/drawable_asset.hpp index 337a81c..7e9085e 100644 --- a/include/rive/assets/drawable_asset.hpp +++ b/include/rive/assets/drawable_asset.hpp
@@ -2,10 +2,8 @@ #define _RIVE_DRAWABLE_ASSET_HPP_ #include "rive/generated/assets/drawable_asset_base.hpp" #include <stdio.h> -namespace rive -{ - class DrawableAsset : public DrawableAssetBase - { +namespace rive { + class DrawableAsset : public DrawableAssetBase { public: }; } // namespace rive
diff --git a/include/rive/assets/file_asset.hpp b/include/rive/assets/file_asset.hpp index 8d0d476..e2bff1d 100644 --- a/include/rive/assets/file_asset.hpp +++ b/include/rive/assets/file_asset.hpp
@@ -3,10 +3,8 @@ #include "rive/generated/assets/file_asset_base.hpp" #include <string> -namespace rive -{ - class FileAsset : public FileAssetBase - { +namespace rive { + class FileAsset : public FileAssetBase { public: virtual bool decode(const uint8_t* bytes, std::size_t size) = 0; virtual std::string fileExtension() = 0;
diff --git a/include/rive/assets/file_asset_contents.hpp b/include/rive/assets/file_asset_contents.hpp index 32c961b..7a237a9 100644 --- a/include/rive/assets/file_asset_contents.hpp +++ b/include/rive/assets/file_asset_contents.hpp
@@ -2,10 +2,8 @@ #define _RIVE_FILE_ASSET_CONTENTS_HPP_ #include "rive/generated/assets/file_asset_contents_base.hpp" -namespace rive -{ - class FileAssetContents : public FileAssetContentsBase - { +namespace rive { + class FileAssetContents : public FileAssetContentsBase { public: StatusCode import(ImportStack& importStack) override; };
diff --git a/include/rive/assets/file_asset_referencer.hpp b/include/rive/assets/file_asset_referencer.hpp index 0d5dc35..7fc02d5 100644 --- a/include/rive/assets/file_asset_referencer.hpp +++ b/include/rive/assets/file_asset_referencer.hpp
@@ -1,11 +1,9 @@ #ifndef _RIVE_FILE_ASSET_REFERENCER_HPP_ #define _RIVE_FILE_ASSET_REFERENCER_HPP_ -namespace rive -{ +namespace rive { class FileAsset; - class FileAssetReferencer - { + class FileAssetReferencer { public: virtual void assets(const std::vector<FileAsset*>& assets) = 0; };
diff --git a/include/rive/assets/folder.hpp b/include/rive/assets/folder.hpp index 78c935d..54d870e 100644 --- a/include/rive/assets/folder.hpp +++ b/include/rive/assets/folder.hpp
@@ -2,10 +2,8 @@ #define _RIVE_FOLDER_HPP_ #include "rive/generated/assets/folder_base.hpp" #include <stdio.h> -namespace rive -{ - class Folder : public FolderBase - { +namespace rive { + class Folder : public FolderBase { public: }; } // namespace rive
diff --git a/include/rive/assets/image_asset.hpp b/include/rive/assets/image_asset.hpp index 6831f0a..76718b9 100644 --- a/include/rive/assets/image_asset.hpp +++ b/include/rive/assets/image_asset.hpp
@@ -4,11 +4,9 @@ #include "rive/generated/assets/image_asset_base.hpp" #include <string> -namespace rive -{ +namespace rive { class RenderImage; - class ImageAsset : public ImageAssetBase - { + class ImageAsset : public ImageAssetBase { private: RenderImage* m_RenderImage;
diff --git a/include/rive/backboard.hpp b/include/rive/backboard.hpp index c7e25f9..a9b1db3 100644 --- a/include/rive/backboard.hpp +++ b/include/rive/backboard.hpp
@@ -1,11 +1,8 @@ #ifndef _RIVE_BACKBOARD_HPP_ #define _RIVE_BACKBOARD_HPP_ #include "rive/generated/backboard_base.hpp" -namespace rive -{ - class Backboard : public BackboardBase - { - }; +namespace rive { + class Backboard : public BackboardBase {}; } // namespace rive #endif \ No newline at end of file
diff --git a/include/rive/bones/bone.hpp b/include/rive/bones/bone.hpp index 21da007..ce7505c 100644 --- a/include/rive/bones/bone.hpp +++ b/include/rive/bones/bone.hpp
@@ -4,11 +4,9 @@ #include <stdio.h> #include <vector> -namespace rive -{ +namespace rive { class Constraint; - class Bone : public BoneBase - { + class Bone : public BoneBase { private: std::vector<Bone*> m_ChildBones; @@ -24,8 +22,7 @@ void addChildBone(Bone* bone); void tipWorldTranslation(Vec2D& result); void addPeerConstraint(Constraint* peer); - const std::vector<Constraint*>& peerConstraints() const - { + const std::vector<Constraint*>& peerConstraints() const { return m_PeerConstraints; }
diff --git a/include/rive/bones/cubic_weight.hpp b/include/rive/bones/cubic_weight.hpp index 44732d7..ad395d5 100644 --- a/include/rive/bones/cubic_weight.hpp +++ b/include/rive/bones/cubic_weight.hpp
@@ -2,10 +2,8 @@ #define _RIVE_CUBIC_WEIGHT_HPP_ #include "rive/generated/bones/cubic_weight_base.hpp" #include <stdio.h> -namespace rive -{ - class CubicWeight : public CubicWeightBase - { +namespace rive { + class CubicWeight : public CubicWeightBase { private: Vec2D m_InTranslation; Vec2D m_OutTranslation;
diff --git a/include/rive/bones/root_bone.hpp b/include/rive/bones/root_bone.hpp index e5c9fa0..a3bfa68 100644 --- a/include/rive/bones/root_bone.hpp +++ b/include/rive/bones/root_bone.hpp
@@ -2,10 +2,8 @@ #define _RIVE_ROOT_BONE_HPP_ #include "rive/generated/bones/root_bone_base.hpp" #include <stdio.h> -namespace rive -{ - class RootBone : public RootBoneBase - { +namespace rive { + class RootBone : public RootBoneBase { public: StatusCode onAddedClean(CoreContext* context) override;
diff --git a/include/rive/bones/skeletal_component.hpp b/include/rive/bones/skeletal_component.hpp index b62dbba..568f29e 100644 --- a/include/rive/bones/skeletal_component.hpp +++ b/include/rive/bones/skeletal_component.hpp
@@ -2,10 +2,8 @@ #define _RIVE_SKELETAL_COMPONENT_HPP_ #include "rive/generated/bones/skeletal_component_base.hpp" #include <stdio.h> -namespace rive -{ - class SkeletalComponent : public SkeletalComponentBase - { +namespace rive { + class SkeletalComponent : public SkeletalComponentBase { public: }; } // namespace rive
diff --git a/include/rive/bones/skin.hpp b/include/rive/bones/skin.hpp index 1d7d0af..f555024 100644 --- a/include/rive/bones/skin.hpp +++ b/include/rive/bones/skin.hpp
@@ -5,14 +5,12 @@ #include <stdio.h> #include <vector> -namespace rive -{ +namespace rive { class Tendon; class PathVertex; class Skinnable; - class Skin : public SkinBase - { + class Skin : public SkinBase { friend class Tendon; public:
diff --git a/include/rive/bones/skinnable.hpp b/include/rive/bones/skinnable.hpp index dea0f05..0cbce5a 100644 --- a/include/rive/bones/skinnable.hpp +++ b/include/rive/bones/skinnable.hpp
@@ -1,13 +1,11 @@ #ifndef _RIVE_SKINNABLE_HPP_ #define _RIVE_SKINNABLE_HPP_ -namespace rive -{ +namespace rive { class Skin; class Component; - class Skinnable - { + class Skinnable { friend class Skin; private:
diff --git a/include/rive/bones/tendon.hpp b/include/rive/bones/tendon.hpp index 0ba9666..499b612 100644 --- a/include/rive/bones/tendon.hpp +++ b/include/rive/bones/tendon.hpp
@@ -5,11 +5,9 @@ #include "rive/math/mat2d.hpp" #include <stdio.h> -namespace rive -{ +namespace rive { class Bone; - class Tendon : public TendonBase - { + class Tendon : public TendonBase { private: Mat2D m_InverseBind; Bone* m_Bone = nullptr;
diff --git a/include/rive/bones/weight.hpp b/include/rive/bones/weight.hpp index c2a2cd3..e7a1979 100644 --- a/include/rive/bones/weight.hpp +++ b/include/rive/bones/weight.hpp
@@ -4,10 +4,8 @@ #include "rive/math/vec2d.hpp" #include <stdio.h> -namespace rive -{ - class Weight : public WeightBase - { +namespace rive { + class Weight : public WeightBase { private: Vec2D m_Translation;
diff --git a/include/rive/command_path.hpp b/include/rive/command_path.hpp index d22ab33..3c2238f 100644 --- a/include/rive/command_path.hpp +++ b/include/rive/command_path.hpp
@@ -3,19 +3,13 @@ #include "rive/math/mat2d.hpp" -namespace rive -{ - enum class FillRule - { - nonZero, - evenOdd - }; +namespace rive { + enum class FillRule { nonZero, evenOdd }; class RenderPath; /// Abstract path used to build up commands used for rendering. - class CommandPath - { + class CommandPath { public: virtual ~CommandPath() {} virtual void reset() = 0; @@ -28,8 +22,7 @@ cubicTo(float ox, float oy, float ix, float iy, float x, float y) = 0; virtual void close() = 0; - void addRect(float x, float y, float width, float height) - { + void addRect(float x, float y, float width, float height) { moveTo(x, y); lineTo(x + width, y); lineTo(x + width, y + height);
diff --git a/include/rive/component.hpp b/include/rive/component.hpp index 33f65f1..0e488d2 100644 --- a/include/rive/component.hpp +++ b/include/rive/component.hpp
@@ -5,13 +5,11 @@ #include <vector> -namespace rive -{ +namespace rive { class ContainerComponent; class Artboard; - class Component : public ComponentBase - { + class Component : public ComponentBase { friend class Artboard; private: @@ -28,8 +26,7 @@ inline Artboard* artboard() const { return m_Artboard; } StatusCode onAddedDirty(CoreContext* context) override; inline ContainerComponent* parent() const { return m_Parent; } - const std::vector<Component*>& dependents() const - { + const std::vector<Component*>& dependents() const { return m_Dependents; } void addDependent(Component* component); @@ -44,12 +41,10 @@ unsigned int graphOrder() const { return m_GraphOrder; } bool addDirt(ComponentDirt value, bool recurse = false); - inline bool hasDirt(ComponentDirt flag) const - { + inline bool hasDirt(ComponentDirt flag) const { return (m_Dirt & flag) == flag; } - static inline bool hasDirt(ComponentDirt value, ComponentDirt flag) - { + static inline bool hasDirt(ComponentDirt value, ComponentDirt flag) { return (value & flag) != ComponentDirt::None; }
diff --git a/include/rive/component_dirt.hpp b/include/rive/component_dirt.hpp index 35a5179..cb56d97 100644 --- a/include/rive/component_dirt.hpp +++ b/include/rive/component_dirt.hpp
@@ -2,10 +2,8 @@ #define _RIVE_DIRTY_FLAGS_HPP_ #include <type_traits> -namespace rive -{ - enum class ComponentDirt : unsigned short - { +namespace rive { + enum class ComponentDirt : unsigned short { None = 0, Dependents = 1 << 0, @@ -50,37 +48,32 @@ }; inline constexpr ComponentDirt operator&(ComponentDirt lhs, - ComponentDirt rhs) - { + ComponentDirt rhs) { return static_cast<ComponentDirt>( static_cast<std::underlying_type<ComponentDirt>::type>(lhs) & static_cast<std::underlying_type<ComponentDirt>::type>(rhs)); } inline constexpr ComponentDirt operator^(ComponentDirt lhs, - ComponentDirt rhs) - { + ComponentDirt rhs) { return static_cast<ComponentDirt>( static_cast<std::underlying_type<ComponentDirt>::type>(lhs) ^ static_cast<std::underlying_type<ComponentDirt>::type>(rhs)); } inline constexpr ComponentDirt operator|(ComponentDirt lhs, - ComponentDirt rhs) - { + ComponentDirt rhs) { return static_cast<ComponentDirt>( static_cast<std::underlying_type<ComponentDirt>::type>(lhs) | static_cast<std::underlying_type<ComponentDirt>::type>(rhs)); } - inline constexpr ComponentDirt operator~(ComponentDirt rhs) - { + inline constexpr ComponentDirt operator~(ComponentDirt rhs) { return static_cast<ComponentDirt>( ~static_cast<std::underlying_type<ComponentDirt>::type>(rhs)); } - inline ComponentDirt& operator|=(ComponentDirt& lhs, ComponentDirt rhs) - { + inline ComponentDirt& operator|=(ComponentDirt& lhs, ComponentDirt rhs) { lhs = static_cast<ComponentDirt>( static_cast<std::underlying_type<ComponentDirt>::type>(lhs) | static_cast<std::underlying_type<ComponentDirt>::type>(rhs)); @@ -88,8 +81,7 @@ return lhs; } - inline ComponentDirt& operator&=(ComponentDirt& lhs, ComponentDirt rhs) - { + inline ComponentDirt& operator&=(ComponentDirt& lhs, ComponentDirt rhs) { lhs = static_cast<ComponentDirt>( static_cast<std::underlying_type<ComponentDirt>::type>(lhs) & static_cast<std::underlying_type<ComponentDirt>::type>(rhs)); @@ -97,8 +89,7 @@ return lhs; } - inline ComponentDirt& operator^=(ComponentDirt& lhs, ComponentDirt rhs) - { + inline ComponentDirt& operator^=(ComponentDirt& lhs, ComponentDirt rhs) { lhs = static_cast<ComponentDirt>( static_cast<std::underlying_type<ComponentDirt>::type>(lhs) ^ static_cast<std::underlying_type<ComponentDirt>::type>(rhs));
diff --git a/include/rive/constraints/constraint.hpp b/include/rive/constraints/constraint.hpp index 7d2b236..41baae4 100644 --- a/include/rive/constraints/constraint.hpp +++ b/include/rive/constraints/constraint.hpp
@@ -2,13 +2,11 @@ #define _RIVE_CONSTRAINT_HPP_ #include "rive/generated/constraints/constraint_base.hpp" #include <stdio.h> -namespace rive -{ +namespace rive { class TransformComponent; class Mat2D; - class Constraint : public ConstraintBase - { + class Constraint : public ConstraintBase { public: void strengthChanged() override; StatusCode onAddedClean(CoreContext* context) override;
diff --git a/include/rive/constraints/distance_constraint.hpp b/include/rive/constraints/distance_constraint.hpp index 4ce0518..dda0abc 100644 --- a/include/rive/constraints/distance_constraint.hpp +++ b/include/rive/constraints/distance_constraint.hpp
@@ -2,10 +2,8 @@ #define _RIVE_DISTANCE_CONSTRAINT_HPP_ #include "rive/generated/constraints/distance_constraint_base.hpp" #include <stdio.h> -namespace rive -{ - class DistanceConstraint : public DistanceConstraintBase - { +namespace rive { + class DistanceConstraint : public DistanceConstraintBase { public: void constrain(TransformComponent* component) override; };
diff --git a/include/rive/constraints/ik_constraint.hpp b/include/rive/constraints/ik_constraint.hpp index cc62fab..300d0cf 100644 --- a/include/rive/constraints/ik_constraint.hpp +++ b/include/rive/constraints/ik_constraint.hpp
@@ -5,14 +5,11 @@ #include "rive/math/transform_components.hpp" #include <vector> -namespace rive -{ +namespace rive { class Bone; - class IKConstraint : public IKConstraintBase - { + class IKConstraint : public IKConstraintBase { private: - struct BoneChainLink - { + struct BoneChainLink { int index; Bone* bone; float angle;
diff --git a/include/rive/constraints/rotation_constraint.hpp b/include/rive/constraints/rotation_constraint.hpp index a78eb8b..875516b 100644 --- a/include/rive/constraints/rotation_constraint.hpp +++ b/include/rive/constraints/rotation_constraint.hpp
@@ -3,10 +3,8 @@ #include "rive/generated/constraints/rotation_constraint_base.hpp" #include "rive/math/transform_components.hpp" #include <stdio.h> -namespace rive -{ - class RotationConstraint : public RotationConstraintBase - { +namespace rive { + class RotationConstraint : public RotationConstraintBase { private: TransformComponents m_ComponentsA; TransformComponents m_ComponentsB;
diff --git a/include/rive/constraints/scale_constraint.hpp b/include/rive/constraints/scale_constraint.hpp index 56c6500..3a52aa0 100644 --- a/include/rive/constraints/scale_constraint.hpp +++ b/include/rive/constraints/scale_constraint.hpp
@@ -3,10 +3,8 @@ #include "rive/generated/constraints/scale_constraint_base.hpp" #include "rive/math/transform_components.hpp" #include <stdio.h> -namespace rive -{ - class ScaleConstraint : public ScaleConstraintBase - { +namespace rive { + class ScaleConstraint : public ScaleConstraintBase { private: TransformComponents m_ComponentsA; TransformComponents m_ComponentsB;
diff --git a/include/rive/constraints/targeted_constraint.hpp b/include/rive/constraints/targeted_constraint.hpp index ba42f93..7fe9ddd 100644 --- a/include/rive/constraints/targeted_constraint.hpp +++ b/include/rive/constraints/targeted_constraint.hpp
@@ -2,11 +2,9 @@ #define _RIVE_TARGETED_CONSTRAINT_HPP_ #include "rive/generated/constraints/targeted_constraint_base.hpp" #include <stdio.h> -namespace rive -{ +namespace rive { class TransformComponent; - class TargetedConstraint : public TargetedConstraintBase - { + class TargetedConstraint : public TargetedConstraintBase { protected: TransformComponent* m_Target = nullptr;
diff --git a/include/rive/constraints/transform_component_constraint.hpp b/include/rive/constraints/transform_component_constraint.hpp index 1f9c388..13f9a62 100644 --- a/include/rive/constraints/transform_component_constraint.hpp +++ b/include/rive/constraints/transform_component_constraint.hpp
@@ -3,13 +3,11 @@ #include "rive/generated/constraints/transform_component_constraint_base.hpp" #include "rive/transform_space.hpp" #include <stdio.h> -namespace rive -{ - class TransformComponentConstraint : public TransformComponentConstraintBase - { +namespace rive { + class TransformComponentConstraint + : public TransformComponentConstraintBase { public: - TransformSpace minMaxSpace() const - { + TransformSpace minMaxSpace() const { return (TransformSpace)minMaxSpaceValue(); } };
diff --git a/include/rive/constraints/transform_component_constraint_y.hpp b/include/rive/constraints/transform_component_constraint_y.hpp index 51861c5..cc4427f 100644 --- a/include/rive/constraints/transform_component_constraint_y.hpp +++ b/include/rive/constraints/transform_component_constraint_y.hpp
@@ -2,11 +2,9 @@ #define _RIVE_TRANSFORM_COMPONENT_CONSTRAINT_Y_HPP_ #include "rive/generated/constraints/transform_component_constraint_y_base.hpp" #include <stdio.h> -namespace rive -{ +namespace rive { class TransformComponentConstraintY - : public TransformComponentConstraintYBase - { + : public TransformComponentConstraintYBase { public: }; } // namespace rive
diff --git a/include/rive/constraints/transform_constraint.hpp b/include/rive/constraints/transform_constraint.hpp index 3cdd8e9..47d65ad 100644 --- a/include/rive/constraints/transform_constraint.hpp +++ b/include/rive/constraints/transform_constraint.hpp
@@ -4,10 +4,8 @@ #include "rive/math/transform_components.hpp" #include <stdio.h> -namespace rive -{ - class TransformConstraint : public TransformConstraintBase - { +namespace rive { + class TransformConstraint : public TransformConstraintBase { private: TransformComponents m_ComponentsA; TransformComponents m_ComponentsB;
diff --git a/include/rive/constraints/transform_space_constraint.hpp b/include/rive/constraints/transform_space_constraint.hpp index 6cc39b4..0a05e42 100644 --- a/include/rive/constraints/transform_space_constraint.hpp +++ b/include/rive/constraints/transform_space_constraint.hpp
@@ -3,17 +3,13 @@ #include "rive/generated/constraints/transform_space_constraint_base.hpp" #include "rive/transform_space.hpp" #include <stdio.h> -namespace rive -{ - class TransformSpaceConstraint : public TransformSpaceConstraintBase - { +namespace rive { + class TransformSpaceConstraint : public TransformSpaceConstraintBase { public: - TransformSpace sourceSpace() const - { + TransformSpace sourceSpace() const { return (TransformSpace)sourceSpaceValue(); } - TransformSpace destSpace() const - { + TransformSpace destSpace() const { return (TransformSpace)destSpaceValue(); } };
diff --git a/include/rive/constraints/translation_constraint.hpp b/include/rive/constraints/translation_constraint.hpp index aee827e..c524fec 100644 --- a/include/rive/constraints/translation_constraint.hpp +++ b/include/rive/constraints/translation_constraint.hpp
@@ -2,10 +2,8 @@ #define _RIVE_TRANSLATION_CONSTRAINT_HPP_ #include "rive/generated/constraints/translation_constraint_base.hpp" #include <stdio.h> -namespace rive -{ - class TranslationConstraint : public TranslationConstraintBase - { +namespace rive { + class TranslationConstraint : public TranslationConstraintBase { public: void constrain(TransformComponent* component) override; };
diff --git a/include/rive/container_component.hpp b/include/rive/container_component.hpp index eecbc41..3cd5be0 100644 --- a/include/rive/container_component.hpp +++ b/include/rive/container_component.hpp
@@ -2,11 +2,8 @@ #define _RIVE_CONTAINER_COMPONENT_HPP_ #include "rive/generated/container_component_base.hpp" #include <vector> -namespace rive -{ - class ContainerComponent : public ContainerComponentBase - { - }; +namespace rive { + class ContainerComponent : public ContainerComponentBase {}; } // namespace rive #endif \ No newline at end of file
diff --git a/include/rive/core.hpp b/include/rive/core.hpp index 3210241..6996963 100644 --- a/include/rive/core.hpp +++ b/include/rive/core.hpp
@@ -5,12 +5,10 @@ #include "rive/status_code.hpp" #include <cassert> -namespace rive -{ +namespace rive { class CoreContext; class ImportStack; - class Core - { + class Core { public: static const int invalidPropertyKey = 0; virtual ~Core() {} @@ -19,12 +17,10 @@ virtual bool deserialize(uint16_t propertyKey, BinaryReader& reader) = 0; - template <typename T> inline bool is() const - { + template <typename T> inline bool is() const { return isTypeOf(T::typeKey); } - template <typename T> inline T* as() - { + template <typename T> inline T* as() { assert(is<T>()); return reinterpret_cast<T*>(this); } @@ -32,8 +28,7 @@ /// Make a shallow copy of the object. virtual Core* clone() const { return nullptr; } - template <typename T> inline const T* as() const - { + template <typename T> inline const T* as() const { assert(is<T>()); return reinterpret_cast<const T*>(this); } @@ -43,8 +38,7 @@ /// to look up objects referenced by id, but not assume that they in /// turn have resolved their references yet. Called during /// load/instance. - virtual StatusCode onAddedDirty(CoreContext* context) - { + virtual StatusCode onAddedDirty(CoreContext* context) { return StatusCode::Ok; } @@ -52,13 +46,11 @@ /// called. This is an opportunity to reference things referenced by /// dependencies. (A path should be able to find a Shape somewhere in /// its hierarchy, which may be multiple levels up). - virtual StatusCode onAddedClean(CoreContext* context) - { + virtual StatusCode onAddedClean(CoreContext* context) { return StatusCode::Ok; } - virtual StatusCode import(ImportStack& importStack) - { + virtual StatusCode import(ImportStack& importStack) { return StatusCode::Ok; } };
diff --git a/include/rive/core/binary_reader.hpp b/include/rive/core/binary_reader.hpp index 0122a9b..c8e6a8c 100644 --- a/include/rive/core/binary_reader.hpp +++ b/include/rive/core/binary_reader.hpp
@@ -5,10 +5,8 @@ #include <string> #include <vector> -namespace rive -{ - class BinaryReader - { +namespace rive { + class BinaryReader { private: uint8_t* m_Position; uint8_t* m_End;
diff --git a/include/rive/core/field_types/core_bool_type.hpp b/include/rive/core/field_types/core_bool_type.hpp index 21deee2..5a23b9b 100644 --- a/include/rive/core/field_types/core_bool_type.hpp +++ b/include/rive/core/field_types/core_bool_type.hpp
@@ -1,11 +1,9 @@ #ifndef _RIVE_CORE_BOOL_TYPE_HPP_ #define _RIVE_CORE_BOOL_TYPE_HPP_ -namespace rive -{ +namespace rive { class BinaryReader; - class CoreBoolType - { + class CoreBoolType { public: static const int id = 0; static bool deserialize(BinaryReader& reader);
diff --git a/include/rive/core/field_types/core_bytes_type.hpp b/include/rive/core/field_types/core_bytes_type.hpp index d4f4bb5..2530cf5 100644 --- a/include/rive/core/field_types/core_bytes_type.hpp +++ b/include/rive/core/field_types/core_bytes_type.hpp
@@ -4,11 +4,9 @@ #include <vector> #include <cstdint> -namespace rive -{ +namespace rive { class BinaryReader; - class CoreBytesType - { + class CoreBytesType { public: static const int id = 1; static std::vector<uint8_t> deserialize(BinaryReader& reader);
diff --git a/include/rive/core/field_types/core_color_type.hpp b/include/rive/core/field_types/core_color_type.hpp index d6c068e..ea9aa07 100644 --- a/include/rive/core/field_types/core_color_type.hpp +++ b/include/rive/core/field_types/core_color_type.hpp
@@ -1,11 +1,9 @@ #ifndef _RIVE_CORE_COLOR_TYPE_HPP_ #define _RIVE_CORE_COLOR_TYPE_HPP_ -namespace rive -{ +namespace rive { class BinaryReader; - class CoreColorType - { + class CoreColorType { public: static const int id = 3; static int deserialize(BinaryReader& reader);
diff --git a/include/rive/core/field_types/core_double_type.hpp b/include/rive/core/field_types/core_double_type.hpp index 224e091..e13be51 100644 --- a/include/rive/core/field_types/core_double_type.hpp +++ b/include/rive/core/field_types/core_double_type.hpp
@@ -1,11 +1,9 @@ #ifndef _RIVE_CORE_DOUBLE_TYPE_HPP_ #define _RIVE_CORE_DOUBLE_TYPE_HPP_ -namespace rive -{ +namespace rive { class BinaryReader; - class CoreDoubleType - { + class CoreDoubleType { public: static const int id = 2; static double deserialize(BinaryReader& reader);
diff --git a/include/rive/core/field_types/core_string_type.hpp b/include/rive/core/field_types/core_string_type.hpp index 3acc0e9..ae95810 100644 --- a/include/rive/core/field_types/core_string_type.hpp +++ b/include/rive/core/field_types/core_string_type.hpp
@@ -3,11 +3,9 @@ #include <string> -namespace rive -{ +namespace rive { class BinaryReader; - class CoreStringType - { + class CoreStringType { public: static const int id = 1; static std::string deserialize(BinaryReader& reader);
diff --git a/include/rive/core/field_types/core_uint_type.hpp b/include/rive/core/field_types/core_uint_type.hpp index 1d2260b..a2c90f7 100644 --- a/include/rive/core/field_types/core_uint_type.hpp +++ b/include/rive/core/field_types/core_uint_type.hpp
@@ -1,11 +1,9 @@ #ifndef _RIVE_CORE_UINT_TYPE_HPP_ #define _RIVE_CORE_UINT_TYPE_HPP_ -namespace rive -{ +namespace rive { class BinaryReader; - class CoreUintType - { + class CoreUintType { public: static const int id = 0; static unsigned int deserialize(BinaryReader& reader);
diff --git a/include/rive/core/reader.h b/include/rive/core/reader.h index 8bf67f2..e0458d6 100644 --- a/include/rive/core/reader.h +++ b/include/rive/core/reader.h
@@ -1,39 +1,34 @@ #include <stdlib.h> #include <string.h> -static bool is_big_endian(void) -{ - union - { - uint32_t i; - char c[4]; - } bint = {0x01020304}; +static bool is_big_endian(void) { + union { + uint32_t i; + char c[4]; + } bint = {0x01020304}; - return bint.c[0] == 1; + return bint.c[0] == 1; } /* Decode an unsigned int LEB128 at buf into r, returning the nr of bytes read. */ inline size_t -decode_uint_leb(const uint8_t* buf, const uint8_t* buf_end, uint64_t* r) -{ - const uint8_t* p = buf; - uint8_t shift = 0; - uint64_t result = 0; - uint8_t byte; +decode_uint_leb(const uint8_t* buf, const uint8_t* buf_end, uint64_t* r) { + const uint8_t* p = buf; + uint8_t shift = 0; + uint64_t result = 0; + uint8_t byte; - do - { - if (p >= buf_end) - { - return 0; - } - byte = *p++; - result |= ((uint64_t)(byte & 0x7f)) << shift; - shift += 7; - } while ((byte & 0x80) != 0); - *r = result; - return p - buf; + do { + if (p >= buf_end) { + return 0; + } + byte = *p++; + result |= ((uint64_t)(byte & 0x7f)) << shift; + shift += 7; + } while ((byte & 0x80) != 0); + *r = result; + return p - buf; } /* Decodes a string @@ -41,105 +36,80 @@ inline size_t decode_string(uint8_t str_len, const uint8_t* buf, const uint8_t* buf_end, - char* char_buf) -{ - // Return zero bytes read on buffer overflow - if (buf_end - buf < str_len) - { - return 0; - } - const uint8_t* p = buf; - for (int i = 0; i < str_len; i++) - { - char_buf[i] = *p++; - } - // Add the null terminator - char_buf[str_len] = '\0'; - return str_len; + char* char_buf) { + // Return zero bytes read on buffer overflow + if (buf_end - buf < str_len) { + return 0; + } + const uint8_t* p = buf; + for (int i = 0; i < str_len; i++) { + char_buf[i] = *p++; + } + // Add the null terminator + char_buf[str_len] = '\0'; + return str_len; } /* Decodes a double (8 bytes) */ inline size_t -decode_double(const uint8_t* buf, const uint8_t* buf_end, double* r) -{ - // Return zero bytes read on buffer overflow - if (buf_end - buf < ((unsigned) sizeof(double))) - { - return 0; - } - if (is_big_endian()) - { - uint8_t inverted[8] = {buf[7], - buf[6], - buf[5], - buf[4], - buf[3], - buf[2], - buf[1], - buf[0]}; - memcpy(r, inverted, sizeof(double)); - } - else - { - memcpy(r, buf, sizeof(double)); - } - return sizeof(double); +decode_double(const uint8_t* buf, const uint8_t* buf_end, double* r) { + // Return zero bytes read on buffer overflow + if (buf_end - buf < ((unsigned)sizeof(double))) { + return 0; + } + if (is_big_endian()) { + uint8_t inverted[8] = { + buf[7], buf[6], buf[5], buf[4], buf[3], buf[2], buf[1], buf[0]}; + memcpy(r, inverted, sizeof(double)); + } else { + memcpy(r, buf, sizeof(double)); + } + return sizeof(double); } /* Decodes a float (4 bytes) */ -inline size_t decode_float(const uint8_t* buf, const uint8_t* buf_end, float* r) -{ - // Return zero bytes read on buffer overflow - if (buf_end - buf < (unsigned) sizeof(float)) - { - return 0; - } - if (is_big_endian()) - { - uint8_t inverted[4] = {buf[3], buf[2], buf[1], buf[0]}; - memcpy(r, inverted, sizeof(float)); - } - else - { - memcpy(r, buf, sizeof(float)); - } - return sizeof(float); +inline size_t +decode_float(const uint8_t* buf, const uint8_t* buf_end, float* r) { + // Return zero bytes read on buffer overflow + if (buf_end - buf < (unsigned)sizeof(float)) { + return 0; + } + if (is_big_endian()) { + uint8_t inverted[4] = {buf[3], buf[2], buf[1], buf[0]}; + memcpy(r, inverted, sizeof(float)); + } else { + memcpy(r, buf, sizeof(float)); + } + return sizeof(float); } /* Decodes a single byte */ inline size_t -decode_uint_8(const uint8_t* buf, const uint8_t* buf_end, uint8_t* r) -{ - // Return zero bytes read on buffer overflow - if (buf_end - buf < (unsigned) sizeof(uint8_t)) - { - return 0; - } - memcpy(r, buf, sizeof(uint8_t)); - return sizeof(uint8_t); +decode_uint_8(const uint8_t* buf, const uint8_t* buf_end, uint8_t* r) { + // Return zero bytes read on buffer overflow + if (buf_end - buf < (unsigned)sizeof(uint8_t)) { + return 0; + } + memcpy(r, buf, sizeof(uint8_t)); + return sizeof(uint8_t); } /* Decodes a 32 bit unsigned integer. */ inline size_t -decode_uint_32(const uint8_t* buf, const uint8_t* buf_end, uint32_t* r) -{ - // Return zero bytes read on buffer overflow - if (buf_end - buf < (unsigned) sizeof(uint32_t)) - { - return 0; - } - if (is_big_endian()) - { - uint8_t inverted[4] = {buf[3], buf[2], buf[1], buf[0]}; - memcpy(r, inverted, sizeof(uint32_t)); - } - else - { - memcpy(r, buf, sizeof(uint32_t)); - } - return sizeof(uint32_t); +decode_uint_32(const uint8_t* buf, const uint8_t* buf_end, uint32_t* r) { + // Return zero bytes read on buffer overflow + if (buf_end - buf < (unsigned)sizeof(uint32_t)) { + return 0; + } + if (is_big_endian()) { + uint8_t inverted[4] = {buf[3], buf[2], buf[1], buf[0]}; + memcpy(r, inverted, sizeof(uint32_t)); + } else { + memcpy(r, buf, sizeof(uint32_t)); + } + return sizeof(uint32_t); }
diff --git a/include/rive/core_context.hpp b/include/rive/core_context.hpp index 9d3ac1b..1711f38 100644 --- a/include/rive/core_context.hpp +++ b/include/rive/core_context.hpp
@@ -1,11 +1,9 @@ #ifndef _RIVE_CORE_CONTEXT_HPP_ #define _RIVE_CORE_CONTEXT_HPP_ -namespace rive -{ +namespace rive { class Core; - class CoreContext - { + class CoreContext { public: virtual Core* resolve(int id) const = 0; };
diff --git a/include/rive/dependency_sorter.hpp b/include/rive/dependency_sorter.hpp index 1fa13b6..404dbc8 100644 --- a/include/rive/dependency_sorter.hpp +++ b/include/rive/dependency_sorter.hpp
@@ -4,11 +4,9 @@ #include <unordered_set> #include <vector> -namespace rive -{ +namespace rive { class Component; - class DependencySorter - { + class DependencySorter { private: std::unordered_set<Component*> m_Perm; std::unordered_set<Component*> m_Temp;
diff --git a/include/rive/draw_rules.hpp b/include/rive/draw_rules.hpp index da0b777..b8a82eb 100644 --- a/include/rive/draw_rules.hpp +++ b/include/rive/draw_rules.hpp
@@ -2,11 +2,9 @@ #define _RIVE_DRAW_RULES_HPP_ #include "rive/generated/draw_rules_base.hpp" #include <stdio.h> -namespace rive -{ +namespace rive { class DrawTarget; - class DrawRules : public DrawRulesBase - { + class DrawRules : public DrawRulesBase { private: DrawTarget* m_ActiveTarget = nullptr;
diff --git a/include/rive/draw_target.hpp b/include/rive/draw_target.hpp index 639db42..c647422 100644 --- a/include/rive/draw_target.hpp +++ b/include/rive/draw_target.hpp
@@ -5,12 +5,10 @@ #include "rive/generated/draw_target_base.hpp" #include <stdio.h> -namespace rive -{ +namespace rive { class Drawable; class Artboard; - class DrawTarget : public DrawTargetBase - { + class DrawTarget : public DrawTargetBase { friend class Artboard; private: @@ -25,8 +23,7 @@ StatusCode onAddedDirty(CoreContext* context) override; StatusCode onAddedClean(CoreContext* context) override; - DrawTargetPlacement placement() const - { + DrawTargetPlacement placement() const { return (DrawTargetPlacement)placementValue(); }
diff --git a/include/rive/draw_target_placement.hpp b/include/rive/draw_target_placement.hpp index 24e926c..1ff3edb 100644 --- a/include/rive/draw_target_placement.hpp +++ b/include/rive/draw_target_placement.hpp
@@ -1,11 +1,6 @@ #ifndef _RIVE_DRAW_TARGET_PLACEMENT_HPP_ #define _RIVE_DRAW_TARGET_PLACEMENT_HPP_ -namespace rive -{ - enum class DrawTargetPlacement : unsigned char - { - before = 0, - after = 1 - }; +namespace rive { + enum class DrawTargetPlacement : unsigned char { before = 0, after = 1 }; } #endif \ No newline at end of file
diff --git a/include/rive/drawable.hpp b/include/rive/drawable.hpp index e8817b6..d693baa 100644 --- a/include/rive/drawable.hpp +++ b/include/rive/drawable.hpp
@@ -4,14 +4,12 @@ #include "rive/renderer.hpp" #include <vector> -namespace rive -{ +namespace rive { class ClippingShape; class Artboard; class DrawRules; - class Drawable : public DrawableBase - { + class Drawable : public DrawableBase { friend class Artboard; private: @@ -27,13 +25,11 @@ bool clip(Renderer* renderer) const; virtual void draw(Renderer* renderer) = 0; void addClippingShape(ClippingShape* shape); - inline const std::vector<ClippingShape*>& clippingShapes() const - { + inline const std::vector<ClippingShape*>& clippingShapes() const { return m_ClippingShapes; } - const inline bool isHidden() const - { + const inline bool isHidden() const { // For now we have a single drawable flag, when we have more we can // make an actual enum for this. return (drawableFlags() & 0x1) == 0x1;
diff --git a/include/rive/file.hpp b/include/rive/file.hpp index c2449ce..b1ca2a5 100644 --- a/include/rive/file.hpp +++ b/include/rive/file.hpp
@@ -11,13 +11,11 @@ /// /// Default namespace for Rive Cpp runtime code. /// -namespace rive -{ +namespace rive { /// /// Tracks the success/failure result when importing a Rive file. /// - enum class ImportResult - { + enum class ImportResult { /// Indicates that a file's been successfully imported. success, /// Indicates that the Rive file is not supported by this runtime. @@ -29,8 +27,7 @@ /// /// A Rive file. /// - class File - { + class File { public: /// Major version number supported by the runtime. static const int majorVersion = 7;
diff --git a/include/rive/file_asset_resolver.hpp b/include/rive/file_asset_resolver.hpp index 2cc526f..64fdebb 100644 --- a/include/rive/file_asset_resolver.hpp +++ b/include/rive/file_asset_resolver.hpp
@@ -4,11 +4,9 @@ #include <cstdint> #include <vector> -namespace rive -{ +namespace rive { class FileAsset; - class FileAssetResolver - { + class FileAssetResolver { public: /// Expected to be overridden to find asset contents when not provided /// in band.
diff --git a/include/rive/generated/animation/animation_base.hpp b/include/rive/generated/animation/animation_base.hpp index b707a95..0624600 100644 --- a/include/rive/generated/animation/animation_base.hpp +++ b/include/rive/generated/animation/animation_base.hpp
@@ -3,10 +3,8 @@ #include <string> #include "rive/core.hpp" #include "rive/core/field_types/core_string_type.hpp" -namespace rive -{ - class AnimationBase : public Core - { +namespace rive { + class AnimationBase : public Core { protected: typedef Core Super; @@ -15,10 +13,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case AnimationBase::typeKey: return true; default: @@ -35,10 +31,8 @@ public: inline const std::string& name() const { return m_Name; } - void name(std::string value) - { - if (m_Name == value) - { + void name(std::string value) { + if (m_Name == value) { return; } m_Name = value; @@ -48,10 +42,8 @@ Core* clone() const override; void copy(const AnimationBase& object) { m_Name = object.m_Name; } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case namePropertyKey: m_Name = CoreStringType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/animation_state_base.hpp b/include/rive/generated/animation/animation_state_base.hpp index ade7a09..bd13a20 100644 --- a/include/rive/generated/animation/animation_state_base.hpp +++ b/include/rive/generated/animation/animation_state_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_ANIMATION_STATE_BASE_HPP_ #include "rive/animation/layer_state.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class AnimationStateBase : public LayerState - { +namespace rive { + class AnimationStateBase : public LayerState { protected: typedef LayerState Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case AnimationStateBase::typeKey: case LayerStateBase::typeKey: case StateMachineLayerComponentBase::typeKey: @@ -36,10 +32,8 @@ public: inline int animationId() const { return m_AnimationId; } - void animationId(int value) - { - if (m_AnimationId == value) - { + void animationId(int value) { + if (m_AnimationId == value) { return; } m_AnimationId = value; @@ -47,16 +41,13 @@ } Core* clone() const override; - void copy(const AnimationStateBase& object) - { + void copy(const AnimationStateBase& object) { m_AnimationId = object.m_AnimationId; LayerState::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case animationIdPropertyKey: m_AnimationId = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/any_state_base.hpp b/include/rive/generated/animation/any_state_base.hpp index 3f820c3..38b5a26 100644 --- a/include/rive/generated/animation/any_state_base.hpp +++ b/include/rive/generated/animation/any_state_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_ANY_STATE_BASE_HPP_ #define _RIVE_ANY_STATE_BASE_HPP_ #include "rive/animation/layer_state.hpp" -namespace rive -{ - class AnyStateBase : public LayerState - { +namespace rive { + class AnyStateBase : public LayerState { protected: typedef LayerState Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case AnyStateBase::typeKey: case LayerStateBase::typeKey: case StateMachineLayerComponentBase::typeKey:
diff --git a/include/rive/generated/animation/blend_animation_1d_base.hpp b/include/rive/generated/animation/blend_animation_1d_base.hpp index 71aaa89..400b620 100644 --- a/include/rive/generated/animation/blend_animation_1d_base.hpp +++ b/include/rive/generated/animation/blend_animation_1d_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_BLEND_ANIMATION1_DBASE_HPP_ #include "rive/animation/blend_animation.hpp" #include "rive/core/field_types/core_double_type.hpp" -namespace rive -{ - class BlendAnimation1DBase : public BlendAnimation - { +namespace rive { + class BlendAnimation1DBase : public BlendAnimation { protected: typedef BlendAnimation Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case BlendAnimation1DBase::typeKey: case BlendAnimationBase::typeKey: return true; @@ -35,10 +31,8 @@ public: inline float value() const { return m_Value; } - void value(float value) - { - if (m_Value == value) - { + void value(float value) { + if (m_Value == value) { return; } m_Value = value; @@ -46,16 +40,13 @@ } Core* clone() const override; - void copy(const BlendAnimation1DBase& object) - { + void copy(const BlendAnimation1DBase& object) { m_Value = object.m_Value; BlendAnimation::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case valuePropertyKey: m_Value = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/blend_animation_base.hpp b/include/rive/generated/animation/blend_animation_base.hpp index 4d6f425..874fd2e 100644 --- a/include/rive/generated/animation/blend_animation_base.hpp +++ b/include/rive/generated/animation/blend_animation_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_BLEND_ANIMATION_BASE_HPP_ #include "rive/core.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class BlendAnimationBase : public Core - { +namespace rive { + class BlendAnimationBase : public Core { protected: typedef Core Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case BlendAnimationBase::typeKey: return true; default: @@ -34,25 +30,20 @@ public: inline int animationId() const { return m_AnimationId; } - void animationId(int value) - { - if (m_AnimationId == value) - { + void animationId(int value) { + if (m_AnimationId == value) { return; } m_AnimationId = value; animationIdChanged(); } - void copy(const BlendAnimationBase& object) - { + void copy(const BlendAnimationBase& object) { m_AnimationId = object.m_AnimationId; } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case animationIdPropertyKey: m_AnimationId = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/blend_animation_direct_base.hpp b/include/rive/generated/animation/blend_animation_direct_base.hpp index 98b89e2..b0f3287 100644 --- a/include/rive/generated/animation/blend_animation_direct_base.hpp +++ b/include/rive/generated/animation/blend_animation_direct_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_BLEND_ANIMATION_DIRECT_BASE_HPP_ #include "rive/animation/blend_animation.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class BlendAnimationDirectBase : public BlendAnimation - { +namespace rive { + class BlendAnimationDirectBase : public BlendAnimation { protected: typedef BlendAnimation Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case BlendAnimationDirectBase::typeKey: case BlendAnimationBase::typeKey: return true; @@ -35,10 +31,8 @@ public: inline int inputId() const { return m_InputId; } - void inputId(int value) - { - if (m_InputId == value) - { + void inputId(int value) { + if (m_InputId == value) { return; } m_InputId = value; @@ -46,16 +40,13 @@ } Core* clone() const override; - void copy(const BlendAnimationDirectBase& object) - { + void copy(const BlendAnimationDirectBase& object) { m_InputId = object.m_InputId; BlendAnimation::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case inputIdPropertyKey: m_InputId = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/blend_state_1d_base.hpp b/include/rive/generated/animation/blend_state_1d_base.hpp index eaae200..cf5109e 100644 --- a/include/rive/generated/animation/blend_state_1d_base.hpp +++ b/include/rive/generated/animation/blend_state_1d_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_BLEND_STATE1_DBASE_HPP_ #include "rive/animation/blend_state.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class BlendState1DBase : public BlendState - { +namespace rive { + class BlendState1DBase : public BlendState { protected: typedef BlendState Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case BlendState1DBase::typeKey: case BlendStateBase::typeKey: case LayerStateBase::typeKey: @@ -37,10 +33,8 @@ public: inline int inputId() const { return m_InputId; } - void inputId(int value) - { - if (m_InputId == value) - { + void inputId(int value) { + if (m_InputId == value) { return; } m_InputId = value; @@ -48,16 +42,13 @@ } Core* clone() const override; - void copy(const BlendState1DBase& object) - { + void copy(const BlendState1DBase& object) { m_InputId = object.m_InputId; BlendState::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case inputIdPropertyKey: m_InputId = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/blend_state_base.hpp b/include/rive/generated/animation/blend_state_base.hpp index 68a85b5..3f72e17 100644 --- a/include/rive/generated/animation/blend_state_base.hpp +++ b/include/rive/generated/animation/blend_state_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_BLEND_STATE_BASE_HPP_ #define _RIVE_BLEND_STATE_BASE_HPP_ #include "rive/animation/layer_state.hpp" -namespace rive -{ - class BlendStateBase : public LayerState - { +namespace rive { + class BlendStateBase : public LayerState { protected: typedef LayerState Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case BlendStateBase::typeKey: case LayerStateBase::typeKey: case StateMachineLayerComponentBase::typeKey:
diff --git a/include/rive/generated/animation/blend_state_direct_base.hpp b/include/rive/generated/animation/blend_state_direct_base.hpp index b05e611..c4ea5e2 100644 --- a/include/rive/generated/animation/blend_state_direct_base.hpp +++ b/include/rive/generated/animation/blend_state_direct_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_BLEND_STATE_DIRECT_BASE_HPP_ #define _RIVE_BLEND_STATE_DIRECT_BASE_HPP_ #include "rive/animation/blend_state.hpp" -namespace rive -{ - class BlendStateDirectBase : public BlendState - { +namespace rive { + class BlendStateDirectBase : public BlendState { protected: typedef BlendState Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case BlendStateDirectBase::typeKey: case BlendStateBase::typeKey: case LayerStateBase::typeKey:
diff --git a/include/rive/generated/animation/blend_state_transition_base.hpp b/include/rive/generated/animation/blend_state_transition_base.hpp index 1ea1cb3..5b89fd5 100644 --- a/include/rive/generated/animation/blend_state_transition_base.hpp +++ b/include/rive/generated/animation/blend_state_transition_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_BLEND_STATE_TRANSITION_BASE_HPP_ #include "rive/animation/state_transition.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class BlendStateTransitionBase : public StateTransition - { +namespace rive { + class BlendStateTransitionBase : public StateTransition { protected: typedef StateTransition Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case BlendStateTransitionBase::typeKey: case StateTransitionBase::typeKey: case StateMachineLayerComponentBase::typeKey: @@ -35,14 +31,11 @@ int m_ExitBlendAnimationId = -1; public: - inline int exitBlendAnimationId() const - { + inline int exitBlendAnimationId() const { return m_ExitBlendAnimationId; } - void exitBlendAnimationId(int value) - { - if (m_ExitBlendAnimationId == value) - { + void exitBlendAnimationId(int value) { + if (m_ExitBlendAnimationId == value) { return; } m_ExitBlendAnimationId = value; @@ -50,16 +43,13 @@ } Core* clone() const override; - void copy(const BlendStateTransitionBase& object) - { + void copy(const BlendStateTransitionBase& object) { m_ExitBlendAnimationId = object.m_ExitBlendAnimationId; StateTransition::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case exitBlendAnimationIdPropertyKey: m_ExitBlendAnimationId = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/cubic_interpolator_base.hpp b/include/rive/generated/animation/cubic_interpolator_base.hpp index e2d6bac..8f17427 100644 --- a/include/rive/generated/animation/cubic_interpolator_base.hpp +++ b/include/rive/generated/animation/cubic_interpolator_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_CUBIC_INTERPOLATOR_BASE_HPP_ #include "rive/core.hpp" #include "rive/core/field_types/core_double_type.hpp" -namespace rive -{ - class CubicInterpolatorBase : public Core - { +namespace rive { + class CubicInterpolatorBase : public Core { protected: typedef Core Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case CubicInterpolatorBase::typeKey: return true; default: @@ -40,10 +36,8 @@ public: inline float x1() const { return m_X1; } - void x1(float value) - { - if (m_X1 == value) - { + void x1(float value) { + if (m_X1 == value) { return; } m_X1 = value; @@ -51,10 +45,8 @@ } inline float y1() const { return m_Y1; } - void y1(float value) - { - if (m_Y1 == value) - { + void y1(float value) { + if (m_Y1 == value) { return; } m_Y1 = value; @@ -62,10 +54,8 @@ } inline float x2() const { return m_X2; } - void x2(float value) - { - if (m_X2 == value) - { + void x2(float value) { + if (m_X2 == value) { return; } m_X2 = value; @@ -73,10 +63,8 @@ } inline float y2() const { return m_Y2; } - void y2(float value) - { - if (m_Y2 == value) - { + void y2(float value) { + if (m_Y2 == value) { return; } m_Y2 = value; @@ -84,18 +72,15 @@ } Core* clone() const override; - void copy(const CubicInterpolatorBase& object) - { + void copy(const CubicInterpolatorBase& object) { m_X1 = object.m_X1; m_Y1 = object.m_Y1; m_X2 = object.m_X2; m_Y2 = object.m_Y2; } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case x1PropertyKey: m_X1 = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/entry_state_base.hpp b/include/rive/generated/animation/entry_state_base.hpp index e81cf3d..c5a250f 100644 --- a/include/rive/generated/animation/entry_state_base.hpp +++ b/include/rive/generated/animation/entry_state_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_ENTRY_STATE_BASE_HPP_ #define _RIVE_ENTRY_STATE_BASE_HPP_ #include "rive/animation/layer_state.hpp" -namespace rive -{ - class EntryStateBase : public LayerState - { +namespace rive { + class EntryStateBase : public LayerState { protected: typedef LayerState Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case EntryStateBase::typeKey: case LayerStateBase::typeKey: case StateMachineLayerComponentBase::typeKey:
diff --git a/include/rive/generated/animation/exit_state_base.hpp b/include/rive/generated/animation/exit_state_base.hpp index 40c93f5..d56bbbb 100644 --- a/include/rive/generated/animation/exit_state_base.hpp +++ b/include/rive/generated/animation/exit_state_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_EXIT_STATE_BASE_HPP_ #define _RIVE_EXIT_STATE_BASE_HPP_ #include "rive/animation/layer_state.hpp" -namespace rive -{ - class ExitStateBase : public LayerState - { +namespace rive { + class ExitStateBase : public LayerState { protected: typedef LayerState Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case ExitStateBase::typeKey: case LayerStateBase::typeKey: case StateMachineLayerComponentBase::typeKey:
diff --git a/include/rive/generated/animation/keyed_object_base.hpp b/include/rive/generated/animation/keyed_object_base.hpp index af90d78..4b88558 100644 --- a/include/rive/generated/animation/keyed_object_base.hpp +++ b/include/rive/generated/animation/keyed_object_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_KEYED_OBJECT_BASE_HPP_ #include "rive/core.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class KeyedObjectBase : public Core - { +namespace rive { + class KeyedObjectBase : public Core { protected: typedef Core Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case KeyedObjectBase::typeKey: return true; default: @@ -34,10 +30,8 @@ public: inline int objectId() const { return m_ObjectId; } - void objectId(int value) - { - if (m_ObjectId == value) - { + void objectId(int value) { + if (m_ObjectId == value) { return; } m_ObjectId = value; @@ -45,15 +39,12 @@ } Core* clone() const override; - void copy(const KeyedObjectBase& object) - { + void copy(const KeyedObjectBase& object) { m_ObjectId = object.m_ObjectId; } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case objectIdPropertyKey: m_ObjectId = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/keyed_property_base.hpp b/include/rive/generated/animation/keyed_property_base.hpp index 68deaf0..1114f5d 100644 --- a/include/rive/generated/animation/keyed_property_base.hpp +++ b/include/rive/generated/animation/keyed_property_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_KEYED_PROPERTY_BASE_HPP_ #include "rive/core.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class KeyedPropertyBase : public Core - { +namespace rive { + class KeyedPropertyBase : public Core { protected: typedef Core Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case KeyedPropertyBase::typeKey: return true; default: @@ -34,10 +30,8 @@ public: inline int propertyKey() const { return m_PropertyKey; } - void propertyKey(int value) - { - if (m_PropertyKey == value) - { + void propertyKey(int value) { + if (m_PropertyKey == value) { return; } m_PropertyKey = value; @@ -45,15 +39,12 @@ } Core* clone() const override; - void copy(const KeyedPropertyBase& object) - { + void copy(const KeyedPropertyBase& object) { m_PropertyKey = object.m_PropertyKey; } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case propertyKeyPropertyKey: m_PropertyKey = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/keyframe_base.hpp b/include/rive/generated/animation/keyframe_base.hpp index 736ada8..53e2f46 100644 --- a/include/rive/generated/animation/keyframe_base.hpp +++ b/include/rive/generated/animation/keyframe_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_KEY_FRAME_BASE_HPP_ #include "rive/core.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class KeyFrameBase : public Core - { +namespace rive { + class KeyFrameBase : public Core { protected: typedef Core Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case KeyFrameBase::typeKey: return true; default: @@ -38,10 +34,8 @@ public: inline int frame() const { return m_Frame; } - void frame(int value) - { - if (m_Frame == value) - { + void frame(int value) { + if (m_Frame == value) { return; } m_Frame = value; @@ -49,10 +43,8 @@ } inline int interpolationType() const { return m_InterpolationType; } - void interpolationType(int value) - { - if (m_InterpolationType == value) - { + void interpolationType(int value) { + if (m_InterpolationType == value) { return; } m_InterpolationType = value; @@ -60,27 +52,22 @@ } inline int interpolatorId() const { return m_InterpolatorId; } - void interpolatorId(int value) - { - if (m_InterpolatorId == value) - { + void interpolatorId(int value) { + if (m_InterpolatorId == value) { return; } m_InterpolatorId = value; interpolatorIdChanged(); } - void copy(const KeyFrameBase& object) - { + void copy(const KeyFrameBase& object) { m_Frame = object.m_Frame; m_InterpolationType = object.m_InterpolationType; m_InterpolatorId = object.m_InterpolatorId; } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case framePropertyKey: m_Frame = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/keyframe_bool_base.hpp b/include/rive/generated/animation/keyframe_bool_base.hpp index d759440..f50f08c 100644 --- a/include/rive/generated/animation/keyframe_bool_base.hpp +++ b/include/rive/generated/animation/keyframe_bool_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_KEY_FRAME_BOOL_BASE_HPP_ #include "rive/animation/keyframe.hpp" #include "rive/core/field_types/core_bool_type.hpp" -namespace rive -{ - class KeyFrameBoolBase : public KeyFrame - { +namespace rive { + class KeyFrameBoolBase : public KeyFrame { protected: typedef KeyFrame Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case KeyFrameBoolBase::typeKey: case KeyFrameBase::typeKey: return true; @@ -35,10 +31,8 @@ public: inline bool value() const { return m_Value; } - void value(bool value) - { - if (m_Value == value) - { + void value(bool value) { + if (m_Value == value) { return; } m_Value = value; @@ -46,16 +40,13 @@ } Core* clone() const override; - void copy(const KeyFrameBoolBase& object) - { + void copy(const KeyFrameBoolBase& object) { m_Value = object.m_Value; KeyFrame::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case valuePropertyKey: m_Value = CoreBoolType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/keyframe_color_base.hpp b/include/rive/generated/animation/keyframe_color_base.hpp index 2528960..5cfd8e7 100644 --- a/include/rive/generated/animation/keyframe_color_base.hpp +++ b/include/rive/generated/animation/keyframe_color_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_KEY_FRAME_COLOR_BASE_HPP_ #include "rive/animation/keyframe.hpp" #include "rive/core/field_types/core_color_type.hpp" -namespace rive -{ - class KeyFrameColorBase : public KeyFrame - { +namespace rive { + class KeyFrameColorBase : public KeyFrame { protected: typedef KeyFrame Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case KeyFrameColorBase::typeKey: case KeyFrameBase::typeKey: return true; @@ -35,10 +31,8 @@ public: inline int value() const { return m_Value; } - void value(int value) - { - if (m_Value == value) - { + void value(int value) { + if (m_Value == value) { return; } m_Value = value; @@ -46,16 +40,13 @@ } Core* clone() const override; - void copy(const KeyFrameColorBase& object) - { + void copy(const KeyFrameColorBase& object) { m_Value = object.m_Value; KeyFrame::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case valuePropertyKey: m_Value = CoreColorType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/keyframe_double_base.hpp b/include/rive/generated/animation/keyframe_double_base.hpp index cde2f3b..c6682a7 100644 --- a/include/rive/generated/animation/keyframe_double_base.hpp +++ b/include/rive/generated/animation/keyframe_double_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_KEY_FRAME_DOUBLE_BASE_HPP_ #include "rive/animation/keyframe.hpp" #include "rive/core/field_types/core_double_type.hpp" -namespace rive -{ - class KeyFrameDoubleBase : public KeyFrame - { +namespace rive { + class KeyFrameDoubleBase : public KeyFrame { protected: typedef KeyFrame Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case KeyFrameDoubleBase::typeKey: case KeyFrameBase::typeKey: return true; @@ -35,10 +31,8 @@ public: inline float value() const { return m_Value; } - void value(float value) - { - if (m_Value == value) - { + void value(float value) { + if (m_Value == value) { return; } m_Value = value; @@ -46,16 +40,13 @@ } Core* clone() const override; - void copy(const KeyFrameDoubleBase& object) - { + void copy(const KeyFrameDoubleBase& object) { m_Value = object.m_Value; KeyFrame::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case valuePropertyKey: m_Value = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/keyframe_id_base.hpp b/include/rive/generated/animation/keyframe_id_base.hpp index c6dc0c3..479848a 100644 --- a/include/rive/generated/animation/keyframe_id_base.hpp +++ b/include/rive/generated/animation/keyframe_id_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_KEY_FRAME_ID_BASE_HPP_ #include "rive/animation/keyframe.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class KeyFrameIdBase : public KeyFrame - { +namespace rive { + class KeyFrameIdBase : public KeyFrame { protected: typedef KeyFrame Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case KeyFrameIdBase::typeKey: case KeyFrameBase::typeKey: return true; @@ -35,10 +31,8 @@ public: inline int value() const { return m_Value; } - void value(int value) - { - if (m_Value == value) - { + void value(int value) { + if (m_Value == value) { return; } m_Value = value; @@ -46,16 +40,13 @@ } Core* clone() const override; - void copy(const KeyFrameIdBase& object) - { + void copy(const KeyFrameIdBase& object) { m_Value = object.m_Value; KeyFrame::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case valuePropertyKey: m_Value = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/layer_state_base.hpp b/include/rive/generated/animation/layer_state_base.hpp index 47f0780..44e1334 100644 --- a/include/rive/generated/animation/layer_state_base.hpp +++ b/include/rive/generated/animation/layer_state_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_LAYER_STATE_BASE_HPP_ #define _RIVE_LAYER_STATE_BASE_HPP_ #include "rive/animation/state_machine_layer_component.hpp" -namespace rive -{ - class LayerStateBase : public StateMachineLayerComponent - { +namespace rive { + class LayerStateBase : public StateMachineLayerComponent { protected: typedef StateMachineLayerComponent Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case LayerStateBase::typeKey: case StateMachineLayerComponentBase::typeKey: return true;
diff --git a/include/rive/generated/animation/linear_animation_base.hpp b/include/rive/generated/animation/linear_animation_base.hpp index f8ce638..925068e 100644 --- a/include/rive/generated/animation/linear_animation_base.hpp +++ b/include/rive/generated/animation/linear_animation_base.hpp
@@ -4,10 +4,8 @@ #include "rive/core/field_types/core_bool_type.hpp" #include "rive/core/field_types/core_double_type.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class LinearAnimationBase : public Animation - { +namespace rive { + class LinearAnimationBase : public Animation { protected: typedef Animation Super; @@ -16,10 +14,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case LinearAnimationBase::typeKey: case AnimationBase::typeKey: return true; @@ -49,10 +45,8 @@ public: inline int fps() const { return m_Fps; } - void fps(int value) - { - if (m_Fps == value) - { + void fps(int value) { + if (m_Fps == value) { return; } m_Fps = value; @@ -60,10 +54,8 @@ } inline int duration() const { return m_Duration; } - void duration(int value) - { - if (m_Duration == value) - { + void duration(int value) { + if (m_Duration == value) { return; } m_Duration = value; @@ -71,10 +63,8 @@ } inline float speed() const { return m_Speed; } - void speed(float value) - { - if (m_Speed == value) - { + void speed(float value) { + if (m_Speed == value) { return; } m_Speed = value; @@ -82,10 +72,8 @@ } inline int loopValue() const { return m_LoopValue; } - void loopValue(int value) - { - if (m_LoopValue == value) - { + void loopValue(int value) { + if (m_LoopValue == value) { return; } m_LoopValue = value; @@ -93,10 +81,8 @@ } inline int workStart() const { return m_WorkStart; } - void workStart(int value) - { - if (m_WorkStart == value) - { + void workStart(int value) { + if (m_WorkStart == value) { return; } m_WorkStart = value; @@ -104,10 +90,8 @@ } inline int workEnd() const { return m_WorkEnd; } - void workEnd(int value) - { - if (m_WorkEnd == value) - { + void workEnd(int value) { + if (m_WorkEnd == value) { return; } m_WorkEnd = value; @@ -115,10 +99,8 @@ } inline bool enableWorkArea() const { return m_EnableWorkArea; } - void enableWorkArea(bool value) - { - if (m_EnableWorkArea == value) - { + void enableWorkArea(bool value) { + if (m_EnableWorkArea == value) { return; } m_EnableWorkArea = value; @@ -126,8 +108,7 @@ } Core* clone() const override; - void copy(const LinearAnimationBase& object) - { + void copy(const LinearAnimationBase& object) { m_Fps = object.m_Fps; m_Duration = object.m_Duration; m_Speed = object.m_Speed; @@ -138,10 +119,8 @@ Animation::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case fpsPropertyKey: m_Fps = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/nested_linear_animation_base.hpp b/include/rive/generated/animation/nested_linear_animation_base.hpp index 0cfb734..991bc17 100644 --- a/include/rive/generated/animation/nested_linear_animation_base.hpp +++ b/include/rive/generated/animation/nested_linear_animation_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_NESTED_LINEAR_ANIMATION_BASE_HPP_ #include "rive/core/field_types/core_double_type.hpp" #include "rive/nested_animation.hpp" -namespace rive -{ - class NestedLinearAnimationBase : public NestedAnimation - { +namespace rive { + class NestedLinearAnimationBase : public NestedAnimation { protected: typedef NestedAnimation Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case NestedLinearAnimationBase::typeKey: case NestedAnimationBase::typeKey: case ComponentBase::typeKey: @@ -36,26 +32,21 @@ public: inline float mix() const { return m_Mix; } - void mix(float value) - { - if (m_Mix == value) - { + void mix(float value) { + if (m_Mix == value) { return; } m_Mix = value; mixChanged(); } - void copy(const NestedLinearAnimationBase& object) - { + void copy(const NestedLinearAnimationBase& object) { m_Mix = object.m_Mix; NestedAnimation::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case mixPropertyKey: m_Mix = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/nested_remap_animation_base.hpp b/include/rive/generated/animation/nested_remap_animation_base.hpp index cb1aa7a..0ab3a86 100644 --- a/include/rive/generated/animation/nested_remap_animation_base.hpp +++ b/include/rive/generated/animation/nested_remap_animation_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_NESTED_REMAP_ANIMATION_BASE_HPP_ #include "rive/animation/nested_linear_animation.hpp" #include "rive/core/field_types/core_double_type.hpp" -namespace rive -{ - class NestedRemapAnimationBase : public NestedLinearAnimation - { +namespace rive { + class NestedRemapAnimationBase : public NestedLinearAnimation { protected: typedef NestedLinearAnimation Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case NestedRemapAnimationBase::typeKey: case NestedLinearAnimationBase::typeKey: case NestedAnimationBase::typeKey: @@ -37,10 +33,8 @@ public: inline float time() const { return m_Time; } - void time(float value) - { - if (m_Time == value) - { + void time(float value) { + if (m_Time == value) { return; } m_Time = value; @@ -48,16 +42,13 @@ } Core* clone() const override; - void copy(const NestedRemapAnimationBase& object) - { + void copy(const NestedRemapAnimationBase& object) { m_Time = object.m_Time; NestedLinearAnimation::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case timePropertyKey: m_Time = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/nested_simple_animation_base.hpp b/include/rive/generated/animation/nested_simple_animation_base.hpp index 8a20588..009f417 100644 --- a/include/rive/generated/animation/nested_simple_animation_base.hpp +++ b/include/rive/generated/animation/nested_simple_animation_base.hpp
@@ -3,10 +3,8 @@ #include "rive/animation/nested_linear_animation.hpp" #include "rive/core/field_types/core_bool_type.hpp" #include "rive/core/field_types/core_double_type.hpp" -namespace rive -{ - class NestedSimpleAnimationBase : public NestedLinearAnimation - { +namespace rive { + class NestedSimpleAnimationBase : public NestedLinearAnimation { protected: typedef NestedLinearAnimation Super; @@ -15,10 +13,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case NestedSimpleAnimationBase::typeKey: case NestedLinearAnimationBase::typeKey: case NestedAnimationBase::typeKey: @@ -40,10 +36,8 @@ public: inline float speed() const { return m_Speed; } - void speed(float value) - { - if (m_Speed == value) - { + void speed(float value) { + if (m_Speed == value) { return; } m_Speed = value; @@ -51,10 +45,8 @@ } inline bool isPlaying() const { return m_IsPlaying; } - void isPlaying(bool value) - { - if (m_IsPlaying == value) - { + void isPlaying(bool value) { + if (m_IsPlaying == value) { return; } m_IsPlaying = value; @@ -62,17 +54,14 @@ } Core* clone() const override; - void copy(const NestedSimpleAnimationBase& object) - { + void copy(const NestedSimpleAnimationBase& object) { m_Speed = object.m_Speed; m_IsPlaying = object.m_IsPlaying; NestedLinearAnimation::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case speedPropertyKey: m_Speed = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/nested_state_machine_base.hpp b/include/rive/generated/animation/nested_state_machine_base.hpp index 8c32ba6..25de306 100644 --- a/include/rive/generated/animation/nested_state_machine_base.hpp +++ b/include/rive/generated/animation/nested_state_machine_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_NESTED_STATE_MACHINE_BASE_HPP_ #define _RIVE_NESTED_STATE_MACHINE_BASE_HPP_ #include "rive/nested_animation.hpp" -namespace rive -{ - class NestedStateMachineBase : public NestedAnimation - { +namespace rive { + class NestedStateMachineBase : public NestedAnimation { protected: typedef NestedAnimation Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case NestedStateMachineBase::typeKey: case NestedAnimationBase::typeKey: case ComponentBase::typeKey:
diff --git a/include/rive/generated/animation/state_machine_base.hpp b/include/rive/generated/animation/state_machine_base.hpp index 0c7f5f1..ab5aff0 100644 --- a/include/rive/generated/animation/state_machine_base.hpp +++ b/include/rive/generated/animation/state_machine_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_STATE_MACHINE_BASE_HPP_ #define _RIVE_STATE_MACHINE_BASE_HPP_ #include "rive/animation/animation.hpp" -namespace rive -{ - class StateMachineBase : public Animation - { +namespace rive { + class StateMachineBase : public Animation { protected: typedef Animation Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case StateMachineBase::typeKey: case AnimationBase::typeKey: return true;
diff --git a/include/rive/generated/animation/state_machine_bool_base.hpp b/include/rive/generated/animation/state_machine_bool_base.hpp index 8083253..81d4a2c 100644 --- a/include/rive/generated/animation/state_machine_bool_base.hpp +++ b/include/rive/generated/animation/state_machine_bool_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_STATE_MACHINE_BOOL_BASE_HPP_ #include "rive/animation/state_machine_input.hpp" #include "rive/core/field_types/core_bool_type.hpp" -namespace rive -{ - class StateMachineBoolBase : public StateMachineInput - { +namespace rive { + class StateMachineBoolBase : public StateMachineInput { protected: typedef StateMachineInput Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case StateMachineBoolBase::typeKey: case StateMachineInputBase::typeKey: case StateMachineComponentBase::typeKey: @@ -36,10 +32,8 @@ public: inline bool value() const { return m_Value; } - void value(bool value) - { - if (m_Value == value) - { + void value(bool value) { + if (m_Value == value) { return; } m_Value = value; @@ -47,16 +41,13 @@ } Core* clone() const override; - void copy(const StateMachineBoolBase& object) - { + void copy(const StateMachineBoolBase& object) { m_Value = object.m_Value; StateMachineInput::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case valuePropertyKey: m_Value = CoreBoolType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/state_machine_component_base.hpp b/include/rive/generated/animation/state_machine_component_base.hpp index cc857d7..63e4521 100644 --- a/include/rive/generated/animation/state_machine_component_base.hpp +++ b/include/rive/generated/animation/state_machine_component_base.hpp
@@ -3,10 +3,8 @@ #include <string> #include "rive/core.hpp" #include "rive/core/field_types/core_string_type.hpp" -namespace rive -{ - class StateMachineComponentBase : public Core - { +namespace rive { + class StateMachineComponentBase : public Core { protected: typedef Core Super; @@ -15,10 +13,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case StateMachineComponentBase::typeKey: return true; default: @@ -35,25 +31,20 @@ public: inline const std::string& name() const { return m_Name; } - void name(std::string value) - { - if (m_Name == value) - { + void name(std::string value) { + if (m_Name == value) { return; } m_Name = value; nameChanged(); } - void copy(const StateMachineComponentBase& object) - { + void copy(const StateMachineComponentBase& object) { m_Name = object.m_Name; } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case namePropertyKey: m_Name = CoreStringType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/state_machine_input_base.hpp b/include/rive/generated/animation/state_machine_input_base.hpp index ad814ae..745c6bb 100644 --- a/include/rive/generated/animation/state_machine_input_base.hpp +++ b/include/rive/generated/animation/state_machine_input_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_STATE_MACHINE_INPUT_BASE_HPP_ #define _RIVE_STATE_MACHINE_INPUT_BASE_HPP_ #include "rive/animation/state_machine_component.hpp" -namespace rive -{ - class StateMachineInputBase : public StateMachineComponent - { +namespace rive { + class StateMachineInputBase : public StateMachineComponent { protected: typedef StateMachineComponent Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case StateMachineInputBase::typeKey: case StateMachineComponentBase::typeKey: return true;
diff --git a/include/rive/generated/animation/state_machine_layer_base.hpp b/include/rive/generated/animation/state_machine_layer_base.hpp index b557ae7..00486ac 100644 --- a/include/rive/generated/animation/state_machine_layer_base.hpp +++ b/include/rive/generated/animation/state_machine_layer_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_STATE_MACHINE_LAYER_BASE_HPP_ #define _RIVE_STATE_MACHINE_LAYER_BASE_HPP_ #include "rive/animation/state_machine_component.hpp" -namespace rive -{ - class StateMachineLayerBase : public StateMachineComponent - { +namespace rive { + class StateMachineLayerBase : public StateMachineComponent { protected: typedef StateMachineComponent Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case StateMachineLayerBase::typeKey: case StateMachineComponentBase::typeKey: return true;
diff --git a/include/rive/generated/animation/state_machine_layer_component_base.hpp b/include/rive/generated/animation/state_machine_layer_component_base.hpp index 17b4b9b..604b24b 100644 --- a/include/rive/generated/animation/state_machine_layer_component_base.hpp +++ b/include/rive/generated/animation/state_machine_layer_component_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_STATE_MACHINE_LAYER_COMPONENT_BASE_HPP_ #define _RIVE_STATE_MACHINE_LAYER_COMPONENT_BASE_HPP_ #include "rive/core.hpp" -namespace rive -{ - class StateMachineLayerComponentBase : public Core - { +namespace rive { + class StateMachineLayerComponentBase : public Core { protected: typedef Core Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case StateMachineLayerComponentBase::typeKey: return true; default: @@ -28,10 +24,8 @@ void copy(const StateMachineLayerComponentBase& object) {} - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { } return false; }
diff --git a/include/rive/generated/animation/state_machine_number_base.hpp b/include/rive/generated/animation/state_machine_number_base.hpp index 605bd38..abd216c 100644 --- a/include/rive/generated/animation/state_machine_number_base.hpp +++ b/include/rive/generated/animation/state_machine_number_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_STATE_MACHINE_NUMBER_BASE_HPP_ #include "rive/animation/state_machine_input.hpp" #include "rive/core/field_types/core_double_type.hpp" -namespace rive -{ - class StateMachineNumberBase : public StateMachineInput - { +namespace rive { + class StateMachineNumberBase : public StateMachineInput { protected: typedef StateMachineInput Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case StateMachineNumberBase::typeKey: case StateMachineInputBase::typeKey: case StateMachineComponentBase::typeKey: @@ -36,10 +32,8 @@ public: inline float value() const { return m_Value; } - void value(float value) - { - if (m_Value == value) - { + void value(float value) { + if (m_Value == value) { return; } m_Value = value; @@ -47,16 +41,13 @@ } Core* clone() const override; - void copy(const StateMachineNumberBase& object) - { + void copy(const StateMachineNumberBase& object) { m_Value = object.m_Value; StateMachineInput::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case valuePropertyKey: m_Value = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/state_machine_trigger_base.hpp b/include/rive/generated/animation/state_machine_trigger_base.hpp index b8ab18f..14ce9d0 100644 --- a/include/rive/generated/animation/state_machine_trigger_base.hpp +++ b/include/rive/generated/animation/state_machine_trigger_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_STATE_MACHINE_TRIGGER_BASE_HPP_ #define _RIVE_STATE_MACHINE_TRIGGER_BASE_HPP_ #include "rive/animation/state_machine_input.hpp" -namespace rive -{ - class StateMachineTriggerBase : public StateMachineInput - { +namespace rive { + class StateMachineTriggerBase : public StateMachineInput { protected: typedef StateMachineInput Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case StateMachineTriggerBase::typeKey: case StateMachineInputBase::typeKey: case StateMachineComponentBase::typeKey:
diff --git a/include/rive/generated/animation/state_transition_base.hpp b/include/rive/generated/animation/state_transition_base.hpp index cd389c5..b24dc85 100644 --- a/include/rive/generated/animation/state_transition_base.hpp +++ b/include/rive/generated/animation/state_transition_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_STATE_TRANSITION_BASE_HPP_ #include "rive/animation/state_machine_layer_component.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class StateTransitionBase : public StateMachineLayerComponent - { +namespace rive { + class StateTransitionBase : public StateMachineLayerComponent { protected: typedef StateMachineLayerComponent Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case StateTransitionBase::typeKey: case StateMachineLayerComponentBase::typeKey: return true; @@ -41,10 +37,8 @@ public: inline int stateToId() const { return m_StateToId; } - void stateToId(int value) - { - if (m_StateToId == value) - { + void stateToId(int value) { + if (m_StateToId == value) { return; } m_StateToId = value; @@ -52,10 +46,8 @@ } inline int flags() const { return m_Flags; } - void flags(int value) - { - if (m_Flags == value) - { + void flags(int value) { + if (m_Flags == value) { return; } m_Flags = value; @@ -63,10 +55,8 @@ } inline int duration() const { return m_Duration; } - void duration(int value) - { - if (m_Duration == value) - { + void duration(int value) { + if (m_Duration == value) { return; } m_Duration = value; @@ -74,10 +64,8 @@ } inline int exitTime() const { return m_ExitTime; } - void exitTime(int value) - { - if (m_ExitTime == value) - { + void exitTime(int value) { + if (m_ExitTime == value) { return; } m_ExitTime = value; @@ -85,8 +73,7 @@ } Core* clone() const override; - void copy(const StateTransitionBase& object) - { + void copy(const StateTransitionBase& object) { m_StateToId = object.m_StateToId; m_Flags = object.m_Flags; m_Duration = object.m_Duration; @@ -94,10 +81,8 @@ StateMachineLayerComponent::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case stateToIdPropertyKey: m_StateToId = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/transition_bool_condition_base.hpp b/include/rive/generated/animation/transition_bool_condition_base.hpp index 5495334..4e068fd 100644 --- a/include/rive/generated/animation/transition_bool_condition_base.hpp +++ b/include/rive/generated/animation/transition_bool_condition_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_TRANSITION_BOOL_CONDITION_BASE_HPP_ #define _RIVE_TRANSITION_BOOL_CONDITION_BASE_HPP_ #include "rive/animation/transition_value_condition.hpp" -namespace rive -{ - class TransitionBoolConditionBase : public TransitionValueCondition - { +namespace rive { + class TransitionBoolConditionBase : public TransitionValueCondition { protected: typedef TransitionValueCondition Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case TransitionBoolConditionBase::typeKey: case TransitionValueConditionBase::typeKey: case TransitionConditionBase::typeKey:
diff --git a/include/rive/generated/animation/transition_condition_base.hpp b/include/rive/generated/animation/transition_condition_base.hpp index 8c62377..961fd16 100644 --- a/include/rive/generated/animation/transition_condition_base.hpp +++ b/include/rive/generated/animation/transition_condition_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_TRANSITION_CONDITION_BASE_HPP_ #include "rive/core.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class TransitionConditionBase : public Core - { +namespace rive { + class TransitionConditionBase : public Core { protected: typedef Core Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case TransitionConditionBase::typeKey: return true; default: @@ -34,25 +30,20 @@ public: inline int inputId() const { return m_InputId; } - void inputId(int value) - { - if (m_InputId == value) - { + void inputId(int value) { + if (m_InputId == value) { return; } m_InputId = value; inputIdChanged(); } - void copy(const TransitionConditionBase& object) - { + void copy(const TransitionConditionBase& object) { m_InputId = object.m_InputId; } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case inputIdPropertyKey: m_InputId = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/transition_number_condition_base.hpp b/include/rive/generated/animation/transition_number_condition_base.hpp index 7788991..5147fd2 100644 --- a/include/rive/generated/animation/transition_number_condition_base.hpp +++ b/include/rive/generated/animation/transition_number_condition_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_TRANSITION_NUMBER_CONDITION_BASE_HPP_ #include "rive/animation/transition_value_condition.hpp" #include "rive/core/field_types/core_double_type.hpp" -namespace rive -{ - class TransitionNumberConditionBase : public TransitionValueCondition - { +namespace rive { + class TransitionNumberConditionBase : public TransitionValueCondition { protected: typedef TransitionValueCondition Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case TransitionNumberConditionBase::typeKey: case TransitionValueConditionBase::typeKey: case TransitionConditionBase::typeKey: @@ -36,10 +32,8 @@ public: inline float value() const { return m_Value; } - void value(float value) - { - if (m_Value == value) - { + void value(float value) { + if (m_Value == value) { return; } m_Value = value; @@ -47,16 +41,13 @@ } Core* clone() const override; - void copy(const TransitionNumberConditionBase& object) - { + void copy(const TransitionNumberConditionBase& object) { m_Value = object.m_Value; TransitionValueCondition::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case valuePropertyKey: m_Value = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/animation/transition_trigger_condition_base.hpp b/include/rive/generated/animation/transition_trigger_condition_base.hpp index 867fb43..1fd560e 100644 --- a/include/rive/generated/animation/transition_trigger_condition_base.hpp +++ b/include/rive/generated/animation/transition_trigger_condition_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_TRANSITION_TRIGGER_CONDITION_BASE_HPP_ #define _RIVE_TRANSITION_TRIGGER_CONDITION_BASE_HPP_ #include "rive/animation/transition_condition.hpp" -namespace rive -{ - class TransitionTriggerConditionBase : public TransitionCondition - { +namespace rive { + class TransitionTriggerConditionBase : public TransitionCondition { protected: typedef TransitionCondition Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case TransitionTriggerConditionBase::typeKey: case TransitionConditionBase::typeKey: return true;
diff --git a/include/rive/generated/animation/transition_value_condition_base.hpp b/include/rive/generated/animation/transition_value_condition_base.hpp index 03949b2..8484111 100644 --- a/include/rive/generated/animation/transition_value_condition_base.hpp +++ b/include/rive/generated/animation/transition_value_condition_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_TRANSITION_VALUE_CONDITION_BASE_HPP_ #include "rive/animation/transition_condition.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class TransitionValueConditionBase : public TransitionCondition - { +namespace rive { + class TransitionValueConditionBase : public TransitionCondition { protected: typedef TransitionCondition Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case TransitionValueConditionBase::typeKey: case TransitionConditionBase::typeKey: return true; @@ -35,26 +31,21 @@ public: inline int opValue() const { return m_OpValue; } - void opValue(int value) - { - if (m_OpValue == value) - { + void opValue(int value) { + if (m_OpValue == value) { return; } m_OpValue = value; opValueChanged(); } - void copy(const TransitionValueConditionBase& object) - { + void copy(const TransitionValueConditionBase& object) { m_OpValue = object.m_OpValue; TransitionCondition::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case opValuePropertyKey: m_OpValue = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/artboard_base.hpp b/include/rive/generated/artboard_base.hpp index b790391..0f83d5f 100644 --- a/include/rive/generated/artboard_base.hpp +++ b/include/rive/generated/artboard_base.hpp
@@ -3,10 +3,8 @@ #include "rive/core/field_types/core_bool_type.hpp" #include "rive/core/field_types/core_double_type.hpp" #include "rive/world_transform_component.hpp" -namespace rive -{ - class ArtboardBase : public WorldTransformComponent - { +namespace rive { + class ArtboardBase : public WorldTransformComponent { protected: typedef WorldTransformComponent Super; @@ -15,10 +13,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case ArtboardBase::typeKey: case WorldTransformComponentBase::typeKey: case ContainerComponentBase::typeKey: @@ -50,10 +46,8 @@ public: inline bool clip() const { return m_Clip; } - void clip(bool value) - { - if (m_Clip == value) - { + void clip(bool value) { + if (m_Clip == value) { return; } m_Clip = value; @@ -61,10 +55,8 @@ } inline float width() const { return m_Width; } - void width(float value) - { - if (m_Width == value) - { + void width(float value) { + if (m_Width == value) { return; } m_Width = value; @@ -72,10 +64,8 @@ } inline float height() const { return m_Height; } - void height(float value) - { - if (m_Height == value) - { + void height(float value) { + if (m_Height == value) { return; } m_Height = value; @@ -83,10 +73,8 @@ } inline float x() const { return m_X; } - void x(float value) - { - if (m_X == value) - { + void x(float value) { + if (m_X == value) { return; } m_X = value; @@ -94,10 +82,8 @@ } inline float y() const { return m_Y; } - void y(float value) - { - if (m_Y == value) - { + void y(float value) { + if (m_Y == value) { return; } m_Y = value; @@ -105,10 +91,8 @@ } inline float originX() const { return m_OriginX; } - void originX(float value) - { - if (m_OriginX == value) - { + void originX(float value) { + if (m_OriginX == value) { return; } m_OriginX = value; @@ -116,10 +100,8 @@ } inline float originY() const { return m_OriginY; } - void originY(float value) - { - if (m_OriginY == value) - { + void originY(float value) { + if (m_OriginY == value) { return; } m_OriginY = value; @@ -127,8 +109,7 @@ } Core* clone() const override; - void copy(const ArtboardBase& object) - { + void copy(const ArtboardBase& object) { m_Clip = object.m_Clip; m_Width = object.m_Width; m_Height = object.m_Height; @@ -139,10 +120,8 @@ WorldTransformComponent::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case clipPropertyKey: m_Clip = CoreBoolType::deserialize(reader); return true;
diff --git a/include/rive/generated/assets/asset_base.hpp b/include/rive/generated/assets/asset_base.hpp index 2a1dd56..bf4da39 100644 --- a/include/rive/generated/assets/asset_base.hpp +++ b/include/rive/generated/assets/asset_base.hpp
@@ -3,10 +3,8 @@ #include <string> #include "rive/core.hpp" #include "rive/core/field_types/core_string_type.hpp" -namespace rive -{ - class AssetBase : public Core - { +namespace rive { + class AssetBase : public Core { protected: typedef Core Super; @@ -15,10 +13,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case AssetBase::typeKey: return true; default: @@ -35,10 +31,8 @@ public: inline const std::string& name() const { return m_Name; } - void name(std::string value) - { - if (m_Name == value) - { + void name(std::string value) { + if (m_Name == value) { return; } m_Name = value; @@ -47,10 +41,8 @@ void copy(const AssetBase& object) { m_Name = object.m_Name; } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case namePropertyKey: m_Name = CoreStringType::deserialize(reader); return true;
diff --git a/include/rive/generated/assets/drawable_asset_base.hpp b/include/rive/generated/assets/drawable_asset_base.hpp index e55cc79..496e114 100644 --- a/include/rive/generated/assets/drawable_asset_base.hpp +++ b/include/rive/generated/assets/drawable_asset_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_DRAWABLE_ASSET_BASE_HPP_ #include "rive/assets/file_asset.hpp" #include "rive/core/field_types/core_double_type.hpp" -namespace rive -{ - class DrawableAssetBase : public FileAsset - { +namespace rive { + class DrawableAssetBase : public FileAsset { protected: typedef FileAsset Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case DrawableAssetBase::typeKey: case FileAssetBase::typeKey: case AssetBase::typeKey: @@ -38,10 +34,8 @@ public: inline float height() const { return m_Height; } - void height(float value) - { - if (m_Height == value) - { + void height(float value) { + if (m_Height == value) { return; } m_Height = value; @@ -49,27 +43,22 @@ } inline float width() const { return m_Width; } - void width(float value) - { - if (m_Width == value) - { + void width(float value) { + if (m_Width == value) { return; } m_Width = value; widthChanged(); } - void copy(const DrawableAssetBase& object) - { + void copy(const DrawableAssetBase& object) { m_Height = object.m_Height; m_Width = object.m_Width; FileAsset::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case heightPropertyKey: m_Height = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/assets/file_asset_base.hpp b/include/rive/generated/assets/file_asset_base.hpp index 0738eb7..1f612f9 100644 --- a/include/rive/generated/assets/file_asset_base.hpp +++ b/include/rive/generated/assets/file_asset_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_FILE_ASSET_BASE_HPP_ #include "rive/assets/asset.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class FileAssetBase : public Asset - { +namespace rive { + class FileAssetBase : public Asset { protected: typedef Asset Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case FileAssetBase::typeKey: case AssetBase::typeKey: return true; @@ -35,26 +31,21 @@ public: inline int assetId() const { return m_AssetId; } - void assetId(int value) - { - if (m_AssetId == value) - { + void assetId(int value) { + if (m_AssetId == value) { return; } m_AssetId = value; assetIdChanged(); } - void copy(const FileAssetBase& object) - { + void copy(const FileAssetBase& object) { m_AssetId = object.m_AssetId; Asset::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case assetIdPropertyKey: m_AssetId = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/assets/file_asset_contents_base.hpp b/include/rive/generated/assets/file_asset_contents_base.hpp index 2463cea..89565d2 100644 --- a/include/rive/generated/assets/file_asset_contents_base.hpp +++ b/include/rive/generated/assets/file_asset_contents_base.hpp
@@ -3,10 +3,8 @@ #include <vector> #include "rive/core.hpp" #include "rive/core/field_types/core_bytes_type.hpp" -namespace rive -{ - class FileAssetContentsBase : public Core - { +namespace rive { + class FileAssetContentsBase : public Core { protected: typedef Core Super; @@ -15,10 +13,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case FileAssetContentsBase::typeKey: return true; default: @@ -35,10 +31,8 @@ public: inline const std::vector<uint8_t>& bytes() const { return m_Bytes; } - void bytes(std::vector<uint8_t> value) - { - if (m_Bytes == value) - { + void bytes(std::vector<uint8_t> value) { + if (m_Bytes == value) { return; } m_Bytes = value; @@ -46,15 +40,12 @@ } Core* clone() const override; - void copy(const FileAssetContentsBase& object) - { + void copy(const FileAssetContentsBase& object) { m_Bytes = object.m_Bytes; } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case bytesPropertyKey: m_Bytes = CoreBytesType::deserialize(reader); return true;
diff --git a/include/rive/generated/assets/folder_base.hpp b/include/rive/generated/assets/folder_base.hpp index 2a59d18..42e0112 100644 --- a/include/rive/generated/assets/folder_base.hpp +++ b/include/rive/generated/assets/folder_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_FOLDER_BASE_HPP_ #define _RIVE_FOLDER_BASE_HPP_ #include "rive/assets/asset.hpp" -namespace rive -{ - class FolderBase : public Asset - { +namespace rive { + class FolderBase : public Asset { protected: typedef Asset Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case FolderBase::typeKey: case AssetBase::typeKey: return true;
diff --git a/include/rive/generated/assets/image_asset_base.hpp b/include/rive/generated/assets/image_asset_base.hpp index 3ba5864..4040579 100644 --- a/include/rive/generated/assets/image_asset_base.hpp +++ b/include/rive/generated/assets/image_asset_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_IMAGE_ASSET_BASE_HPP_ #define _RIVE_IMAGE_ASSET_BASE_HPP_ #include "rive/assets/drawable_asset.hpp" -namespace rive -{ - class ImageAssetBase : public DrawableAsset - { +namespace rive { + class ImageAssetBase : public DrawableAsset { protected: typedef DrawableAsset Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case ImageAssetBase::typeKey: case DrawableAssetBase::typeKey: case FileAssetBase::typeKey:
diff --git a/include/rive/generated/backboard_base.hpp b/include/rive/generated/backboard_base.hpp index c124f7a..86a0983 100644 --- a/include/rive/generated/backboard_base.hpp +++ b/include/rive/generated/backboard_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_BACKBOARD_BASE_HPP_ #define _RIVE_BACKBOARD_BASE_HPP_ #include "rive/core.hpp" -namespace rive -{ - class BackboardBase : public Core - { +namespace rive { + class BackboardBase : public Core { protected: typedef Core Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case BackboardBase::typeKey: return true; default: @@ -29,10 +25,8 @@ Core* clone() const override; void copy(const BackboardBase& object) {} - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { } return false; }
diff --git a/include/rive/generated/bones/bone_base.hpp b/include/rive/generated/bones/bone_base.hpp index b29e222..20473ce 100644 --- a/include/rive/generated/bones/bone_base.hpp +++ b/include/rive/generated/bones/bone_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_BONE_BASE_HPP_ #include "rive/bones/skeletal_component.hpp" #include "rive/core/field_types/core_double_type.hpp" -namespace rive -{ - class BoneBase : public SkeletalComponent - { +namespace rive { + class BoneBase : public SkeletalComponent { protected: typedef SkeletalComponent Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case BoneBase::typeKey: case SkeletalComponentBase::typeKey: case TransformComponentBase::typeKey: @@ -39,10 +35,8 @@ public: inline float length() const { return m_Length; } - void length(float value) - { - if (m_Length == value) - { + void length(float value) { + if (m_Length == value) { return; } m_Length = value; @@ -50,16 +44,13 @@ } Core* clone() const override; - void copy(const BoneBase& object) - { + void copy(const BoneBase& object) { m_Length = object.m_Length; SkeletalComponent::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case lengthPropertyKey: m_Length = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/bones/cubic_weight_base.hpp b/include/rive/generated/bones/cubic_weight_base.hpp index 60a5a1a..8920cec 100644 --- a/include/rive/generated/bones/cubic_weight_base.hpp +++ b/include/rive/generated/bones/cubic_weight_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_CUBIC_WEIGHT_BASE_HPP_ #include "rive/bones/weight.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class CubicWeightBase : public Weight - { +namespace rive { + class CubicWeightBase : public Weight { protected: typedef Weight Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case CubicWeightBase::typeKey: case WeightBase::typeKey: case ComponentBase::typeKey: @@ -42,10 +38,8 @@ public: inline int inValues() const { return m_InValues; } - void inValues(int value) - { - if (m_InValues == value) - { + void inValues(int value) { + if (m_InValues == value) { return; } m_InValues = value; @@ -53,10 +47,8 @@ } inline int inIndices() const { return m_InIndices; } - void inIndices(int value) - { - if (m_InIndices == value) - { + void inIndices(int value) { + if (m_InIndices == value) { return; } m_InIndices = value; @@ -64,10 +56,8 @@ } inline int outValues() const { return m_OutValues; } - void outValues(int value) - { - if (m_OutValues == value) - { + void outValues(int value) { + if (m_OutValues == value) { return; } m_OutValues = value; @@ -75,10 +65,8 @@ } inline int outIndices() const { return m_OutIndices; } - void outIndices(int value) - { - if (m_OutIndices == value) - { + void outIndices(int value) { + if (m_OutIndices == value) { return; } m_OutIndices = value; @@ -86,8 +74,7 @@ } Core* clone() const override; - void copy(const CubicWeightBase& object) - { + void copy(const CubicWeightBase& object) { m_InValues = object.m_InValues; m_InIndices = object.m_InIndices; m_OutValues = object.m_OutValues; @@ -95,10 +82,8 @@ Weight::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case inValuesPropertyKey: m_InValues = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/bones/root_bone_base.hpp b/include/rive/generated/bones/root_bone_base.hpp index f35af4e..25ae15a 100644 --- a/include/rive/generated/bones/root_bone_base.hpp +++ b/include/rive/generated/bones/root_bone_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_ROOT_BONE_BASE_HPP_ #include "rive/bones/bone.hpp" #include "rive/core/field_types/core_double_type.hpp" -namespace rive -{ - class RootBoneBase : public Bone - { +namespace rive { + class RootBoneBase : public Bone { protected: typedef Bone Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case RootBoneBase::typeKey: case BoneBase::typeKey: case SkeletalComponentBase::typeKey: @@ -42,10 +38,8 @@ public: inline float x() const override { return m_X; } - void x(float value) - { - if (m_X == value) - { + void x(float value) { + if (m_X == value) { return; } m_X = value; @@ -53,10 +47,8 @@ } inline float y() const override { return m_Y; } - void y(float value) - { - if (m_Y == value) - { + void y(float value) { + if (m_Y == value) { return; } m_Y = value; @@ -64,17 +56,14 @@ } Core* clone() const override; - void copy(const RootBoneBase& object) - { + void copy(const RootBoneBase& object) { m_X = object.m_X; m_Y = object.m_Y; Bone::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case xPropertyKey: m_X = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/bones/skeletal_component_base.hpp b/include/rive/generated/bones/skeletal_component_base.hpp index 39c335c..070db46 100644 --- a/include/rive/generated/bones/skeletal_component_base.hpp +++ b/include/rive/generated/bones/skeletal_component_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_SKELETAL_COMPONENT_BASE_HPP_ #define _RIVE_SKELETAL_COMPONENT_BASE_HPP_ #include "rive/transform_component.hpp" -namespace rive -{ - class SkeletalComponentBase : public TransformComponent - { +namespace rive { + class SkeletalComponentBase : public TransformComponent { protected: typedef TransformComponent Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case SkeletalComponentBase::typeKey: case TransformComponentBase::typeKey: case WorldTransformComponentBase::typeKey:
diff --git a/include/rive/generated/bones/skin_base.hpp b/include/rive/generated/bones/skin_base.hpp index 434b41c..5478a81 100644 --- a/include/rive/generated/bones/skin_base.hpp +++ b/include/rive/generated/bones/skin_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_SKIN_BASE_HPP_ #include "rive/container_component.hpp" #include "rive/core/field_types/core_double_type.hpp" -namespace rive -{ - class SkinBase : public ContainerComponent - { +namespace rive { + class SkinBase : public ContainerComponent { protected: typedef ContainerComponent Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case SkinBase::typeKey: case ContainerComponentBase::typeKey: case ComponentBase::typeKey: @@ -46,10 +42,8 @@ public: inline float xx() const { return m_Xx; } - void xx(float value) - { - if (m_Xx == value) - { + void xx(float value) { + if (m_Xx == value) { return; } m_Xx = value; @@ -57,10 +51,8 @@ } inline float yx() const { return m_Yx; } - void yx(float value) - { - if (m_Yx == value) - { + void yx(float value) { + if (m_Yx == value) { return; } m_Yx = value; @@ -68,10 +60,8 @@ } inline float xy() const { return m_Xy; } - void xy(float value) - { - if (m_Xy == value) - { + void xy(float value) { + if (m_Xy == value) { return; } m_Xy = value; @@ -79,10 +69,8 @@ } inline float yy() const { return m_Yy; } - void yy(float value) - { - if (m_Yy == value) - { + void yy(float value) { + if (m_Yy == value) { return; } m_Yy = value; @@ -90,10 +78,8 @@ } inline float tx() const { return m_Tx; } - void tx(float value) - { - if (m_Tx == value) - { + void tx(float value) { + if (m_Tx == value) { return; } m_Tx = value; @@ -101,10 +87,8 @@ } inline float ty() const { return m_Ty; } - void ty(float value) - { - if (m_Ty == value) - { + void ty(float value) { + if (m_Ty == value) { return; } m_Ty = value; @@ -112,8 +96,7 @@ } Core* clone() const override; - void copy(const SkinBase& object) - { + void copy(const SkinBase& object) { m_Xx = object.m_Xx; m_Yx = object.m_Yx; m_Xy = object.m_Xy; @@ -123,10 +106,8 @@ ContainerComponent::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case xxPropertyKey: m_Xx = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/bones/tendon_base.hpp b/include/rive/generated/bones/tendon_base.hpp index 920a27e..ce5ebe1 100644 --- a/include/rive/generated/bones/tendon_base.hpp +++ b/include/rive/generated/bones/tendon_base.hpp
@@ -3,10 +3,8 @@ #include "rive/component.hpp" #include "rive/core/field_types/core_double_type.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class TendonBase : public Component - { +namespace rive { + class TendonBase : public Component { protected: typedef Component Super; @@ -15,10 +13,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case TendonBase::typeKey: case ComponentBase::typeKey: return true; @@ -48,10 +44,8 @@ public: inline int boneId() const { return m_BoneId; } - void boneId(int value) - { - if (m_BoneId == value) - { + void boneId(int value) { + if (m_BoneId == value) { return; } m_BoneId = value; @@ -59,10 +53,8 @@ } inline float xx() const { return m_Xx; } - void xx(float value) - { - if (m_Xx == value) - { + void xx(float value) { + if (m_Xx == value) { return; } m_Xx = value; @@ -70,10 +62,8 @@ } inline float yx() const { return m_Yx; } - void yx(float value) - { - if (m_Yx == value) - { + void yx(float value) { + if (m_Yx == value) { return; } m_Yx = value; @@ -81,10 +71,8 @@ } inline float xy() const { return m_Xy; } - void xy(float value) - { - if (m_Xy == value) - { + void xy(float value) { + if (m_Xy == value) { return; } m_Xy = value; @@ -92,10 +80,8 @@ } inline float yy() const { return m_Yy; } - void yy(float value) - { - if (m_Yy == value) - { + void yy(float value) { + if (m_Yy == value) { return; } m_Yy = value; @@ -103,10 +89,8 @@ } inline float tx() const { return m_Tx; } - void tx(float value) - { - if (m_Tx == value) - { + void tx(float value) { + if (m_Tx == value) { return; } m_Tx = value; @@ -114,10 +98,8 @@ } inline float ty() const { return m_Ty; } - void ty(float value) - { - if (m_Ty == value) - { + void ty(float value) { + if (m_Ty == value) { return; } m_Ty = value; @@ -125,8 +107,7 @@ } Core* clone() const override; - void copy(const TendonBase& object) - { + void copy(const TendonBase& object) { m_BoneId = object.m_BoneId; m_Xx = object.m_Xx; m_Yx = object.m_Yx; @@ -137,10 +118,8 @@ Component::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case boneIdPropertyKey: m_BoneId = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/bones/weight_base.hpp b/include/rive/generated/bones/weight_base.hpp index 99f9de2..881e4c8 100644 --- a/include/rive/generated/bones/weight_base.hpp +++ b/include/rive/generated/bones/weight_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_WEIGHT_BASE_HPP_ #include "rive/component.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class WeightBase : public Component - { +namespace rive { + class WeightBase : public Component { protected: typedef Component Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case WeightBase::typeKey: case ComponentBase::typeKey: return true; @@ -37,10 +33,8 @@ public: inline int values() const { return m_Values; } - void values(int value) - { - if (m_Values == value) - { + void values(int value) { + if (m_Values == value) { return; } m_Values = value; @@ -48,10 +42,8 @@ } inline int indices() const { return m_Indices; } - void indices(int value) - { - if (m_Indices == value) - { + void indices(int value) { + if (m_Indices == value) { return; } m_Indices = value; @@ -59,17 +51,14 @@ } Core* clone() const override; - void copy(const WeightBase& object) - { + void copy(const WeightBase& object) { m_Values = object.m_Values; m_Indices = object.m_Indices; Component::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case valuesPropertyKey: m_Values = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/component_base.hpp b/include/rive/generated/component_base.hpp index 49584e3..2052295 100644 --- a/include/rive/generated/component_base.hpp +++ b/include/rive/generated/component_base.hpp
@@ -4,10 +4,8 @@ #include "rive/core.hpp" #include "rive/core/field_types/core_string_type.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class ComponentBase : public Core - { +namespace rive { + class ComponentBase : public Core { protected: typedef Core Super; @@ -16,10 +14,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case ComponentBase::typeKey: return true; default: @@ -38,10 +34,8 @@ public: inline const std::string& name() const { return m_Name; } - void name(std::string value) - { - if (m_Name == value) - { + void name(std::string value) { + if (m_Name == value) { return; } m_Name = value; @@ -49,26 +43,21 @@ } inline int parentId() const { return m_ParentId; } - void parentId(int value) - { - if (m_ParentId == value) - { + void parentId(int value) { + if (m_ParentId == value) { return; } m_ParentId = value; parentIdChanged(); } - void copy(const ComponentBase& object) - { + void copy(const ComponentBase& object) { m_Name = object.m_Name; m_ParentId = object.m_ParentId; } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case namePropertyKey: m_Name = CoreStringType::deserialize(reader); return true;
diff --git a/include/rive/generated/constraints/constraint_base.hpp b/include/rive/generated/constraints/constraint_base.hpp index 5545b67..27785dc 100644 --- a/include/rive/generated/constraints/constraint_base.hpp +++ b/include/rive/generated/constraints/constraint_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_CONSTRAINT_BASE_HPP_ #include "rive/component.hpp" #include "rive/core/field_types/core_double_type.hpp" -namespace rive -{ - class ConstraintBase : public Component - { +namespace rive { + class ConstraintBase : public Component { protected: typedef Component Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case ConstraintBase::typeKey: case ComponentBase::typeKey: return true; @@ -35,26 +31,21 @@ public: inline float strength() const { return m_Strength; } - void strength(float value) - { - if (m_Strength == value) - { + void strength(float value) { + if (m_Strength == value) { return; } m_Strength = value; strengthChanged(); } - void copy(const ConstraintBase& object) - { + void copy(const ConstraintBase& object) { m_Strength = object.m_Strength; Component::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case strengthPropertyKey: m_Strength = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/constraints/distance_constraint_base.hpp b/include/rive/generated/constraints/distance_constraint_base.hpp index 7e056d7..1d3a1ae 100644 --- a/include/rive/generated/constraints/distance_constraint_base.hpp +++ b/include/rive/generated/constraints/distance_constraint_base.hpp
@@ -3,10 +3,8 @@ #include "rive/constraints/targeted_constraint.hpp" #include "rive/core/field_types/core_double_type.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class DistanceConstraintBase : public TargetedConstraint - { +namespace rive { + class DistanceConstraintBase : public TargetedConstraint { protected: typedef TargetedConstraint Super; @@ -15,10 +13,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case DistanceConstraintBase::typeKey: case TargetedConstraintBase::typeKey: case ConstraintBase::typeKey: @@ -40,10 +36,8 @@ public: inline float distance() const { return m_Distance; } - void distance(float value) - { - if (m_Distance == value) - { + void distance(float value) { + if (m_Distance == value) { return; } m_Distance = value; @@ -51,10 +45,8 @@ } inline int modeValue() const { return m_ModeValue; } - void modeValue(int value) - { - if (m_ModeValue == value) - { + void modeValue(int value) { + if (m_ModeValue == value) { return; } m_ModeValue = value; @@ -62,17 +54,14 @@ } Core* clone() const override; - void copy(const DistanceConstraintBase& object) - { + void copy(const DistanceConstraintBase& object) { m_Distance = object.m_Distance; m_ModeValue = object.m_ModeValue; TargetedConstraint::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case distancePropertyKey: m_Distance = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/constraints/ik_constraint_base.hpp b/include/rive/generated/constraints/ik_constraint_base.hpp index 623921d..6aba926 100644 --- a/include/rive/generated/constraints/ik_constraint_base.hpp +++ b/include/rive/generated/constraints/ik_constraint_base.hpp
@@ -3,10 +3,8 @@ #include "rive/constraints/targeted_constraint.hpp" #include "rive/core/field_types/core_bool_type.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class IKConstraintBase : public TargetedConstraint - { +namespace rive { + class IKConstraintBase : public TargetedConstraint { protected: typedef TargetedConstraint Super; @@ -15,10 +13,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case IKConstraintBase::typeKey: case TargetedConstraintBase::typeKey: case ConstraintBase::typeKey: @@ -40,10 +36,8 @@ public: inline bool invertDirection() const { return m_InvertDirection; } - void invertDirection(bool value) - { - if (m_InvertDirection == value) - { + void invertDirection(bool value) { + if (m_InvertDirection == value) { return; } m_InvertDirection = value; @@ -51,10 +45,8 @@ } inline int parentBoneCount() const { return m_ParentBoneCount; } - void parentBoneCount(int value) - { - if (m_ParentBoneCount == value) - { + void parentBoneCount(int value) { + if (m_ParentBoneCount == value) { return; } m_ParentBoneCount = value; @@ -62,17 +54,14 @@ } Core* clone() const override; - void copy(const IKConstraintBase& object) - { + void copy(const IKConstraintBase& object) { m_InvertDirection = object.m_InvertDirection; m_ParentBoneCount = object.m_ParentBoneCount; TargetedConstraint::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case invertDirectionPropertyKey: m_InvertDirection = CoreBoolType::deserialize(reader); return true;
diff --git a/include/rive/generated/constraints/rotation_constraint_base.hpp b/include/rive/generated/constraints/rotation_constraint_base.hpp index 7f1eb9d..bf7517a 100644 --- a/include/rive/generated/constraints/rotation_constraint_base.hpp +++ b/include/rive/generated/constraints/rotation_constraint_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_ROTATION_CONSTRAINT_BASE_HPP_ #define _RIVE_ROTATION_CONSTRAINT_BASE_HPP_ #include "rive/constraints/transform_component_constraint.hpp" -namespace rive -{ - class RotationConstraintBase : public TransformComponentConstraint - { +namespace rive { + class RotationConstraintBase : public TransformComponentConstraint { protected: typedef TransformComponentConstraint Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case RotationConstraintBase::typeKey: case TransformComponentConstraintBase::typeKey: case TransformSpaceConstraintBase::typeKey:
diff --git a/include/rive/generated/constraints/scale_constraint_base.hpp b/include/rive/generated/constraints/scale_constraint_base.hpp index bbe69b0..073b1b0 100644 --- a/include/rive/generated/constraints/scale_constraint_base.hpp +++ b/include/rive/generated/constraints/scale_constraint_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_SCALE_CONSTRAINT_BASE_HPP_ #define _RIVE_SCALE_CONSTRAINT_BASE_HPP_ #include "rive/constraints/transform_component_constraint_y.hpp" -namespace rive -{ - class ScaleConstraintBase : public TransformComponentConstraintY - { +namespace rive { + class ScaleConstraintBase : public TransformComponentConstraintY { protected: typedef TransformComponentConstraintY Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case ScaleConstraintBase::typeKey: case TransformComponentConstraintYBase::typeKey: case TransformComponentConstraintBase::typeKey:
diff --git a/include/rive/generated/constraints/targeted_constraint_base.hpp b/include/rive/generated/constraints/targeted_constraint_base.hpp index 2329d17..99f693e 100644 --- a/include/rive/generated/constraints/targeted_constraint_base.hpp +++ b/include/rive/generated/constraints/targeted_constraint_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_TARGETED_CONSTRAINT_BASE_HPP_ #include "rive/constraints/constraint.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class TargetedConstraintBase : public Constraint - { +namespace rive { + class TargetedConstraintBase : public Constraint { protected: typedef Constraint Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case TargetedConstraintBase::typeKey: case ConstraintBase::typeKey: case ComponentBase::typeKey: @@ -36,26 +32,21 @@ public: inline int targetId() const { return m_TargetId; } - void targetId(int value) - { - if (m_TargetId == value) - { + void targetId(int value) { + if (m_TargetId == value) { return; } m_TargetId = value; targetIdChanged(); } - void copy(const TargetedConstraintBase& object) - { + void copy(const TargetedConstraintBase& object) { m_TargetId = object.m_TargetId; Constraint::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case targetIdPropertyKey: m_TargetId = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/constraints/transform_component_constraint_base.hpp b/include/rive/generated/constraints/transform_component_constraint_base.hpp index eb8a6c4..322f659 100644 --- a/include/rive/generated/constraints/transform_component_constraint_base.hpp +++ b/include/rive/generated/constraints/transform_component_constraint_base.hpp
@@ -4,10 +4,8 @@ #include "rive/core/field_types/core_bool_type.hpp" #include "rive/core/field_types/core_double_type.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class TransformComponentConstraintBase : public TransformSpaceConstraint - { +namespace rive { + class TransformComponentConstraintBase : public TransformSpaceConstraint { protected: typedef TransformSpaceConstraint Super; @@ -16,10 +14,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case TransformComponentConstraintBase::typeKey: case TransformSpaceConstraintBase::typeKey: case TargetedConstraintBase::typeKey: @@ -54,10 +50,8 @@ public: inline int minMaxSpaceValue() const { return m_MinMaxSpaceValue; } - void minMaxSpaceValue(int value) - { - if (m_MinMaxSpaceValue == value) - { + void minMaxSpaceValue(int value) { + if (m_MinMaxSpaceValue == value) { return; } m_MinMaxSpaceValue = value; @@ -65,10 +59,8 @@ } inline float copyFactor() const { return m_CopyFactor; } - void copyFactor(float value) - { - if (m_CopyFactor == value) - { + void copyFactor(float value) { + if (m_CopyFactor == value) { return; } m_CopyFactor = value; @@ -76,10 +68,8 @@ } inline float minValue() const { return m_MinValue; } - void minValue(float value) - { - if (m_MinValue == value) - { + void minValue(float value) { + if (m_MinValue == value) { return; } m_MinValue = value; @@ -87,10 +77,8 @@ } inline float maxValue() const { return m_MaxValue; } - void maxValue(float value) - { - if (m_MaxValue == value) - { + void maxValue(float value) { + if (m_MaxValue == value) { return; } m_MaxValue = value; @@ -98,10 +86,8 @@ } inline bool offset() const { return m_Offset; } - void offset(bool value) - { - if (m_Offset == value) - { + void offset(bool value) { + if (m_Offset == value) { return; } m_Offset = value; @@ -109,10 +95,8 @@ } inline bool doesCopy() const { return m_DoesCopy; } - void doesCopy(bool value) - { - if (m_DoesCopy == value) - { + void doesCopy(bool value) { + if (m_DoesCopy == value) { return; } m_DoesCopy = value; @@ -120,10 +104,8 @@ } inline bool min() const { return m_Min; } - void min(bool value) - { - if (m_Min == value) - { + void min(bool value) { + if (m_Min == value) { return; } m_Min = value; @@ -131,18 +113,15 @@ } inline bool max() const { return m_Max; } - void max(bool value) - { - if (m_Max == value) - { + void max(bool value) { + if (m_Max == value) { return; } m_Max = value; maxChanged(); } - void copy(const TransformComponentConstraintBase& object) - { + void copy(const TransformComponentConstraintBase& object) { m_MinMaxSpaceValue = object.m_MinMaxSpaceValue; m_CopyFactor = object.m_CopyFactor; m_MinValue = object.m_MinValue; @@ -154,10 +133,8 @@ TransformSpaceConstraint::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case minMaxSpaceValuePropertyKey: m_MinMaxSpaceValue = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/constraints/transform_component_constraint_y_base.hpp b/include/rive/generated/constraints/transform_component_constraint_y_base.hpp index f23d6a1..9558cdc 100644 --- a/include/rive/generated/constraints/transform_component_constraint_y_base.hpp +++ b/include/rive/generated/constraints/transform_component_constraint_y_base.hpp
@@ -3,11 +3,9 @@ #include "rive/constraints/transform_component_constraint.hpp" #include "rive/core/field_types/core_bool_type.hpp" #include "rive/core/field_types/core_double_type.hpp" -namespace rive -{ +namespace rive { class TransformComponentConstraintYBase - : public TransformComponentConstraint - { + : public TransformComponentConstraint { protected: typedef TransformComponentConstraint Super; @@ -16,10 +14,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case TransformComponentConstraintYBase::typeKey: case TransformComponentConstraintBase::typeKey: case TransformSpaceConstraintBase::typeKey: @@ -51,10 +47,8 @@ public: inline float copyFactorY() const { return m_CopyFactorY; } - void copyFactorY(float value) - { - if (m_CopyFactorY == value) - { + void copyFactorY(float value) { + if (m_CopyFactorY == value) { return; } m_CopyFactorY = value; @@ -62,10 +56,8 @@ } inline float minValueY() const { return m_MinValueY; } - void minValueY(float value) - { - if (m_MinValueY == value) - { + void minValueY(float value) { + if (m_MinValueY == value) { return; } m_MinValueY = value; @@ -73,10 +65,8 @@ } inline float maxValueY() const { return m_MaxValueY; } - void maxValueY(float value) - { - if (m_MaxValueY == value) - { + void maxValueY(float value) { + if (m_MaxValueY == value) { return; } m_MaxValueY = value; @@ -84,10 +74,8 @@ } inline bool doesCopyY() const { return m_DoesCopyY; } - void doesCopyY(bool value) - { - if (m_DoesCopyY == value) - { + void doesCopyY(bool value) { + if (m_DoesCopyY == value) { return; } m_DoesCopyY = value; @@ -95,10 +83,8 @@ } inline bool minY() const { return m_MinY; } - void minY(bool value) - { - if (m_MinY == value) - { + void minY(bool value) { + if (m_MinY == value) { return; } m_MinY = value; @@ -106,18 +92,15 @@ } inline bool maxY() const { return m_MaxY; } - void maxY(bool value) - { - if (m_MaxY == value) - { + void maxY(bool value) { + if (m_MaxY == value) { return; } m_MaxY = value; maxYChanged(); } - void copy(const TransformComponentConstraintYBase& object) - { + void copy(const TransformComponentConstraintYBase& object) { m_CopyFactorY = object.m_CopyFactorY; m_MinValueY = object.m_MinValueY; m_MaxValueY = object.m_MaxValueY; @@ -127,10 +110,8 @@ TransformComponentConstraint::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case copyFactorYPropertyKey: m_CopyFactorY = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/constraints/transform_constraint_base.hpp b/include/rive/generated/constraints/transform_constraint_base.hpp index db363a4..907294d 100644 --- a/include/rive/generated/constraints/transform_constraint_base.hpp +++ b/include/rive/generated/constraints/transform_constraint_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_TRANSFORM_CONSTRAINT_BASE_HPP_ #define _RIVE_TRANSFORM_CONSTRAINT_BASE_HPP_ #include "rive/constraints/transform_space_constraint.hpp" -namespace rive -{ - class TransformConstraintBase : public TransformSpaceConstraint - { +namespace rive { + class TransformConstraintBase : public TransformSpaceConstraint { protected: typedef TransformSpaceConstraint Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case TransformConstraintBase::typeKey: case TransformSpaceConstraintBase::typeKey: case TargetedConstraintBase::typeKey:
diff --git a/include/rive/generated/constraints/transform_space_constraint_base.hpp b/include/rive/generated/constraints/transform_space_constraint_base.hpp index 5d3f59d..e2abbe8 100644 --- a/include/rive/generated/constraints/transform_space_constraint_base.hpp +++ b/include/rive/generated/constraints/transform_space_constraint_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_TRANSFORM_SPACE_CONSTRAINT_BASE_HPP_ #include "rive/constraints/targeted_constraint.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class TransformSpaceConstraintBase : public TargetedConstraint - { +namespace rive { + class TransformSpaceConstraintBase : public TargetedConstraint { protected: typedef TargetedConstraint Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case TransformSpaceConstraintBase::typeKey: case TargetedConstraintBase::typeKey: case ConstraintBase::typeKey: @@ -39,10 +35,8 @@ public: inline int sourceSpaceValue() const { return m_SourceSpaceValue; } - void sourceSpaceValue(int value) - { - if (m_SourceSpaceValue == value) - { + void sourceSpaceValue(int value) { + if (m_SourceSpaceValue == value) { return; } m_SourceSpaceValue = value; @@ -50,27 +44,22 @@ } inline int destSpaceValue() const { return m_DestSpaceValue; } - void destSpaceValue(int value) - { - if (m_DestSpaceValue == value) - { + void destSpaceValue(int value) { + if (m_DestSpaceValue == value) { return; } m_DestSpaceValue = value; destSpaceValueChanged(); } - void copy(const TransformSpaceConstraintBase& object) - { + void copy(const TransformSpaceConstraintBase& object) { m_SourceSpaceValue = object.m_SourceSpaceValue; m_DestSpaceValue = object.m_DestSpaceValue; TargetedConstraint::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case sourceSpaceValuePropertyKey: m_SourceSpaceValue = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/constraints/translation_constraint_base.hpp b/include/rive/generated/constraints/translation_constraint_base.hpp index a0beef7..1ebe627 100644 --- a/include/rive/generated/constraints/translation_constraint_base.hpp +++ b/include/rive/generated/constraints/translation_constraint_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_TRANSLATION_CONSTRAINT_BASE_HPP_ #define _RIVE_TRANSLATION_CONSTRAINT_BASE_HPP_ #include "rive/constraints/transform_component_constraint_y.hpp" -namespace rive -{ - class TranslationConstraintBase : public TransformComponentConstraintY - { +namespace rive { + class TranslationConstraintBase : public TransformComponentConstraintY { protected: typedef TransformComponentConstraintY Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case TranslationConstraintBase::typeKey: case TransformComponentConstraintYBase::typeKey: case TransformComponentConstraintBase::typeKey:
diff --git a/include/rive/generated/container_component_base.hpp b/include/rive/generated/container_component_base.hpp index 2da0af2..9549365 100644 --- a/include/rive/generated/container_component_base.hpp +++ b/include/rive/generated/container_component_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_CONTAINER_COMPONENT_BASE_HPP_ #define _RIVE_CONTAINER_COMPONENT_BASE_HPP_ #include "rive/component.hpp" -namespace rive -{ - class ContainerComponentBase : public Component - { +namespace rive { + class ContainerComponentBase : public Component { protected: typedef Component Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case ContainerComponentBase::typeKey: case ComponentBase::typeKey: return true;
diff --git a/include/rive/generated/core_registry.hpp b/include/rive/generated/core_registry.hpp index 65cbf89..8ea8e18 100644 --- a/include/rive/generated/core_registry.hpp +++ b/include/rive/generated/core_registry.hpp
@@ -101,15 +101,11 @@ #include "rive/shapes/triangle.hpp" #include "rive/transform_component.hpp" #include "rive/world_transform_component.hpp" -namespace rive -{ - class CoreRegistry - { +namespace rive { + class CoreRegistry { public: - static Core* makeCoreInstance(int typeKey) - { - switch (typeKey) - { + static Core* makeCoreInstance(int typeKey) { + switch (typeKey) { case DrawTargetBase::typeKey: return new DrawTarget(); case DistanceConstraintBase::typeKey: @@ -255,10 +251,9 @@ } return nullptr; } - static void setString(Core* object, int propertyKey, std::string value) - { - switch (propertyKey) - { + static void + setString(Core* object, int propertyKey, std::string value) { + switch (propertyKey) { case ComponentBase::namePropertyKey: object->as<ComponentBase>()->name(value); break; @@ -273,10 +268,8 @@ break; } } - static void setUint(Core* object, int propertyKey, int value) - { - switch (propertyKey) - { + static void setUint(Core* object, int propertyKey, int value) { + switch (propertyKey) { case ComponentBase::parentIdPropertyKey: object->as<ComponentBase>()->parentId(value); break; @@ -443,10 +436,8 @@ break; } } - static void setDouble(Core* object, int propertyKey, float value) - { - switch (propertyKey) - { + static void setDouble(Core* object, int propertyKey, float value) { + switch (propertyKey) { case ConstraintBase::strengthPropertyKey: object->as<ConstraintBase>()->strength(value); break; @@ -698,10 +689,8 @@ break; } } - static void setBool(Core* object, int propertyKey, bool value) - { - switch (propertyKey) - { + static void setBool(Core* object, int propertyKey, bool value) { + switch (propertyKey) { case TransformComponentConstraintBase::offsetPropertyKey: object->as<TransformComponentConstraintBase>()->offset( value); @@ -763,10 +752,8 @@ break; } } - static void setColor(Core* object, int propertyKey, int value) - { - switch (propertyKey) - { + static void setColor(Core* object, int propertyKey, int value) { + switch (propertyKey) { case KeyFrameColorBase::valuePropertyKey: object->as<KeyFrameColorBase>()->value(value); break; @@ -779,19 +766,15 @@ } } static void - setBytes(Core* object, int propertyKey, std::vector<uint8_t> value) - { - switch (propertyKey) - { + setBytes(Core* object, int propertyKey, std::vector<uint8_t> value) { + switch (propertyKey) { case FileAssetContentsBase::bytesPropertyKey: object->as<FileAssetContentsBase>()->bytes(value); break; } } - static std::string getString(Core* object, int propertyKey) - { - switch (propertyKey) - { + static std::string getString(Core* object, int propertyKey) { + switch (propertyKey) { case ComponentBase::namePropertyKey: return object->as<ComponentBase>()->name(); case StateMachineComponentBase::namePropertyKey: @@ -803,10 +786,8 @@ } return ""; } - static int getUint(Core* object, int propertyKey) - { - switch (propertyKey) - { + static int getUint(Core* object, int propertyKey) { + switch (propertyKey) { case ComponentBase::parentIdPropertyKey: return object->as<ComponentBase>()->parentId(); case DrawTargetBase::drawableIdPropertyKey: @@ -922,10 +903,8 @@ } return 0; } - static float getDouble(Core* object, int propertyKey) - { - switch (propertyKey) - { + static float getDouble(Core* object, int propertyKey) { + switch (propertyKey) { case ConstraintBase::strengthPropertyKey: return object->as<ConstraintBase>()->strength(); case DistanceConstraintBase::distancePropertyKey: @@ -1099,10 +1078,8 @@ } return 0.0f; } - static bool getBool(Core* object, int propertyKey) - { - switch (propertyKey) - { + static bool getBool(Core* object, int propertyKey) { + switch (propertyKey) { case TransformComponentConstraintBase::offsetPropertyKey: return object->as<TransformComponentConstraintBase>() ->offset(); @@ -1149,10 +1126,8 @@ } return false; } - static int getColor(Core* object, int propertyKey) - { - switch (propertyKey) - { + static int getColor(Core* object, int propertyKey) { + switch (propertyKey) { case KeyFrameColorBase::valuePropertyKey: return object->as<KeyFrameColorBase>()->value(); case SolidColorBase::colorValuePropertyKey: @@ -1162,19 +1137,15 @@ } return 0; } - static std::vector<uint8_t> getBytes(Core* object, int propertyKey) - { - switch (propertyKey) - { + static std::vector<uint8_t> getBytes(Core* object, int propertyKey) { + switch (propertyKey) { case FileAssetContentsBase::bytesPropertyKey: return object->as<FileAssetContentsBase>()->bytes(); } return std::vector<uint8_t>(); } - static int propertyFieldId(int propertyKey) - { - switch (propertyKey) - { + static int propertyFieldId(int propertyKey) { + switch (propertyKey) { case ComponentBase::namePropertyKey: case StateMachineComponentBase::namePropertyKey: case AnimationBase::namePropertyKey:
diff --git a/include/rive/generated/draw_rules_base.hpp b/include/rive/generated/draw_rules_base.hpp index 112d2fe..4c2b47f 100644 --- a/include/rive/generated/draw_rules_base.hpp +++ b/include/rive/generated/draw_rules_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_DRAW_RULES_BASE_HPP_ #include "rive/container_component.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class DrawRulesBase : public ContainerComponent - { +namespace rive { + class DrawRulesBase : public ContainerComponent { protected: typedef ContainerComponent Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case DrawRulesBase::typeKey: case ContainerComponentBase::typeKey: case ComponentBase::typeKey: @@ -36,10 +32,8 @@ public: inline int drawTargetId() const { return m_DrawTargetId; } - void drawTargetId(int value) - { - if (m_DrawTargetId == value) - { + void drawTargetId(int value) { + if (m_DrawTargetId == value) { return; } m_DrawTargetId = value; @@ -47,16 +41,13 @@ } Core* clone() const override; - void copy(const DrawRulesBase& object) - { + void copy(const DrawRulesBase& object) { m_DrawTargetId = object.m_DrawTargetId; ContainerComponent::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case drawTargetIdPropertyKey: m_DrawTargetId = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/draw_target_base.hpp b/include/rive/generated/draw_target_base.hpp index aadcb6d..aa996e1 100644 --- a/include/rive/generated/draw_target_base.hpp +++ b/include/rive/generated/draw_target_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_DRAW_TARGET_BASE_HPP_ #include "rive/component.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class DrawTargetBase : public Component - { +namespace rive { + class DrawTargetBase : public Component { protected: typedef Component Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case DrawTargetBase::typeKey: case ComponentBase::typeKey: return true; @@ -37,10 +33,8 @@ public: inline int drawableId() const { return m_DrawableId; } - void drawableId(int value) - { - if (m_DrawableId == value) - { + void drawableId(int value) { + if (m_DrawableId == value) { return; } m_DrawableId = value; @@ -48,10 +42,8 @@ } inline int placementValue() const { return m_PlacementValue; } - void placementValue(int value) - { - if (m_PlacementValue == value) - { + void placementValue(int value) { + if (m_PlacementValue == value) { return; } m_PlacementValue = value; @@ -59,17 +51,14 @@ } Core* clone() const override; - void copy(const DrawTargetBase& object) - { + void copy(const DrawTargetBase& object) { m_DrawableId = object.m_DrawableId; m_PlacementValue = object.m_PlacementValue; Component::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case drawableIdPropertyKey: m_DrawableId = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/drawable_base.hpp b/include/rive/generated/drawable_base.hpp index 1652915..c684594 100644 --- a/include/rive/generated/drawable_base.hpp +++ b/include/rive/generated/drawable_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_DRAWABLE_BASE_HPP_ #include "rive/core/field_types/core_uint_type.hpp" #include "rive/node.hpp" -namespace rive -{ - class DrawableBase : public Node - { +namespace rive { + class DrawableBase : public Node { protected: typedef Node Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case DrawableBase::typeKey: case NodeBase::typeKey: case TransformComponentBase::typeKey: @@ -41,10 +37,8 @@ public: inline int blendModeValue() const { return m_BlendModeValue; } - void blendModeValue(int value) - { - if (m_BlendModeValue == value) - { + void blendModeValue(int value) { + if (m_BlendModeValue == value) { return; } m_BlendModeValue = value; @@ -52,27 +46,22 @@ } inline int drawableFlags() const { return m_DrawableFlags; } - void drawableFlags(int value) - { - if (m_DrawableFlags == value) - { + void drawableFlags(int value) { + if (m_DrawableFlags == value) { return; } m_DrawableFlags = value; drawableFlagsChanged(); } - void copy(const DrawableBase& object) - { + void copy(const DrawableBase& object) { m_BlendModeValue = object.m_BlendModeValue; m_DrawableFlags = object.m_DrawableFlags; Node::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case blendModeValuePropertyKey: m_BlendModeValue = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/nested_animation_base.hpp b/include/rive/generated/nested_animation_base.hpp index 273a6c7..7d34a04 100644 --- a/include/rive/generated/nested_animation_base.hpp +++ b/include/rive/generated/nested_animation_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_NESTED_ANIMATION_BASE_HPP_ #include "rive/component.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class NestedAnimationBase : public Component - { +namespace rive { + class NestedAnimationBase : public Component { protected: typedef Component Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case NestedAnimationBase::typeKey: case ComponentBase::typeKey: return true; @@ -35,26 +31,21 @@ public: inline int animationId() const { return m_AnimationId; } - void animationId(int value) - { - if (m_AnimationId == value) - { + void animationId(int value) { + if (m_AnimationId == value) { return; } m_AnimationId = value; animationIdChanged(); } - void copy(const NestedAnimationBase& object) - { + void copy(const NestedAnimationBase& object) { m_AnimationId = object.m_AnimationId; Component::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case animationIdPropertyKey: m_AnimationId = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/nested_artboard_base.hpp b/include/rive/generated/nested_artboard_base.hpp index 7b48d0a..6c41396 100644 --- a/include/rive/generated/nested_artboard_base.hpp +++ b/include/rive/generated/nested_artboard_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_NESTED_ARTBOARD_BASE_HPP_ #include "rive/core/field_types/core_uint_type.hpp" #include "rive/drawable.hpp" -namespace rive -{ - class NestedArtboardBase : public Drawable - { +namespace rive { + class NestedArtboardBase : public Drawable { protected: typedef Drawable Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case NestedArtboardBase::typeKey: case DrawableBase::typeKey: case NodeBase::typeKey: @@ -40,10 +36,8 @@ public: inline int artboardId() const { return m_ArtboardId; } - void artboardId(int value) - { - if (m_ArtboardId == value) - { + void artboardId(int value) { + if (m_ArtboardId == value) { return; } m_ArtboardId = value; @@ -51,16 +45,13 @@ } Core* clone() const override; - void copy(const NestedArtboardBase& object) - { + void copy(const NestedArtboardBase& object) { m_ArtboardId = object.m_ArtboardId; Drawable::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case artboardIdPropertyKey: m_ArtboardId = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/node_base.hpp b/include/rive/generated/node_base.hpp index f88b20e..6e197f7 100644 --- a/include/rive/generated/node_base.hpp +++ b/include/rive/generated/node_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_NODE_BASE_HPP_ #include "rive/core/field_types/core_double_type.hpp" #include "rive/transform_component.hpp" -namespace rive -{ - class NodeBase : public TransformComponent - { +namespace rive { + class NodeBase : public TransformComponent { protected: typedef TransformComponent Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case NodeBase::typeKey: case TransformComponentBase::typeKey: case WorldTransformComponentBase::typeKey: @@ -40,10 +36,8 @@ public: inline float x() const override { return m_X; } - void x(float value) - { - if (m_X == value) - { + void x(float value) { + if (m_X == value) { return; } m_X = value; @@ -51,10 +45,8 @@ } inline float y() const override { return m_Y; } - void y(float value) - { - if (m_Y == value) - { + void y(float value) { + if (m_Y == value) { return; } m_Y = value; @@ -62,17 +54,14 @@ } Core* clone() const override; - void copy(const NodeBase& object) - { + void copy(const NodeBase& object) { m_X = object.m_X; m_Y = object.m_Y; TransformComponent::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case xPropertyKey: m_X = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/shapes/clipping_shape_base.hpp b/include/rive/generated/shapes/clipping_shape_base.hpp index 5fbe5b2..42672ad 100644 --- a/include/rive/generated/shapes/clipping_shape_base.hpp +++ b/include/rive/generated/shapes/clipping_shape_base.hpp
@@ -3,10 +3,8 @@ #include "rive/component.hpp" #include "rive/core/field_types/core_bool_type.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class ClippingShapeBase : public Component - { +namespace rive { + class ClippingShapeBase : public Component { protected: typedef Component Super; @@ -15,10 +13,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case ClippingShapeBase::typeKey: case ComponentBase::typeKey: return true; @@ -40,10 +36,8 @@ public: inline int sourceId() const { return m_SourceId; } - void sourceId(int value) - { - if (m_SourceId == value) - { + void sourceId(int value) { + if (m_SourceId == value) { return; } m_SourceId = value; @@ -51,10 +45,8 @@ } inline int fillRule() const { return m_FillRule; } - void fillRule(int value) - { - if (m_FillRule == value) - { + void fillRule(int value) { + if (m_FillRule == value) { return; } m_FillRule = value; @@ -62,10 +54,8 @@ } inline bool isVisible() const { return m_IsVisible; } - void isVisible(bool value) - { - if (m_IsVisible == value) - { + void isVisible(bool value) { + if (m_IsVisible == value) { return; } m_IsVisible = value; @@ -73,18 +63,15 @@ } Core* clone() const override; - void copy(const ClippingShapeBase& object) - { + void copy(const ClippingShapeBase& object) { m_SourceId = object.m_SourceId; m_FillRule = object.m_FillRule; m_IsVisible = object.m_IsVisible; Component::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case sourceIdPropertyKey: m_SourceId = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/shapes/cubic_asymmetric_vertex_base.hpp b/include/rive/generated/shapes/cubic_asymmetric_vertex_base.hpp index 4bbcaf4..793a509 100644 --- a/include/rive/generated/shapes/cubic_asymmetric_vertex_base.hpp +++ b/include/rive/generated/shapes/cubic_asymmetric_vertex_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_CUBIC_ASYMMETRIC_VERTEX_BASE_HPP_ #include "rive/core/field_types/core_double_type.hpp" #include "rive/shapes/cubic_vertex.hpp" -namespace rive -{ - class CubicAsymmetricVertexBase : public CubicVertex - { +namespace rive { + class CubicAsymmetricVertexBase : public CubicVertex { protected: typedef CubicVertex Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case CubicAsymmetricVertexBase::typeKey: case CubicVertexBase::typeKey: case PathVertexBase::typeKey: @@ -42,10 +38,8 @@ public: inline float rotation() const { return m_Rotation; } - void rotation(float value) - { - if (m_Rotation == value) - { + void rotation(float value) { + if (m_Rotation == value) { return; } m_Rotation = value; @@ -53,10 +47,8 @@ } inline float inDistance() const { return m_InDistance; } - void inDistance(float value) - { - if (m_InDistance == value) - { + void inDistance(float value) { + if (m_InDistance == value) { return; } m_InDistance = value; @@ -64,10 +56,8 @@ } inline float outDistance() const { return m_OutDistance; } - void outDistance(float value) - { - if (m_OutDistance == value) - { + void outDistance(float value) { + if (m_OutDistance == value) { return; } m_OutDistance = value; @@ -75,18 +65,15 @@ } Core* clone() const override; - void copy(const CubicAsymmetricVertexBase& object) - { + void copy(const CubicAsymmetricVertexBase& object) { m_Rotation = object.m_Rotation; m_InDistance = object.m_InDistance; m_OutDistance = object.m_OutDistance; CubicVertex::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case rotationPropertyKey: m_Rotation = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/shapes/cubic_detached_vertex_base.hpp b/include/rive/generated/shapes/cubic_detached_vertex_base.hpp index dec9bce..109eae0 100644 --- a/include/rive/generated/shapes/cubic_detached_vertex_base.hpp +++ b/include/rive/generated/shapes/cubic_detached_vertex_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_CUBIC_DETACHED_VERTEX_BASE_HPP_ #include "rive/core/field_types/core_double_type.hpp" #include "rive/shapes/cubic_vertex.hpp" -namespace rive -{ - class CubicDetachedVertexBase : public CubicVertex - { +namespace rive { + class CubicDetachedVertexBase : public CubicVertex { protected: typedef CubicVertex Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case CubicDetachedVertexBase::typeKey: case CubicVertexBase::typeKey: case PathVertexBase::typeKey: @@ -44,10 +40,8 @@ public: inline float inRotation() const { return m_InRotation; } - void inRotation(float value) - { - if (m_InRotation == value) - { + void inRotation(float value) { + if (m_InRotation == value) { return; } m_InRotation = value; @@ -55,10 +49,8 @@ } inline float inDistance() const { return m_InDistance; } - void inDistance(float value) - { - if (m_InDistance == value) - { + void inDistance(float value) { + if (m_InDistance == value) { return; } m_InDistance = value; @@ -66,10 +58,8 @@ } inline float outRotation() const { return m_OutRotation; } - void outRotation(float value) - { - if (m_OutRotation == value) - { + void outRotation(float value) { + if (m_OutRotation == value) { return; } m_OutRotation = value; @@ -77,10 +67,8 @@ } inline float outDistance() const { return m_OutDistance; } - void outDistance(float value) - { - if (m_OutDistance == value) - { + void outDistance(float value) { + if (m_OutDistance == value) { return; } m_OutDistance = value; @@ -88,8 +76,7 @@ } Core* clone() const override; - void copy(const CubicDetachedVertexBase& object) - { + void copy(const CubicDetachedVertexBase& object) { m_InRotation = object.m_InRotation; m_InDistance = object.m_InDistance; m_OutRotation = object.m_OutRotation; @@ -97,10 +84,8 @@ CubicVertex::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case inRotationPropertyKey: m_InRotation = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/shapes/cubic_mirrored_vertex_base.hpp b/include/rive/generated/shapes/cubic_mirrored_vertex_base.hpp index be2502b..5e614f1 100644 --- a/include/rive/generated/shapes/cubic_mirrored_vertex_base.hpp +++ b/include/rive/generated/shapes/cubic_mirrored_vertex_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_CUBIC_MIRRORED_VERTEX_BASE_HPP_ #include "rive/core/field_types/core_double_type.hpp" #include "rive/shapes/cubic_vertex.hpp" -namespace rive -{ - class CubicMirroredVertexBase : public CubicVertex - { +namespace rive { + class CubicMirroredVertexBase : public CubicVertex { protected: typedef CubicVertex Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case CubicMirroredVertexBase::typeKey: case CubicVertexBase::typeKey: case PathVertexBase::typeKey: @@ -40,10 +36,8 @@ public: inline float rotation() const { return m_Rotation; } - void rotation(float value) - { - if (m_Rotation == value) - { + void rotation(float value) { + if (m_Rotation == value) { return; } m_Rotation = value; @@ -51,10 +45,8 @@ } inline float distance() const { return m_Distance; } - void distance(float value) - { - if (m_Distance == value) - { + void distance(float value) { + if (m_Distance == value) { return; } m_Distance = value; @@ -62,17 +54,14 @@ } Core* clone() const override; - void copy(const CubicMirroredVertexBase& object) - { + void copy(const CubicMirroredVertexBase& object) { m_Rotation = object.m_Rotation; m_Distance = object.m_Distance; CubicVertex::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case rotationPropertyKey: m_Rotation = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/shapes/cubic_vertex_base.hpp b/include/rive/generated/shapes/cubic_vertex_base.hpp index 3a0f2a1..fe02cca 100644 --- a/include/rive/generated/shapes/cubic_vertex_base.hpp +++ b/include/rive/generated/shapes/cubic_vertex_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_CUBIC_VERTEX_BASE_HPP_ #define _RIVE_CUBIC_VERTEX_BASE_HPP_ #include "rive/shapes/path_vertex.hpp" -namespace rive -{ - class CubicVertexBase : public PathVertex - { +namespace rive { + class CubicVertexBase : public PathVertex { protected: typedef PathVertex Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case CubicVertexBase::typeKey: case PathVertexBase::typeKey: case ContainerComponentBase::typeKey:
diff --git a/include/rive/generated/shapes/ellipse_base.hpp b/include/rive/generated/shapes/ellipse_base.hpp index 65584eb..d7ee43d 100644 --- a/include/rive/generated/shapes/ellipse_base.hpp +++ b/include/rive/generated/shapes/ellipse_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_ELLIPSE_BASE_HPP_ #define _RIVE_ELLIPSE_BASE_HPP_ #include "rive/shapes/parametric_path.hpp" -namespace rive -{ - class EllipseBase : public ParametricPath - { +namespace rive { + class EllipseBase : public ParametricPath { protected: typedef ParametricPath Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case EllipseBase::typeKey: case ParametricPathBase::typeKey: case PathBase::typeKey:
diff --git a/include/rive/generated/shapes/image_base.hpp b/include/rive/generated/shapes/image_base.hpp index c3ec431..b8c33bd 100644 --- a/include/rive/generated/shapes/image_base.hpp +++ b/include/rive/generated/shapes/image_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_IMAGE_BASE_HPP_ #include "rive/core/field_types/core_uint_type.hpp" #include "rive/drawable.hpp" -namespace rive -{ - class ImageBase : public Drawable - { +namespace rive { + class ImageBase : public Drawable { protected: typedef Drawable Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case ImageBase::typeKey: case DrawableBase::typeKey: case NodeBase::typeKey: @@ -40,10 +36,8 @@ public: inline int assetId() const { return m_AssetId; } - void assetId(int value) - { - if (m_AssetId == value) - { + void assetId(int value) { + if (m_AssetId == value) { return; } m_AssetId = value; @@ -51,16 +45,13 @@ } Core* clone() const override; - void copy(const ImageBase& object) - { + void copy(const ImageBase& object) { m_AssetId = object.m_AssetId; Drawable::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case assetIdPropertyKey: m_AssetId = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/shapes/paint/fill_base.hpp b/include/rive/generated/shapes/paint/fill_base.hpp index 05990f7..171b606 100644 --- a/include/rive/generated/shapes/paint/fill_base.hpp +++ b/include/rive/generated/shapes/paint/fill_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_FILL_BASE_HPP_ #include "rive/core/field_types/core_uint_type.hpp" #include "rive/shapes/paint/shape_paint.hpp" -namespace rive -{ - class FillBase : public ShapePaint - { +namespace rive { + class FillBase : public ShapePaint { protected: typedef ShapePaint Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case FillBase::typeKey: case ShapePaintBase::typeKey: case ContainerComponentBase::typeKey: @@ -37,10 +33,8 @@ public: inline int fillRule() const { return m_FillRule; } - void fillRule(int value) - { - if (m_FillRule == value) - { + void fillRule(int value) { + if (m_FillRule == value) { return; } m_FillRule = value; @@ -48,16 +42,13 @@ } Core* clone() const override; - void copy(const FillBase& object) - { + void copy(const FillBase& object) { m_FillRule = object.m_FillRule; ShapePaint::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case fillRulePropertyKey: m_FillRule = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/shapes/paint/gradient_stop_base.hpp b/include/rive/generated/shapes/paint/gradient_stop_base.hpp index 367a5b0..e737edb 100644 --- a/include/rive/generated/shapes/paint/gradient_stop_base.hpp +++ b/include/rive/generated/shapes/paint/gradient_stop_base.hpp
@@ -3,10 +3,8 @@ #include "rive/component.hpp" #include "rive/core/field_types/core_color_type.hpp" #include "rive/core/field_types/core_double_type.hpp" -namespace rive -{ - class GradientStopBase : public Component - { +namespace rive { + class GradientStopBase : public Component { protected: typedef Component Super; @@ -15,10 +13,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case GradientStopBase::typeKey: case ComponentBase::typeKey: return true; @@ -38,10 +34,8 @@ public: inline int colorValue() const { return m_ColorValue; } - void colorValue(int value) - { - if (m_ColorValue == value) - { + void colorValue(int value) { + if (m_ColorValue == value) { return; } m_ColorValue = value; @@ -49,10 +43,8 @@ } inline float position() const { return m_Position; } - void position(float value) - { - if (m_Position == value) - { + void position(float value) { + if (m_Position == value) { return; } m_Position = value; @@ -60,17 +52,14 @@ } Core* clone() const override; - void copy(const GradientStopBase& object) - { + void copy(const GradientStopBase& object) { m_ColorValue = object.m_ColorValue; m_Position = object.m_Position; Component::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case colorValuePropertyKey: m_ColorValue = CoreColorType::deserialize(reader); return true;
diff --git a/include/rive/generated/shapes/paint/linear_gradient_base.hpp b/include/rive/generated/shapes/paint/linear_gradient_base.hpp index 2c829f9..4034ad8 100644 --- a/include/rive/generated/shapes/paint/linear_gradient_base.hpp +++ b/include/rive/generated/shapes/paint/linear_gradient_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_LINEAR_GRADIENT_BASE_HPP_ #include "rive/container_component.hpp" #include "rive/core/field_types/core_double_type.hpp" -namespace rive -{ - class LinearGradientBase : public ContainerComponent - { +namespace rive { + class LinearGradientBase : public ContainerComponent { protected: typedef ContainerComponent Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case LinearGradientBase::typeKey: case ContainerComponentBase::typeKey: case ComponentBase::typeKey: @@ -44,10 +40,8 @@ public: inline float startX() const { return m_StartX; } - void startX(float value) - { - if (m_StartX == value) - { + void startX(float value) { + if (m_StartX == value) { return; } m_StartX = value; @@ -55,10 +49,8 @@ } inline float startY() const { return m_StartY; } - void startY(float value) - { - if (m_StartY == value) - { + void startY(float value) { + if (m_StartY == value) { return; } m_StartY = value; @@ -66,10 +58,8 @@ } inline float endX() const { return m_EndX; } - void endX(float value) - { - if (m_EndX == value) - { + void endX(float value) { + if (m_EndX == value) { return; } m_EndX = value; @@ -77,10 +67,8 @@ } inline float endY() const { return m_EndY; } - void endY(float value) - { - if (m_EndY == value) - { + void endY(float value) { + if (m_EndY == value) { return; } m_EndY = value; @@ -88,10 +76,8 @@ } inline float opacity() const { return m_Opacity; } - void opacity(float value) - { - if (m_Opacity == value) - { + void opacity(float value) { + if (m_Opacity == value) { return; } m_Opacity = value; @@ -99,8 +85,7 @@ } Core* clone() const override; - void copy(const LinearGradientBase& object) - { + void copy(const LinearGradientBase& object) { m_StartX = object.m_StartX; m_StartY = object.m_StartY; m_EndX = object.m_EndX; @@ -109,10 +94,8 @@ ContainerComponent::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case startXPropertyKey: m_StartX = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/shapes/paint/radial_gradient_base.hpp b/include/rive/generated/shapes/paint/radial_gradient_base.hpp index d898c8b..aae102c 100644 --- a/include/rive/generated/shapes/paint/radial_gradient_base.hpp +++ b/include/rive/generated/shapes/paint/radial_gradient_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_RADIAL_GRADIENT_BASE_HPP_ #define _RIVE_RADIAL_GRADIENT_BASE_HPP_ #include "rive/shapes/paint/linear_gradient.hpp" -namespace rive -{ - class RadialGradientBase : public LinearGradient - { +namespace rive { + class RadialGradientBase : public LinearGradient { protected: typedef LinearGradient Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case RadialGradientBase::typeKey: case LinearGradientBase::typeKey: case ContainerComponentBase::typeKey:
diff --git a/include/rive/generated/shapes/paint/shape_paint_base.hpp b/include/rive/generated/shapes/paint/shape_paint_base.hpp index 5d7ce96..fd05ef0 100644 --- a/include/rive/generated/shapes/paint/shape_paint_base.hpp +++ b/include/rive/generated/shapes/paint/shape_paint_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_SHAPE_PAINT_BASE_HPP_ #include "rive/container_component.hpp" #include "rive/core/field_types/core_bool_type.hpp" -namespace rive -{ - class ShapePaintBase : public ContainerComponent - { +namespace rive { + class ShapePaintBase : public ContainerComponent { protected: typedef ContainerComponent Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case ShapePaintBase::typeKey: case ContainerComponentBase::typeKey: case ComponentBase::typeKey: @@ -36,26 +32,21 @@ public: virtual bool isVisible() const { return m_IsVisible; } - void isVisible(bool value) - { - if (m_IsVisible == value) - { + void isVisible(bool value) { + if (m_IsVisible == value) { return; } m_IsVisible = value; isVisibleChanged(); } - void copy(const ShapePaintBase& object) - { + void copy(const ShapePaintBase& object) { m_IsVisible = object.m_IsVisible; ContainerComponent::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case isVisiblePropertyKey: m_IsVisible = CoreBoolType::deserialize(reader); return true;
diff --git a/include/rive/generated/shapes/paint/solid_color_base.hpp b/include/rive/generated/shapes/paint/solid_color_base.hpp index c91a0e6..bc104ee 100644 --- a/include/rive/generated/shapes/paint/solid_color_base.hpp +++ b/include/rive/generated/shapes/paint/solid_color_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_SOLID_COLOR_BASE_HPP_ #include "rive/component.hpp" #include "rive/core/field_types/core_color_type.hpp" -namespace rive -{ - class SolidColorBase : public Component - { +namespace rive { + class SolidColorBase : public Component { protected: typedef Component Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case SolidColorBase::typeKey: case ComponentBase::typeKey: return true; @@ -35,10 +31,8 @@ public: inline int colorValue() const { return m_ColorValue; } - void colorValue(int value) - { - if (m_ColorValue == value) - { + void colorValue(int value) { + if (m_ColorValue == value) { return; } m_ColorValue = value; @@ -46,16 +40,13 @@ } Core* clone() const override; - void copy(const SolidColorBase& object) - { + void copy(const SolidColorBase& object) { m_ColorValue = object.m_ColorValue; Component::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case colorValuePropertyKey: m_ColorValue = CoreColorType::deserialize(reader); return true;
diff --git a/include/rive/generated/shapes/paint/stroke_base.hpp b/include/rive/generated/shapes/paint/stroke_base.hpp index 2b4d973..85d64d1 100644 --- a/include/rive/generated/shapes/paint/stroke_base.hpp +++ b/include/rive/generated/shapes/paint/stroke_base.hpp
@@ -4,10 +4,8 @@ #include "rive/core/field_types/core_double_type.hpp" #include "rive/core/field_types/core_uint_type.hpp" #include "rive/shapes/paint/shape_paint.hpp" -namespace rive -{ - class StrokeBase : public ShapePaint - { +namespace rive { + class StrokeBase : public ShapePaint { protected: typedef ShapePaint Super; @@ -16,10 +14,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case StrokeBase::typeKey: case ShapePaintBase::typeKey: case ContainerComponentBase::typeKey: @@ -45,10 +41,8 @@ public: inline float thickness() const { return m_Thickness; } - void thickness(float value) - { - if (m_Thickness == value) - { + void thickness(float value) { + if (m_Thickness == value) { return; } m_Thickness = value; @@ -56,10 +50,8 @@ } inline int cap() const { return m_Cap; } - void cap(int value) - { - if (m_Cap == value) - { + void cap(int value) { + if (m_Cap == value) { return; } m_Cap = value; @@ -67,24 +59,19 @@ } inline int join() const { return m_Join; } - void join(int value) - { - if (m_Join == value) - { + void join(int value) { + if (m_Join == value) { return; } m_Join = value; joinChanged(); } - inline bool transformAffectsStroke() const - { + inline bool transformAffectsStroke() const { return m_TransformAffectsStroke; } - void transformAffectsStroke(bool value) - { - if (m_TransformAffectsStroke == value) - { + void transformAffectsStroke(bool value) { + if (m_TransformAffectsStroke == value) { return; } m_TransformAffectsStroke = value; @@ -92,8 +79,7 @@ } Core* clone() const override; - void copy(const StrokeBase& object) - { + void copy(const StrokeBase& object) { m_Thickness = object.m_Thickness; m_Cap = object.m_Cap; m_Join = object.m_Join; @@ -101,10 +87,8 @@ ShapePaint::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case thicknessPropertyKey: m_Thickness = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/shapes/paint/trim_path_base.hpp b/include/rive/generated/shapes/paint/trim_path_base.hpp index 321a418..e09a621 100644 --- a/include/rive/generated/shapes/paint/trim_path_base.hpp +++ b/include/rive/generated/shapes/paint/trim_path_base.hpp
@@ -3,10 +3,8 @@ #include "rive/component.hpp" #include "rive/core/field_types/core_double_type.hpp" #include "rive/core/field_types/core_uint_type.hpp" -namespace rive -{ - class TrimPathBase : public Component - { +namespace rive { + class TrimPathBase : public Component { protected: typedef Component Super; @@ -15,10 +13,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case TrimPathBase::typeKey: case ComponentBase::typeKey: return true; @@ -42,10 +38,8 @@ public: inline float start() const { return m_Start; } - void start(float value) - { - if (m_Start == value) - { + void start(float value) { + if (m_Start == value) { return; } m_Start = value; @@ -53,10 +47,8 @@ } inline float end() const { return m_End; } - void end(float value) - { - if (m_End == value) - { + void end(float value) { + if (m_End == value) { return; } m_End = value; @@ -64,10 +56,8 @@ } inline float offset() const { return m_Offset; } - void offset(float value) - { - if (m_Offset == value) - { + void offset(float value) { + if (m_Offset == value) { return; } m_Offset = value; @@ -75,10 +65,8 @@ } inline int modeValue() const { return m_ModeValue; } - void modeValue(int value) - { - if (m_ModeValue == value) - { + void modeValue(int value) { + if (m_ModeValue == value) { return; } m_ModeValue = value; @@ -86,8 +74,7 @@ } Core* clone() const override; - void copy(const TrimPathBase& object) - { + void copy(const TrimPathBase& object) { m_Start = object.m_Start; m_End = object.m_End; m_Offset = object.m_Offset; @@ -95,10 +82,8 @@ Component::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case startPropertyKey: m_Start = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/shapes/parametric_path_base.hpp b/include/rive/generated/shapes/parametric_path_base.hpp index 0d36ca1..7651533 100644 --- a/include/rive/generated/shapes/parametric_path_base.hpp +++ b/include/rive/generated/shapes/parametric_path_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_PARAMETRIC_PATH_BASE_HPP_ #include "rive/core/field_types/core_double_type.hpp" #include "rive/shapes/path.hpp" -namespace rive -{ - class ParametricPathBase : public Path - { +namespace rive { + class ParametricPathBase : public Path { protected: typedef Path Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case ParametricPathBase::typeKey: case PathBase::typeKey: case NodeBase::typeKey: @@ -46,10 +42,8 @@ public: inline float width() const { return m_Width; } - void width(float value) - { - if (m_Width == value) - { + void width(float value) { + if (m_Width == value) { return; } m_Width = value; @@ -57,10 +51,8 @@ } inline float height() const { return m_Height; } - void height(float value) - { - if (m_Height == value) - { + void height(float value) { + if (m_Height == value) { return; } m_Height = value; @@ -68,10 +60,8 @@ } inline float originX() const { return m_OriginX; } - void originX(float value) - { - if (m_OriginX == value) - { + void originX(float value) { + if (m_OriginX == value) { return; } m_OriginX = value; @@ -79,18 +69,15 @@ } inline float originY() const { return m_OriginY; } - void originY(float value) - { - if (m_OriginY == value) - { + void originY(float value) { + if (m_OriginY == value) { return; } m_OriginY = value; originYChanged(); } - void copy(const ParametricPathBase& object) - { + void copy(const ParametricPathBase& object) { m_Width = object.m_Width; m_Height = object.m_Height; m_OriginX = object.m_OriginX; @@ -98,10 +85,8 @@ Path::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case widthPropertyKey: m_Width = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/shapes/path_base.hpp b/include/rive/generated/shapes/path_base.hpp index efc7dd1..76d960a 100644 --- a/include/rive/generated/shapes/path_base.hpp +++ b/include/rive/generated/shapes/path_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_PATH_BASE_HPP_ #include "rive/core/field_types/core_uint_type.hpp" #include "rive/node.hpp" -namespace rive -{ - class PathBase : public Node - { +namespace rive { + class PathBase : public Node { protected: typedef Node Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case PathBase::typeKey: case NodeBase::typeKey: case TransformComponentBase::typeKey: @@ -39,26 +35,21 @@ public: inline int pathFlags() const { return m_PathFlags; } - void pathFlags(int value) - { - if (m_PathFlags == value) - { + void pathFlags(int value) { + if (m_PathFlags == value) { return; } m_PathFlags = value; pathFlagsChanged(); } - void copy(const PathBase& object) - { + void copy(const PathBase& object) { m_PathFlags = object.m_PathFlags; Node::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case pathFlagsPropertyKey: m_PathFlags = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/shapes/path_vertex_base.hpp b/include/rive/generated/shapes/path_vertex_base.hpp index b4ae419..6b864af 100644 --- a/include/rive/generated/shapes/path_vertex_base.hpp +++ b/include/rive/generated/shapes/path_vertex_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_PATH_VERTEX_BASE_HPP_ #include "rive/container_component.hpp" #include "rive/core/field_types/core_double_type.hpp" -namespace rive -{ - class PathVertexBase : public ContainerComponent - { +namespace rive { + class PathVertexBase : public ContainerComponent { protected: typedef ContainerComponent Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case PathVertexBase::typeKey: case ContainerComponentBase::typeKey: case ComponentBase::typeKey: @@ -38,10 +34,8 @@ public: inline float x() const { return m_X; } - void x(float value) - { - if (m_X == value) - { + void x(float value) { + if (m_X == value) { return; } m_X = value; @@ -49,27 +43,22 @@ } inline float y() const { return m_Y; } - void y(float value) - { - if (m_Y == value) - { + void y(float value) { + if (m_Y == value) { return; } m_Y = value; yChanged(); } - void copy(const PathVertexBase& object) - { + void copy(const PathVertexBase& object) { m_X = object.m_X; m_Y = object.m_Y; ContainerComponent::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case xPropertyKey: m_X = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/shapes/points_path_base.hpp b/include/rive/generated/shapes/points_path_base.hpp index d92d426..551c54d 100644 --- a/include/rive/generated/shapes/points_path_base.hpp +++ b/include/rive/generated/shapes/points_path_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_POINTS_PATH_BASE_HPP_ #include "rive/core/field_types/core_bool_type.hpp" #include "rive/shapes/path.hpp" -namespace rive -{ - class PointsPathBase : public Path - { +namespace rive { + class PointsPathBase : public Path { protected: typedef Path Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case PointsPathBase::typeKey: case PathBase::typeKey: case NodeBase::typeKey: @@ -40,10 +36,8 @@ public: inline bool isClosed() const { return m_IsClosed; } - void isClosed(bool value) - { - if (m_IsClosed == value) - { + void isClosed(bool value) { + if (m_IsClosed == value) { return; } m_IsClosed = value; @@ -51,16 +45,13 @@ } Core* clone() const override; - void copy(const PointsPathBase& object) - { + void copy(const PointsPathBase& object) { m_IsClosed = object.m_IsClosed; Path::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case isClosedPropertyKey: m_IsClosed = CoreBoolType::deserialize(reader); return true;
diff --git a/include/rive/generated/shapes/polygon_base.hpp b/include/rive/generated/shapes/polygon_base.hpp index 802f453..06695b3 100644 --- a/include/rive/generated/shapes/polygon_base.hpp +++ b/include/rive/generated/shapes/polygon_base.hpp
@@ -3,10 +3,8 @@ #include "rive/core/field_types/core_double_type.hpp" #include "rive/core/field_types/core_uint_type.hpp" #include "rive/shapes/parametric_path.hpp" -namespace rive -{ - class PolygonBase : public ParametricPath - { +namespace rive { + class PolygonBase : public ParametricPath { protected: typedef ParametricPath Super; @@ -15,10 +13,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case PolygonBase::typeKey: case ParametricPathBase::typeKey: case PathBase::typeKey: @@ -44,10 +40,8 @@ public: inline int points() const { return m_Points; } - void points(int value) - { - if (m_Points == value) - { + void points(int value) { + if (m_Points == value) { return; } m_Points = value; @@ -55,10 +49,8 @@ } inline float cornerRadius() const { return m_CornerRadius; } - void cornerRadius(float value) - { - if (m_CornerRadius == value) - { + void cornerRadius(float value) { + if (m_CornerRadius == value) { return; } m_CornerRadius = value; @@ -66,17 +58,14 @@ } Core* clone() const override; - void copy(const PolygonBase& object) - { + void copy(const PolygonBase& object) { m_Points = object.m_Points; m_CornerRadius = object.m_CornerRadius; ParametricPath::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case pointsPropertyKey: m_Points = CoreUintType::deserialize(reader); return true;
diff --git a/include/rive/generated/shapes/rectangle_base.hpp b/include/rive/generated/shapes/rectangle_base.hpp index 62dc2a5..f548e45 100644 --- a/include/rive/generated/shapes/rectangle_base.hpp +++ b/include/rive/generated/shapes/rectangle_base.hpp
@@ -3,10 +3,8 @@ #include "rive/core/field_types/core_bool_type.hpp" #include "rive/core/field_types/core_double_type.hpp" #include "rive/shapes/parametric_path.hpp" -namespace rive -{ - class RectangleBase : public ParametricPath - { +namespace rive { + class RectangleBase : public ParametricPath { protected: typedef ParametricPath Super; @@ -15,10 +13,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case RectangleBase::typeKey: case ParametricPathBase::typeKey: case PathBase::typeKey: @@ -50,10 +46,8 @@ public: inline bool linkCornerRadius() const { return m_LinkCornerRadius; } - void linkCornerRadius(bool value) - { - if (m_LinkCornerRadius == value) - { + void linkCornerRadius(bool value) { + if (m_LinkCornerRadius == value) { return; } m_LinkCornerRadius = value; @@ -61,10 +55,8 @@ } inline float cornerRadiusTL() const { return m_CornerRadiusTL; } - void cornerRadiusTL(float value) - { - if (m_CornerRadiusTL == value) - { + void cornerRadiusTL(float value) { + if (m_CornerRadiusTL == value) { return; } m_CornerRadiusTL = value; @@ -72,10 +64,8 @@ } inline float cornerRadiusTR() const { return m_CornerRadiusTR; } - void cornerRadiusTR(float value) - { - if (m_CornerRadiusTR == value) - { + void cornerRadiusTR(float value) { + if (m_CornerRadiusTR == value) { return; } m_CornerRadiusTR = value; @@ -83,10 +73,8 @@ } inline float cornerRadiusBL() const { return m_CornerRadiusBL; } - void cornerRadiusBL(float value) - { - if (m_CornerRadiusBL == value) - { + void cornerRadiusBL(float value) { + if (m_CornerRadiusBL == value) { return; } m_CornerRadiusBL = value; @@ -94,10 +82,8 @@ } inline float cornerRadiusBR() const { return m_CornerRadiusBR; } - void cornerRadiusBR(float value) - { - if (m_CornerRadiusBR == value) - { + void cornerRadiusBR(float value) { + if (m_CornerRadiusBR == value) { return; } m_CornerRadiusBR = value; @@ -105,8 +91,7 @@ } Core* clone() const override; - void copy(const RectangleBase& object) - { + void copy(const RectangleBase& object) { m_LinkCornerRadius = object.m_LinkCornerRadius; m_CornerRadiusTL = object.m_CornerRadiusTL; m_CornerRadiusTR = object.m_CornerRadiusTR; @@ -115,10 +100,8 @@ ParametricPath::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case linkCornerRadiusPropertyKey: m_LinkCornerRadius = CoreBoolType::deserialize(reader); return true;
diff --git a/include/rive/generated/shapes/shape_base.hpp b/include/rive/generated/shapes/shape_base.hpp index 26a36ad..efd2630 100644 --- a/include/rive/generated/shapes/shape_base.hpp +++ b/include/rive/generated/shapes/shape_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_SHAPE_BASE_HPP_ #define _RIVE_SHAPE_BASE_HPP_ #include "rive/drawable.hpp" -namespace rive -{ - class ShapeBase : public Drawable - { +namespace rive { + class ShapeBase : public Drawable { protected: typedef Drawable Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case ShapeBase::typeKey: case DrawableBase::typeKey: case NodeBase::typeKey:
diff --git a/include/rive/generated/shapes/star_base.hpp b/include/rive/generated/shapes/star_base.hpp index e466c5c..300c033 100644 --- a/include/rive/generated/shapes/star_base.hpp +++ b/include/rive/generated/shapes/star_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_STAR_BASE_HPP_ #include "rive/core/field_types/core_double_type.hpp" #include "rive/shapes/polygon.hpp" -namespace rive -{ - class StarBase : public Polygon - { +namespace rive { + class StarBase : public Polygon { protected: typedef Polygon Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case StarBase::typeKey: case PolygonBase::typeKey: case ParametricPathBase::typeKey: @@ -42,10 +38,8 @@ public: inline float innerRadius() const { return m_InnerRadius; } - void innerRadius(float value) - { - if (m_InnerRadius == value) - { + void innerRadius(float value) { + if (m_InnerRadius == value) { return; } m_InnerRadius = value; @@ -53,16 +47,13 @@ } Core* clone() const override; - void copy(const StarBase& object) - { + void copy(const StarBase& object) { m_InnerRadius = object.m_InnerRadius; Polygon::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case innerRadiusPropertyKey: m_InnerRadius = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/shapes/straight_vertex_base.hpp b/include/rive/generated/shapes/straight_vertex_base.hpp index 7602ddc..ebe1057 100644 --- a/include/rive/generated/shapes/straight_vertex_base.hpp +++ b/include/rive/generated/shapes/straight_vertex_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_STRAIGHT_VERTEX_BASE_HPP_ #include "rive/core/field_types/core_double_type.hpp" #include "rive/shapes/path_vertex.hpp" -namespace rive -{ - class StraightVertexBase : public PathVertex - { +namespace rive { + class StraightVertexBase : public PathVertex { protected: typedef PathVertex Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case StraightVertexBase::typeKey: case PathVertexBase::typeKey: case ContainerComponentBase::typeKey: @@ -37,10 +33,8 @@ public: inline float radius() const { return m_Radius; } - void radius(float value) - { - if (m_Radius == value) - { + void radius(float value) { + if (m_Radius == value) { return; } m_Radius = value; @@ -48,16 +42,13 @@ } Core* clone() const override; - void copy(const StraightVertexBase& object) - { + void copy(const StraightVertexBase& object) { m_Radius = object.m_Radius; PathVertex::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case radiusPropertyKey: m_Radius = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/shapes/triangle_base.hpp b/include/rive/generated/shapes/triangle_base.hpp index 4bed527..32bfc88 100644 --- a/include/rive/generated/shapes/triangle_base.hpp +++ b/include/rive/generated/shapes/triangle_base.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_TRIANGLE_BASE_HPP_ #define _RIVE_TRIANGLE_BASE_HPP_ #include "rive/shapes/parametric_path.hpp" -namespace rive -{ - class TriangleBase : public ParametricPath - { +namespace rive { + class TriangleBase : public ParametricPath { protected: typedef ParametricPath Super; @@ -13,10 +11,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case TriangleBase::typeKey: case ParametricPathBase::typeKey: case PathBase::typeKey:
diff --git a/include/rive/generated/transform_component_base.hpp b/include/rive/generated/transform_component_base.hpp index fe6f762..1899390 100644 --- a/include/rive/generated/transform_component_base.hpp +++ b/include/rive/generated/transform_component_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_TRANSFORM_COMPONENT_BASE_HPP_ #include "rive/core/field_types/core_double_type.hpp" #include "rive/world_transform_component.hpp" -namespace rive -{ - class TransformComponentBase : public WorldTransformComponent - { +namespace rive { + class TransformComponentBase : public WorldTransformComponent { protected: typedef WorldTransformComponent Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case TransformComponentBase::typeKey: case WorldTransformComponentBase::typeKey: case ContainerComponentBase::typeKey: @@ -41,10 +37,8 @@ public: inline float rotation() const { return m_Rotation; } - void rotation(float value) - { - if (m_Rotation == value) - { + void rotation(float value) { + if (m_Rotation == value) { return; } m_Rotation = value; @@ -52,10 +46,8 @@ } inline float scaleX() const { return m_ScaleX; } - void scaleX(float value) - { - if (m_ScaleX == value) - { + void scaleX(float value) { + if (m_ScaleX == value) { return; } m_ScaleX = value; @@ -63,28 +55,23 @@ } inline float scaleY() const { return m_ScaleY; } - void scaleY(float value) - { - if (m_ScaleY == value) - { + void scaleY(float value) { + if (m_ScaleY == value) { return; } m_ScaleY = value; scaleYChanged(); } - void copy(const TransformComponentBase& object) - { + void copy(const TransformComponentBase& object) { m_Rotation = object.m_Rotation; m_ScaleX = object.m_ScaleX; m_ScaleY = object.m_ScaleY; WorldTransformComponent::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case rotationPropertyKey: m_Rotation = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/generated/world_transform_component_base.hpp b/include/rive/generated/world_transform_component_base.hpp index a7d0b08..9ec5e40 100644 --- a/include/rive/generated/world_transform_component_base.hpp +++ b/include/rive/generated/world_transform_component_base.hpp
@@ -2,10 +2,8 @@ #define _RIVE_WORLD_TRANSFORM_COMPONENT_BASE_HPP_ #include "rive/container_component.hpp" #include "rive/core/field_types/core_double_type.hpp" -namespace rive -{ - class WorldTransformComponentBase : public ContainerComponent - { +namespace rive { + class WorldTransformComponentBase : public ContainerComponent { protected: typedef ContainerComponent Super; @@ -14,10 +12,8 @@ /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. - bool isTypeOf(uint16_t typeKey) const override - { - switch (typeKey) - { + bool isTypeOf(uint16_t typeKey) const override { + switch (typeKey) { case WorldTransformComponentBase::typeKey: case ContainerComponentBase::typeKey: case ComponentBase::typeKey: @@ -36,26 +32,21 @@ public: inline float opacity() const { return m_Opacity; } - void opacity(float value) - { - if (m_Opacity == value) - { + void opacity(float value) { + if (m_Opacity == value) { return; } m_Opacity = value; opacityChanged(); } - void copy(const WorldTransformComponentBase& object) - { + void copy(const WorldTransformComponentBase& object) { m_Opacity = object.m_Opacity; ContainerComponent::copy(object); } - bool deserialize(uint16_t propertyKey, BinaryReader& reader) override - { - switch (propertyKey) - { + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override { + switch (propertyKey) { case opacityPropertyKey: m_Opacity = CoreDoubleType::deserialize(reader); return true;
diff --git a/include/rive/importers/artboard_importer.hpp b/include/rive/importers/artboard_importer.hpp index 371d249..a806515 100644 --- a/include/rive/importers/artboard_importer.hpp +++ b/include/rive/importers/artboard_importer.hpp
@@ -3,14 +3,12 @@ #include "rive/importers/import_stack.hpp" -namespace rive -{ +namespace rive { class Core; class Artboard; class LinearAnimation; class StateMachine; - class ArtboardImporter : public ImportStackObject - { + class ArtboardImporter : public ImportStackObject { private: Artboard* m_Artboard;
diff --git a/include/rive/importers/backboard_importer.hpp b/include/rive/importers/backboard_importer.hpp index 6f86048..0219213 100644 --- a/include/rive/importers/backboard_importer.hpp +++ b/include/rive/importers/backboard_importer.hpp
@@ -5,15 +5,13 @@ #include <unordered_map> #include <vector> -namespace rive -{ +namespace rive { class Artboard; class NestedArtboard; class Backboard; class FileAsset; class FileAssetReferencer; - class BackboardImporter : public ImportStackObject - { + class BackboardImporter : public ImportStackObject { private: Backboard* m_Backboard; std::unordered_map<int, Artboard*> m_ArtboardLookup;
diff --git a/include/rive/importers/file_asset_importer.hpp b/include/rive/importers/file_asset_importer.hpp index 06f4a18..6629ae3 100644 --- a/include/rive/importers/file_asset_importer.hpp +++ b/include/rive/importers/file_asset_importer.hpp
@@ -5,13 +5,11 @@ #include <unordered_map> #include <vector> -namespace rive -{ +namespace rive { class FileAsset; class FileAssetContents; class FileAssetResolver; - class FileAssetImporter : public ImportStackObject - { + class FileAssetImporter : public ImportStackObject { private: bool m_LoadedContents = false; FileAsset* m_FileAsset;
diff --git a/include/rive/importers/import_stack.hpp b/include/rive/importers/import_stack.hpp index 9bc5500..23ba8ad 100644 --- a/include/rive/importers/import_stack.hpp +++ b/include/rive/importers/import_stack.hpp
@@ -6,99 +6,79 @@ #include <vector> #include <algorithm> -namespace rive -{ - class ImportStackObject - { +namespace rive { + class ImportStackObject { public: virtual ~ImportStackObject() {} virtual StatusCode resolve() { return StatusCode::Ok; } virtual bool readNullObject() { return false; } }; - class ImportStack - { + class ImportStack { private: std::unordered_map<uint16_t, ImportStackObject*> m_Latests; std::vector<ImportStackObject*> m_LastAdded; public: - template <typename T = ImportStackObject> T* latest(uint16_t coreType) - { + template <typename T = ImportStackObject> T* latest(uint16_t coreType) { auto itr = m_Latests.find(coreType); - if (itr == m_Latests.end()) - { + if (itr == m_Latests.end()) { return nullptr; } return reinterpret_cast<T*>(itr->second); } - StatusCode makeLatest(uint16_t coreType, ImportStackObject* object) - { + StatusCode makeLatest(uint16_t coreType, ImportStackObject* object) { // Clean up the old object in the stack. auto itr = m_Latests.find(coreType); - if (itr != m_Latests.end()) - { + if (itr != m_Latests.end()) { auto stackObject = itr->second; // Remove it from latests. auto itr = std::find( m_LastAdded.begin(), m_LastAdded.end(), stackObject); - if (itr != m_LastAdded.end()) - { + if (itr != m_LastAdded.end()) { m_LastAdded.erase(itr); } StatusCode code = stackObject->resolve(); delete stackObject; - if (code != StatusCode::Ok) - { + if (code != StatusCode::Ok) { m_Latests.erase(coreType); return code; } } // Set the new one. - if (object == nullptr) - { + if (object == nullptr) { m_Latests.erase(coreType); - } - else - { + } else { m_Latests[coreType] = object; m_LastAdded.push_back(object); } return StatusCode::Ok; } - StatusCode resolve() - { - for (auto& pair : m_Latests) - { + StatusCode resolve() { + for (auto& pair : m_Latests) { StatusCode code = pair.second->resolve(); - if (code != StatusCode::Ok) - { + if (code != StatusCode::Ok) { return code; } } return StatusCode::Ok; } - ~ImportStack() - { - for (auto& pair : m_Latests) - { + ~ImportStack() { + for (auto& pair : m_Latests) { delete pair.second; } } - bool readNullObject() - { + bool readNullObject() { for (auto itr = m_LastAdded.rbegin(); itr != m_LastAdded.rend(); - itr++) - { - if ((*itr)->readNullObject()) - { + itr++) { + if ((*itr)->readNullObject()) { return true; } }
diff --git a/include/rive/importers/keyed_object_importer.hpp b/include/rive/importers/keyed_object_importer.hpp index 77a1b41..945d4d2 100644 --- a/include/rive/importers/keyed_object_importer.hpp +++ b/include/rive/importers/keyed_object_importer.hpp
@@ -3,13 +3,11 @@ #include "rive/importers/import_stack.hpp" -namespace rive -{ +namespace rive { class Core; class KeyedObject; class KeyedProperty; - class KeyedObjectImporter : public ImportStackObject - { + class KeyedObjectImporter : public ImportStackObject { private: KeyedObject* m_KeyedObject;
diff --git a/include/rive/importers/keyed_property_importer.hpp b/include/rive/importers/keyed_property_importer.hpp index 6a4e941..47bd92c 100644 --- a/include/rive/importers/keyed_property_importer.hpp +++ b/include/rive/importers/keyed_property_importer.hpp
@@ -3,14 +3,12 @@ #include "rive/importers/import_stack.hpp" -namespace rive -{ +namespace rive { class Core; class KeyFrame; class KeyedProperty; class LinearAnimation; - class KeyedPropertyImporter : public ImportStackObject - { + class KeyedPropertyImporter : public ImportStackObject { private: LinearAnimation* m_Animation; KeyedProperty* m_KeyedProperty;
diff --git a/include/rive/importers/layer_state_importer.hpp b/include/rive/importers/layer_state_importer.hpp index 3c6344f..be430e9 100644 --- a/include/rive/importers/layer_state_importer.hpp +++ b/include/rive/importers/layer_state_importer.hpp
@@ -3,14 +3,12 @@ #include "rive/importers/import_stack.hpp" -namespace rive -{ +namespace rive { class LayerState; class StateTransition; class BlendAnimation; - class LayerStateImporter : public ImportStackObject - { + class LayerStateImporter : public ImportStackObject { private: LayerState* m_State;
diff --git a/include/rive/importers/linear_animation_importer.hpp b/include/rive/importers/linear_animation_importer.hpp index 31044a7..3f3466d 100644 --- a/include/rive/importers/linear_animation_importer.hpp +++ b/include/rive/importers/linear_animation_importer.hpp
@@ -3,13 +3,11 @@ #include "rive/importers/import_stack.hpp" -namespace rive -{ +namespace rive { class Core; class LinearAnimation; class KeyedObject; - class LinearAnimationImporter : public ImportStackObject - { + class LinearAnimationImporter : public ImportStackObject { private: LinearAnimation* m_Animation;
diff --git a/include/rive/importers/state_machine_importer.hpp b/include/rive/importers/state_machine_importer.hpp index e069520..963223c 100644 --- a/include/rive/importers/state_machine_importer.hpp +++ b/include/rive/importers/state_machine_importer.hpp
@@ -3,13 +3,11 @@ #include "rive/importers/import_stack.hpp" -namespace rive -{ +namespace rive { class StateMachineInput; class StateMachineLayer; class StateMachine; - class StateMachineImporter : public ImportStackObject - { + class StateMachineImporter : public ImportStackObject { private: StateMachine* m_StateMachine;
diff --git a/include/rive/importers/state_machine_layer_importer.hpp b/include/rive/importers/state_machine_layer_importer.hpp index 69b8d7c..a31e64a 100644 --- a/include/rive/importers/state_machine_layer_importer.hpp +++ b/include/rive/importers/state_machine_layer_importer.hpp
@@ -3,14 +3,12 @@ #include "rive/importers/import_stack.hpp" -namespace rive -{ +namespace rive { class StateMachineLayer; class LayerState; class Artboard; - class StateMachineLayerImporter : public ImportStackObject - { + class StateMachineLayerImporter : public ImportStackObject { private: StateMachineLayer* m_Layer; const Artboard* m_Artboard;
diff --git a/include/rive/importers/state_transition_importer.hpp b/include/rive/importers/state_transition_importer.hpp index e7d29b5..513c764 100644 --- a/include/rive/importers/state_transition_importer.hpp +++ b/include/rive/importers/state_transition_importer.hpp
@@ -3,13 +3,11 @@ #include "rive/importers/import_stack.hpp" -namespace rive -{ +namespace rive { class StateTransition; class TransitionCondition; - class StateTransitionImporter : public ImportStackObject - { + class StateTransitionImporter : public ImportStackObject { private: StateTransition* m_Transition;
diff --git a/include/rive/layout.hpp b/include/rive/layout.hpp index 0fd3492..9eda329 100644 --- a/include/rive/layout.hpp +++ b/include/rive/layout.hpp
@@ -1,9 +1,7 @@ #ifndef _RIVE_LAYOUT_HPP_ #define _RIVE_LAYOUT_HPP_ -namespace rive -{ - enum class Fit : unsigned char - { +namespace rive { + enum class Fit : unsigned char { fill, contain, cover, @@ -13,8 +11,7 @@ scaleDown }; - class Alignment - { + class Alignment { private: float m_X, m_Y;
diff --git a/include/rive/math/aabb.hpp b/include/rive/math/aabb.hpp index 0b84282..f292330 100644 --- a/include/rive/math/aabb.hpp +++ b/include/rive/math/aabb.hpp
@@ -5,16 +5,12 @@ #include "rive/math/vec2d.hpp" #include <cstddef> -namespace rive -{ - class AABB - { +namespace rive { + class AABB { public: - union - { + union { float buffer[4]; - struct - { + struct { float minX, minY, maxX, maxY; }; };
diff --git a/include/rive/math/circle_constant.hpp b/include/rive/math/circle_constant.hpp index d75bb74..61250b3 100644 --- a/include/rive/math/circle_constant.hpp +++ b/include/rive/math/circle_constant.hpp
@@ -1,7 +1,6 @@ #ifndef _RIVE_CIRCLE_CONSTANT_HPP_ #define _RIVE_CIRCLE_CONSTANT_HPP_ -namespace rive -{ +namespace rive { constexpr float circleConstant = 0.552284749831; constexpr float icircleConstant = 1.0 - circleConstant; } // namespace rive
diff --git a/include/rive/math/color.hpp b/include/rive/math/color.hpp index 94bf314..408c70e 100644 --- a/include/rive/math/color.hpp +++ b/include/rive/math/color.hpp
@@ -3,10 +3,8 @@ #include <cstddef> -namespace rive -{ - class Color - { +namespace rive { + class Color { private: float m_Buffer[4]; @@ -18,14 +16,10 @@ Color(float r, float g, float b, float a) : m_Buffer{r, g, b, a} {} Color(int r, int g, int b, int a) : - m_Buffer{r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f} - { - } + m_Buffer{r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f} {} Color(int r, int g, int b) : - m_Buffer{r / 255.0f, g / 255.0f, b / 255.0f, 1.0f} - { - } + m_Buffer{r / 255.0f, g / 255.0f, b / 255.0f, 1.0f} {} Color(float rgba) : m_Buffer{rgba, rgba, rgba, rgba} {} @@ -33,42 +27,34 @@ float& operator[](std::size_t idx) { return m_Buffer[idx]; } const float& operator[](std::size_t idx) const { return m_Buffer[idx]; } - bool operator==(const Color& b) const - { + bool operator==(const Color& b) const { return m_Buffer[0] == b[0] && m_Buffer[1] == b[1] && m_Buffer[2] == b[2] && m_Buffer[3] == b[3]; } - void set(float r, float g, float b, float a) - { + void set(float r, float g, float b, float a) { m_Buffer[0] = r; m_Buffer[1] = g; m_Buffer[2] = b; m_Buffer[3] = a; } - void lerp(const Color& second, float amount) - { + void lerp(const Color& second, float amount) { float iamount = 1.0f - amount; - for (int i = 0; i < 4; i++) - { + for (int i = 0; i < 4; i++) { m_Buffer[i] = second.m_Buffer[i] * amount + m_Buffer[i] * iamount; } } - void multiply(const Color& second) - { - for (int i = 0; i < 4; i++) - { + void multiply(const Color& second) { + for (int i = 0; i < 4; i++) { m_Buffer[i] *= second.m_Buffer[i]; } } - void copy(const Color& second) - { - for (int i = 0; i < 4; i++) - { + void copy(const Color& second) { + for (int i = 0; i < 4; i++) { m_Buffer[i] = second.m_Buffer[i]; } }
diff --git a/include/rive/math/mat2d.hpp b/include/rive/math/mat2d.hpp index 1e1813a..051c5f0 100644 --- a/include/rive/math/mat2d.hpp +++ b/include/rive/math/mat2d.hpp
@@ -3,12 +3,10 @@ #include <cstddef> -namespace rive -{ +namespace rive { class Vec2D; class TransformComponents; - class Mat2D - { + class Mat2D { private: float m_Buffer[6]; @@ -22,8 +20,7 @@ float& operator[](std::size_t idx) { return m_Buffer[idx]; } const float& operator[](std::size_t idx) const { return m_Buffer[idx]; } - static void identity(Mat2D& result) - { + static void identity(Mat2D& result) { result[0] = 1.0f; result[1] = 0.0f; result[2] = 0.0f; @@ -57,15 +54,13 @@ void ty(float value) { m_Buffer[5] = value; } }; - inline Mat2D operator*(const Mat2D& a, const Mat2D& b) - { + inline Mat2D operator*(const Mat2D& a, const Mat2D& b) { Mat2D result; Mat2D::multiply(result, a, b); return result; } - inline bool operator==(const Mat2D& a, const Mat2D& b) - { + inline bool operator==(const Mat2D& a, const Mat2D& b) { return a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3] && a[4] == b[4] && a[5] == b[5]; }
diff --git a/include/rive/math/transform_components.hpp b/include/rive/math/transform_components.hpp index 56f8227..078d9f1 100644 --- a/include/rive/math/transform_components.hpp +++ b/include/rive/math/transform_components.hpp
@@ -4,10 +4,8 @@ #include "rive/math/vec2d.hpp" #include <cstddef> -namespace rive -{ - class TransformComponents - { +namespace rive { + class TransformComponents { private: float m_X; float m_Y; @@ -23,18 +21,14 @@ m_ScaleX(1.0f), m_ScaleY(1.0f), m_Rotation(0.0f), - m_Skew(0.0f) - { - } + m_Skew(0.0f) {} TransformComponents(const TransformComponents& copy) : m_X(copy.m_X), m_Y(copy.m_Y), m_ScaleX(copy.m_ScaleX), m_ScaleY(copy.m_ScaleY), m_Rotation(copy.m_Rotation), - m_Skew(copy.m_Skew) - { - } + m_Skew(copy.m_Skew) {} float x() const { return m_X; } void x(float value) { m_X = value; } @@ -49,20 +43,17 @@ float skew() const { return m_Skew; } void skew(float value) { m_Skew = value; } - void translation(Vec2D& result) const - { + void translation(Vec2D& result) const { result[0] = m_X; result[1] = m_Y; } - void scale(Vec2D& result) const - { + void scale(Vec2D& result) const { result[0] = m_ScaleX; result[1] = m_ScaleY; } static void copy(TransformComponents& result, - const TransformComponents& a) - { + const TransformComponents& a) { result.m_X = a.m_X; result.m_Y = a.m_Y; result.m_ScaleX = a.m_ScaleX;
diff --git a/include/rive/math/vec2d.hpp b/include/rive/math/vec2d.hpp index 60a5524..f90f465 100644 --- a/include/rive/math/vec2d.hpp +++ b/include/rive/math/vec2d.hpp
@@ -3,11 +3,9 @@ #include <cstddef> -namespace rive -{ +namespace rive { class Mat2D; - class Vec2D - { + class Vec2D { private: float m_Buffer[2]; @@ -39,33 +37,28 @@ static void negate(Vec2D& o, const Vec2D& a); }; - inline Vec2D operator*(const Mat2D& a, const Vec2D& b) - { + inline Vec2D operator*(const Mat2D& a, const Vec2D& b) { Vec2D result; Vec2D::transform(result, b, a); return result; } - inline Vec2D operator-(const Vec2D& a, const Vec2D& b) - { + inline Vec2D operator-(const Vec2D& a, const Vec2D& b) { Vec2D result; Vec2D::subtract(result, a, b); return result; } - inline Vec2D operator+(const Vec2D& a, const Vec2D& b) - { + inline Vec2D operator+(const Vec2D& a, const Vec2D& b) { Vec2D result; Vec2D::add(result, a, b); return result; } - inline bool operator==(const Vec2D& a, const Vec2D& b) - { + inline bool operator==(const Vec2D& a, const Vec2D& b) { return a[0] == b[0] && a[1] == b[1]; } - inline bool operator!=(const Vec2D& a, const Vec2D& b) - { + inline bool operator!=(const Vec2D& a, const Vec2D& b) { return a[0] != b[0] || a[1] != b[1]; } } // namespace rive
diff --git a/include/rive/nested_animation.hpp b/include/rive/nested_animation.hpp index 3c7277c..123ac76 100644 --- a/include/rive/nested_animation.hpp +++ b/include/rive/nested_animation.hpp
@@ -2,10 +2,8 @@ #define _RIVE_NESTED_ANIMATION_HPP_ #include "rive/generated/nested_animation_base.hpp" #include <stdio.h> -namespace rive -{ - class NestedAnimation : public NestedAnimationBase - { +namespace rive { + class NestedAnimation : public NestedAnimationBase { public: StatusCode onAddedDirty(CoreContext* context) override;
diff --git a/include/rive/nested_artboard.hpp b/include/rive/nested_artboard.hpp index 83e1826..b7deee4 100644 --- a/include/rive/nested_artboard.hpp +++ b/include/rive/nested_artboard.hpp
@@ -2,11 +2,9 @@ #define _RIVE_NESTED_ARTBOARD_HPP_ #include "rive/generated/nested_artboard_base.hpp" #include <stdio.h> -namespace rive -{ +namespace rive { class NestedAnimation; - class NestedArtboard : public NestedArtboardBase - { + class NestedArtboard : public NestedArtboardBase { private: Artboard* m_NestedInstance = nullptr;
diff --git a/include/rive/node.hpp b/include/rive/node.hpp index b28862b..160c4f1 100644 --- a/include/rive/node.hpp +++ b/include/rive/node.hpp
@@ -2,11 +2,9 @@ #define _RIVE_NODE_HPP_ #include "rive/generated/node_base.hpp" -namespace rive -{ +namespace rive { /// A Rive Node - class Node : public NodeBase - { + class Node : public NodeBase { protected: void xChanged() override; void yChanged() override;
diff --git a/include/rive/relative_local_asset_resolver.hpp b/include/rive/relative_local_asset_resolver.hpp index 94af8b3..a3d1db9 100644 --- a/include/rive/relative_local_asset_resolver.hpp +++ b/include/rive/relative_local_asset_resolver.hpp
@@ -6,29 +6,24 @@ #include <cstdio> #include <string> -namespace rive -{ +namespace rive { class FileAsset; /// An implementation of FileAssetResolver which finds the assets in a local /// path relative to the original .riv file looking for them. - class RelativeLocalAssetResolver : public FileAssetResolver - { + class RelativeLocalAssetResolver : public FileAssetResolver { private: std::string m_Path; public: - RelativeLocalAssetResolver(std::string filename) - { + RelativeLocalAssetResolver(std::string filename) { std::size_t finalSlash = filename.rfind('/'); - if (finalSlash != std::string::npos) - { + if (finalSlash != std::string::npos) { m_Path = filename.substr(0, finalSlash + 1); } } - void loadContents(FileAsset& asset) override - { + void loadContents(FileAsset& asset) override { std::string filename = m_Path + asset.uniqueFilename(); FILE* fp = fopen(filename.c_str(), "r"); @@ -36,8 +31,7 @@ auto length = ftell(fp); fseek(fp, 0, SEEK_SET); uint8_t* bytes = new uint8_t[length]; - if (fread(bytes, 1, length, fp) == length) - { + if (fread(bytes, 1, length, fp) == length) { asset.decode(bytes, length); } delete[] bytes;
diff --git a/include/rive/renderer.hpp b/include/rive/renderer.hpp index db35ebb..edced89 100644 --- a/include/rive/renderer.hpp +++ b/include/rive/renderer.hpp
@@ -13,18 +13,12 @@ #include <stdio.h> #include <cstdint> -namespace rive -{ +namespace rive { class Vec2D; - enum class RenderPaintStyle - { - stroke, - fill - }; + enum class RenderPaintStyle { stroke, fill }; - class RenderPaint - { + class RenderPaint { public: virtual void style(RenderPaintStyle style) = 0; virtual void color(ColorInt value) = 0; @@ -40,8 +34,7 @@ virtual ~RenderPaint() {} }; - class RenderImage - { + class RenderImage { protected: int m_Width = 0; int m_Height = 0; @@ -53,12 +46,10 @@ int height() const { return m_Height; } }; - class RenderPath : public CommandPath - { + class RenderPath : public CommandPath { public: RenderPath* renderPath() override { return this; } - void addPath(CommandPath* path, const Mat2D& transform) override - { + void addPath(CommandPath* path, const Mat2D& transform) override { addRenderPath(path->renderPath(), transform); } @@ -66,8 +57,7 @@ const Mat2D& transform) = 0; }; - class Renderer - { + class Renderer { public: virtual ~Renderer() {} virtual void save() = 0; @@ -82,8 +72,7 @@ Fit fit, const Alignment& alignment, const AABB& frame, - const AABB& content) - { + const AABB& content) { float contentWidth = content[2] - content[0]; float contentHeight = content[3] - content[1]; float x = -content[0] - contentWidth / 2.0 - @@ -93,47 +82,39 @@ float scaleX = 1.0, scaleY = 1.0; - switch (fit) - { - case Fit::fill: - { + switch (fit) { + case Fit::fill: { scaleX = frame.width() / contentWidth; scaleY = frame.height() / contentHeight; break; } - case Fit::contain: - { + case Fit::contain: { float minScale = std::fmin(frame.width() / contentWidth, frame.height() / contentHeight); scaleX = scaleY = minScale; break; } - case Fit::cover: - { + case Fit::cover: { float maxScale = std::fmax(frame.width() / contentWidth, frame.height() / contentHeight); scaleX = scaleY = maxScale; break; } - case Fit::fitHeight: - { + case Fit::fitHeight: { float minScale = frame.height() / contentHeight; scaleX = scaleY = minScale; break; } - case Fit::fitWidth: - { + case Fit::fitWidth: { float minScale = frame.width() / contentWidth; scaleX = scaleY = minScale; break; } - case Fit::none: - { + case Fit::none: { scaleX = scaleY = 1.0; break; } - case Fit::scaleDown: - { + case Fit::scaleDown: { float minScale = std::fmin(frame.width() / contentWidth, frame.height() / contentHeight); scaleX = scaleY = minScale < 1.0 ? minScale : 1.0; @@ -161,8 +142,7 @@ void align(Fit fit, const Alignment& alignment, const AABB& frame, - const AABB& content) - { + const AABB& content) { Mat2D result; computeAlignment(result, fit, alignment, frame, content); transform(result);
diff --git a/include/rive/runtime_header.hpp b/include/rive/runtime_header.hpp index 5ba8bd0..bdfb755 100644 --- a/include/rive/runtime_header.hpp +++ b/include/rive/runtime_header.hpp
@@ -4,15 +4,13 @@ #include "rive/core/binary_reader.hpp" #include <unordered_map> -namespace rive -{ +namespace rive { /// Rive file runtime header. The header is fonud at the beginning of every /// Rive runtime file, and begins with a specific 4-byte format: "RIVE". /// This is followed by the major and minor version of Rive used to create /// the file. Finally the owner and file ids are at the end of header; these /// unsigned integers may be zero. - class RuntimeHeader - { + class RuntimeHeader { private: static constexpr char fingerprint[] = "RIVE"; @@ -29,11 +27,9 @@ /// @returns the file's id; may be zero int fileId() const { return m_FileId; } - int propertyFieldId(int propertyKey) const - { + int propertyFieldId(int propertyKey) const { auto itr = m_PropertyToFieldIndex.find(propertyKey); - if (itr == m_PropertyToFieldIndex.end()) - { + if (itr == m_PropertyToFieldIndex.end()) { return -1; } @@ -44,32 +40,26 @@ /// @param reader the binary reader attached to the buffer /// @param header a pointer to the header where the data will be stored. /// @returns true if the header is successfully read - static bool read(BinaryReader& reader, RuntimeHeader& header) - { - for (int i = 0; i < 4; i++) - { + static bool read(BinaryReader& reader, RuntimeHeader& header) { + for (int i = 0; i < 4; i++) { auto b = reader.readByte(); - if (fingerprint[i] != b) - { + if (fingerprint[i] != b) { return false; } } header.m_MajorVersion = (int)reader.readVarUint64(); - if (reader.didOverflow()) - { + if (reader.didOverflow()) { return false; } header.m_MinorVersion = (int)reader.readVarUint64(); - if (reader.didOverflow()) - { + if (reader.didOverflow()) { return false; } header.m_FileId = (int)reader.readVarUint64(); - if (reader.didOverflow()) - { + if (reader.didOverflow()) { return false; } @@ -79,26 +69,22 @@ propertyKey = (int)reader.readVarUint64()) { propertyKeys.push_back(propertyKey); - if (reader.didOverflow()) - { + if (reader.didOverflow()) { return false; } } int currentInt = 0; int currentBit = 8; - for (auto propertyKey : propertyKeys) - { - if (currentBit == 8) - { + for (auto propertyKey : propertyKeys) { + if (currentBit == 8) { currentInt = reader.readUint32(); currentBit = 0; } int fieldIndex = (currentInt >> currentBit) & 3; header.m_PropertyToFieldIndex[propertyKey] = fieldIndex; currentBit += 2; - if (reader.didOverflow()) - { + if (reader.didOverflow()) { return false; } }
diff --git a/include/rive/shapes/clipping_shape.hpp b/include/rive/shapes/clipping_shape.hpp index 4305e2b..4d01176 100644 --- a/include/rive/shapes/clipping_shape.hpp +++ b/include/rive/shapes/clipping_shape.hpp
@@ -4,13 +4,11 @@ #include <stdio.h> #include <vector> -namespace rive -{ +namespace rive { class Shape; class Node; class RenderPath; - class ClippingShape : public ClippingShapeBase - { + class ClippingShape : public ClippingShapeBase { private: std::vector<Shape*> m_Shapes; Node* m_Source = nullptr;
diff --git a/include/rive/shapes/cubic_asymmetric_vertex.hpp b/include/rive/shapes/cubic_asymmetric_vertex.hpp index 1437dc2..6e10349 100644 --- a/include/rive/shapes/cubic_asymmetric_vertex.hpp +++ b/include/rive/shapes/cubic_asymmetric_vertex.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_CUBIC_ASYMMETRIC_VERTEX_HPP_ #define _RIVE_CUBIC_ASYMMETRIC_VERTEX_HPP_ #include "rive/generated/shapes/cubic_asymmetric_vertex_base.hpp" -namespace rive -{ - class CubicAsymmetricVertex : public CubicAsymmetricVertexBase - { +namespace rive { + class CubicAsymmetricVertex : public CubicAsymmetricVertexBase { protected: void computeIn() override; void computeOut() override;
diff --git a/include/rive/shapes/cubic_detached_vertex.hpp b/include/rive/shapes/cubic_detached_vertex.hpp index cb73ad0..a0fb961 100644 --- a/include/rive/shapes/cubic_detached_vertex.hpp +++ b/include/rive/shapes/cubic_detached_vertex.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_CUBIC_DETACHED_VERTEX_HPP_ #define _RIVE_CUBIC_DETACHED_VERTEX_HPP_ #include "rive/generated/shapes/cubic_detached_vertex_base.hpp" -namespace rive -{ - class CubicDetachedVertex : public CubicDetachedVertexBase - { +namespace rive { + class CubicDetachedVertex : public CubicDetachedVertexBase { protected: void computeIn() override; void computeOut() override;
diff --git a/include/rive/shapes/cubic_mirrored_vertex.hpp b/include/rive/shapes/cubic_mirrored_vertex.hpp index 1abe4f5..dcbaf99 100644 --- a/include/rive/shapes/cubic_mirrored_vertex.hpp +++ b/include/rive/shapes/cubic_mirrored_vertex.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_CUBIC_MIRRORED_VERTEX_HPP_ #define _RIVE_CUBIC_MIRRORED_VERTEX_HPP_ #include "rive/generated/shapes/cubic_mirrored_vertex_base.hpp" -namespace rive -{ - class CubicMirroredVertex : public CubicMirroredVertexBase - { +namespace rive { + class CubicMirroredVertex : public CubicMirroredVertexBase { protected: void computeIn() override; void computeOut() override;
diff --git a/include/rive/shapes/cubic_vertex.hpp b/include/rive/shapes/cubic_vertex.hpp index d7bc44e..717f7ea 100644 --- a/include/rive/shapes/cubic_vertex.hpp +++ b/include/rive/shapes/cubic_vertex.hpp
@@ -3,11 +3,9 @@ #include "rive/generated/shapes/cubic_vertex_base.hpp" #include "rive/math/vec2d.hpp" -namespace rive -{ +namespace rive { class Vec2D; - class CubicVertex : public CubicVertexBase - { + class CubicVertex : public CubicVertexBase { protected: bool m_InValid = false; bool m_OutValid = false;
diff --git a/include/rive/shapes/ellipse.hpp b/include/rive/shapes/ellipse.hpp index 5547f80..a9ff0bd 100644 --- a/include/rive/shapes/ellipse.hpp +++ b/include/rive/shapes/ellipse.hpp
@@ -3,10 +3,8 @@ #include "rive/generated/shapes/ellipse_base.hpp" #include "rive/shapes/cubic_detached_vertex.hpp" -namespace rive -{ - class Ellipse : public EllipseBase - { +namespace rive { + class Ellipse : public EllipseBase { CubicDetachedVertex m_Vertex1, m_Vertex2, m_Vertex3, m_Vertex4; public:
diff --git a/include/rive/shapes/image.hpp b/include/rive/shapes/image.hpp index fad53f2..84dab09 100644 --- a/include/rive/shapes/image.hpp +++ b/include/rive/shapes/image.hpp
@@ -2,11 +2,9 @@ #define _RIVE_IMAGE_HPP_ #include "rive/generated/shapes/image_base.hpp" #include "rive/assets/file_asset_referencer.hpp" -namespace rive -{ +namespace rive { class ImageAsset; - class Image : public ImageBase, public FileAssetReferencer - { + class Image : public ImageBase, public FileAssetReferencer { private: ImageAsset* m_ImageAsset = nullptr;
diff --git a/include/rive/shapes/metrics_path.hpp b/include/rive/shapes/metrics_path.hpp index d2dd8d7..a6c696c 100644 --- a/include/rive/shapes/metrics_path.hpp +++ b/include/rive/shapes/metrics_path.hpp
@@ -6,21 +6,16 @@ #include <cassert> #include <vector> -namespace rive -{ +namespace rive { - struct CubicSegment - { + struct CubicSegment { float t; float length; CubicSegment(float tValue, float lengthValue) : - t(tValue), length(lengthValue) - { - } + t(tValue), length(lengthValue) {} }; - struct PathPart - { + struct PathPart { static const unsigned char line = 0; /// Type is 0 when this is a line segment, it's 1 or greater when it's a /// cubic. When it's a cubic it also represents the index in @@ -36,13 +31,10 @@ unsigned char numSegments; PathPart(unsigned char t, unsigned char l) : - type(t), offset(l), numSegments(0) - { - } + type(t), offset(l), numSegments(0) {} }; - class MetricsPath : public CommandPath - { + class MetricsPath : public CommandPath { private: std::vector<Vec2D> m_Points; std::vector<Vec2D> m_TransformedPoints; @@ -85,21 +77,18 @@ RenderPath* result); }; - class OnlyMetricsPath : public MetricsPath - { + class OnlyMetricsPath : public MetricsPath { public: void fillRule(FillRule value) override {} - RenderPath* renderPath() override - { + RenderPath* renderPath() override { // Should never be used for actual rendering. assert(false); return nullptr; } }; - class RenderMetricsPath : public MetricsPath - { + class RenderMetricsPath : public MetricsPath { private: RenderPath* m_RenderPath;
diff --git a/include/rive/shapes/paint/blend_mode.hpp b/include/rive/shapes/paint/blend_mode.hpp index 0fea262..43939c9 100644 --- a/include/rive/shapes/paint/blend_mode.hpp +++ b/include/rive/shapes/paint/blend_mode.hpp
@@ -1,9 +1,7 @@ #ifndef _RIVE_BLEND_MODE_HPP_ #define _RIVE_BLEND_MODE_HPP_ -namespace rive -{ - enum class BlendMode : unsigned int - { +namespace rive { + enum class BlendMode : unsigned int { srcOver = 3, screen = 14, overlay = 15,
diff --git a/include/rive/shapes/paint/color.hpp b/include/rive/shapes/paint/color.hpp index 740c7ba..8603938 100644 --- a/include/rive/shapes/paint/color.hpp +++ b/include/rive/shapes/paint/color.hpp
@@ -3,8 +3,7 @@ #include <cmath> #include <cstdint> -namespace rive -{ +namespace rive { using ColorInt = uint32_t; ColorInt colorARGB(int a, int r, int g, int b);
diff --git a/include/rive/shapes/paint/fill.hpp b/include/rive/shapes/paint/fill.hpp index 4c9e665..a62adcf 100644 --- a/include/rive/shapes/paint/fill.hpp +++ b/include/rive/shapes/paint/fill.hpp
@@ -2,10 +2,8 @@ #define _RIVE_FILL_HPP_ #include "rive/generated/shapes/paint/fill_base.hpp" #include "rive/shapes/path_space.hpp" -namespace rive -{ - class Fill : public FillBase - { +namespace rive { + class Fill : public FillBase { public: RenderPaint* initRenderPaint(ShapePaintMutator* mutator) override; PathSpace pathSpace() const override;
diff --git a/include/rive/shapes/paint/gradient_stop.hpp b/include/rive/shapes/paint/gradient_stop.hpp index fd4fffd..c7e657b 100644 --- a/include/rive/shapes/paint/gradient_stop.hpp +++ b/include/rive/shapes/paint/gradient_stop.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_GRADIENT_STOP_HPP_ #define _RIVE_GRADIENT_STOP_HPP_ #include "rive/generated/shapes/paint/gradient_stop_base.hpp" -namespace rive -{ - class GradientStop : public GradientStopBase - { +namespace rive { + class GradientStop : public GradientStopBase { public: StatusCode onAddedDirty(CoreContext* context) override;
diff --git a/include/rive/shapes/paint/linear_gradient.hpp b/include/rive/shapes/paint/linear_gradient.hpp index 8b3566b..aa1e452 100644 --- a/include/rive/shapes/paint/linear_gradient.hpp +++ b/include/rive/shapes/paint/linear_gradient.hpp
@@ -4,13 +4,11 @@ #include "rive/math/vec2d.hpp" #include "rive/shapes/paint/shape_paint_mutator.hpp" #include <vector> -namespace rive -{ +namespace rive { class Node; class GradientStop; - class LinearGradient : public LinearGradientBase, public ShapePaintMutator - { + class LinearGradient : public LinearGradientBase, public ShapePaintMutator { private: std::vector<GradientStop*> m_Stops; Node* m_ShapePaintContainer = nullptr;
diff --git a/include/rive/shapes/paint/radial_gradient.hpp b/include/rive/shapes/paint/radial_gradient.hpp index af87546..50c296a 100644 --- a/include/rive/shapes/paint/radial_gradient.hpp +++ b/include/rive/shapes/paint/radial_gradient.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_RADIAL_GRADIENT_HPP_ #define _RIVE_RADIAL_GRADIENT_HPP_ #include "rive/generated/shapes/paint/radial_gradient_base.hpp" -namespace rive -{ - class RadialGradient : public RadialGradientBase - { +namespace rive { + class RadialGradient : public RadialGradientBase { public: void makeGradient(const Vec2D& start, const Vec2D& end) override; };
diff --git a/include/rive/shapes/paint/shape_paint.hpp b/include/rive/shapes/paint/shape_paint.hpp index ad61ea2..89ed2de 100644 --- a/include/rive/shapes/paint/shape_paint.hpp +++ b/include/rive/shapes/paint/shape_paint.hpp
@@ -5,12 +5,10 @@ #include "rive/shapes/paint/blend_mode.hpp" #include "rive/shapes/paint/shape_paint_mutator.hpp" #include "rive/shapes/path_space.hpp" -namespace rive -{ +namespace rive { class RenderPaint; class ShapePaintMutator; - class ShapePaint : public ShapePaintBase - { + class ShapePaint : public ShapePaintBase { protected: RenderPaint* m_RenderPaint = nullptr; ShapePaintMutator* m_PaintMutator = nullptr; @@ -20,8 +18,7 @@ StatusCode onAddedClean(CoreContext* context) override; float renderOpacity() const { return m_PaintMutator->renderOpacity(); } - void renderOpacity(float value) - { + void renderOpacity(float value) { m_PaintMutator->renderOpacity(value); } @@ -40,10 +37,8 @@ /// ShapePaint. It'll be one of SolidColor, LinearGradient, or /// RadialGradient. Component* paint() const { return m_PaintMutator->component(); } - - bool isTranslucent() const { - return m_PaintMutator->isTranslucent(); - } + + bool isTranslucent() const { return m_PaintMutator->isTranslucent(); } }; } // namespace rive
diff --git a/include/rive/shapes/paint/shape_paint_mutator.hpp b/include/rive/shapes/paint/shape_paint_mutator.hpp index 1d24555..e985db7 100644 --- a/include/rive/shapes/paint/shape_paint_mutator.hpp +++ b/include/rive/shapes/paint/shape_paint_mutator.hpp
@@ -1,12 +1,10 @@ #ifndef _RIVE_SHAPE_PAINT_MUTATOR_HPP_ #define _RIVE_SHAPE_PAINT_MUTATOR_HPP_ -namespace rive -{ +namespace rive { class Component; class RenderPaint; - class ShapePaintMutator - { + class ShapePaintMutator { private: float m_RenderOpacity = 1.0f; RenderPaint* m_RenderPaint = nullptr; @@ -28,7 +26,7 @@ void renderOpacity(float value); Component* component() const { return m_Component; } - + bool isTranslucent() const { return m_RenderOpacity < 1 || this->internalIsTranslucent(); }
diff --git a/include/rive/shapes/paint/solid_color.hpp b/include/rive/shapes/paint/solid_color.hpp index f882de1..3a862e6 100644 --- a/include/rive/shapes/paint/solid_color.hpp +++ b/include/rive/shapes/paint/solid_color.hpp
@@ -2,10 +2,8 @@ #define _RIVE_SOLID_COLOR_HPP_ #include "rive/generated/shapes/paint/solid_color_base.hpp" #include "rive/shapes/paint/shape_paint_mutator.hpp" -namespace rive -{ - class SolidColor : public SolidColorBase, public ShapePaintMutator - { +namespace rive { + class SolidColor : public SolidColorBase, public ShapePaintMutator { public: StatusCode onAddedDirty(CoreContext* context) override;
diff --git a/include/rive/shapes/paint/stroke.hpp b/include/rive/shapes/paint/stroke.hpp index 804102d..8b7e984 100644 --- a/include/rive/shapes/paint/stroke.hpp +++ b/include/rive/shapes/paint/stroke.hpp
@@ -2,11 +2,9 @@ #define _RIVE_STROKE_HPP_ #include "rive/generated/shapes/paint/stroke_base.hpp" #include "rive/shapes/path_space.hpp" -namespace rive -{ +namespace rive { class StrokeEffect; - class Stroke : public StrokeBase - { + class Stroke : public StrokeBase { private: StrokeEffect* m_Effect = nullptr;
diff --git a/include/rive/shapes/paint/stroke_cap.hpp b/include/rive/shapes/paint/stroke_cap.hpp index 635da82..7dc87e7 100644 --- a/include/rive/shapes/paint/stroke_cap.hpp +++ b/include/rive/shapes/paint/stroke_cap.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_STROKE_CAP_HPP_ #define _RIVE_STROKE_CAP_HPP_ -namespace rive -{ +namespace rive { /// Style used for stroke line endings. - enum class StrokeCap : unsigned int - { + enum class StrokeCap : unsigned int { /// Flat edge at the start/end of the stroke. butt = 0,
diff --git a/include/rive/shapes/paint/stroke_effect.hpp b/include/rive/shapes/paint/stroke_effect.hpp index cb46119..bc40a4c 100644 --- a/include/rive/shapes/paint/stroke_effect.hpp +++ b/include/rive/shapes/paint/stroke_effect.hpp
@@ -1,12 +1,10 @@ #ifndef _RIVE_STROKE_EFFECT_HPP_ #define _RIVE_STROKE_EFFECT_HPP_ -namespace rive -{ +namespace rive { class RenderPath; class MetricsPath; - class StrokeEffect - { + class StrokeEffect { public: virtual RenderPath* effectPath(MetricsPath* source) = 0; virtual void invalidateEffect() = 0;
diff --git a/include/rive/shapes/paint/stroke_join.hpp b/include/rive/shapes/paint/stroke_join.hpp index cafeb13..b8629e2 100644 --- a/include/rive/shapes/paint/stroke_join.hpp +++ b/include/rive/shapes/paint/stroke_join.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_STROKE_JOIN_HPP_ #define _RIVE_STROKE_JOIN_HPP_ -namespace rive -{ +namespace rive { /// Style used for stroke segment joins when there is a sharp change. - enum class StrokeJoin : unsigned int - { + enum class StrokeJoin : unsigned int { /// Makes a sharp corner at the joint. miter = 0,
diff --git a/include/rive/shapes/paint/trim_path.hpp b/include/rive/shapes/paint/trim_path.hpp index 78156a6..9806228 100644 --- a/include/rive/shapes/paint/trim_path.hpp +++ b/include/rive/shapes/paint/trim_path.hpp
@@ -4,10 +4,8 @@ #include "rive/shapes/paint/stroke_effect.hpp" #include <stdio.h> -namespace rive -{ - class TrimPath : public TrimPathBase, public StrokeEffect - { +namespace rive { + class TrimPath : public TrimPathBase, public StrokeEffect { private: RenderPath* m_TrimmedPath; RenderPath* m_RenderPath = nullptr;
diff --git a/include/rive/shapes/parametric_path.hpp b/include/rive/shapes/parametric_path.hpp index 034b51f..a8d3da1 100644 --- a/include/rive/shapes/parametric_path.hpp +++ b/include/rive/shapes/parametric_path.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_PARAMETRIC_PATH_HPP_ #define _RIVE_PARAMETRIC_PATH_HPP_ #include "rive/generated/shapes/parametric_path_base.hpp" -namespace rive -{ - class ParametricPath : public ParametricPathBase - { +namespace rive { + class ParametricPath : public ParametricPathBase { protected: void widthChanged() override; void heightChanged() override;
diff --git a/include/rive/shapes/path.hpp b/include/rive/shapes/path.hpp index 811a11e..a1e20cf 100644 --- a/include/rive/shapes/path.hpp +++ b/include/rive/shapes/path.hpp
@@ -4,8 +4,7 @@ #include "rive/math/mat2d.hpp" #include <vector> -namespace rive -{ +namespace rive { class Shape; class CommandPath; class PathVertex; @@ -19,8 +18,7 @@ /// and cubic vertices. No corner vertices and it's entirely in world space. /// This is helpful for getting a close to identical representation of the /// vertices used to issue the high level path draw commands. - class FlattenedPath - { + class FlattenedPath { private: std::vector<PathVertex*> m_Vertices; @@ -32,8 +30,7 @@ }; #endif - class Path : public PathBase - { + class Path : public PathBase { protected: Shape* m_Shape = nullptr; CommandPath* m_CommandPath = nullptr;
diff --git a/include/rive/shapes/path_composer.hpp b/include/rive/shapes/path_composer.hpp index 3375a37..fb27068 100644 --- a/include/rive/shapes/path_composer.hpp +++ b/include/rive/shapes/path_composer.hpp
@@ -1,13 +1,11 @@ #ifndef _RIVE_PATH_COMPOSER_HPP_ #define _RIVE_PATH_COMPOSER_HPP_ #include "rive/component.hpp" -namespace rive -{ +namespace rive { class Shape; class CommandPath; class RenderPath; - class PathComposer : public Component - { + class PathComposer : public Component { private: Shape* m_Shape; CommandPath* m_LocalPath = nullptr;
diff --git a/include/rive/shapes/path_space.hpp b/include/rive/shapes/path_space.hpp index 80c3cf2..17a6682 100644 --- a/include/rive/shapes/path_space.hpp +++ b/include/rive/shapes/path_space.hpp
@@ -3,10 +3,8 @@ #include <type_traits> -namespace rive -{ - enum class PathSpace : unsigned char - { +namespace rive { + enum class PathSpace : unsigned char { Neither = 0, Local = 1 << 1, World = 1 << 2, @@ -14,35 +12,30 @@ Clipping = 1 << 4 }; - inline constexpr PathSpace operator&(PathSpace lhs, PathSpace rhs) - { + inline constexpr PathSpace operator&(PathSpace lhs, PathSpace rhs) { return static_cast<PathSpace>( static_cast<std::underlying_type<PathSpace>::type>(lhs) & static_cast<std::underlying_type<PathSpace>::type>(rhs)); } - inline constexpr PathSpace operator^(PathSpace lhs, PathSpace rhs) - { + inline constexpr PathSpace operator^(PathSpace lhs, PathSpace rhs) { return static_cast<PathSpace>( static_cast<std::underlying_type<PathSpace>::type>(lhs) ^ static_cast<std::underlying_type<PathSpace>::type>(rhs)); } - inline constexpr PathSpace operator|(PathSpace lhs, PathSpace rhs) - { + inline constexpr PathSpace operator|(PathSpace lhs, PathSpace rhs) { return static_cast<PathSpace>( static_cast<std::underlying_type<PathSpace>::type>(lhs) | static_cast<std::underlying_type<PathSpace>::type>(rhs)); } - inline constexpr PathSpace operator~(PathSpace rhs) - { + inline constexpr PathSpace operator~(PathSpace rhs) { return static_cast<PathSpace>( ~static_cast<std::underlying_type<PathSpace>::type>(rhs)); } - inline PathSpace& operator|=(PathSpace& lhs, PathSpace rhs) - { + inline PathSpace& operator|=(PathSpace& lhs, PathSpace rhs) { lhs = static_cast<PathSpace>( static_cast<std::underlying_type<PathSpace>::type>(lhs) | static_cast<std::underlying_type<PathSpace>::type>(rhs)); @@ -50,8 +43,7 @@ return lhs; } - inline PathSpace& operator&=(PathSpace& lhs, PathSpace rhs) - { + inline PathSpace& operator&=(PathSpace& lhs, PathSpace rhs) { lhs = static_cast<PathSpace>( static_cast<std::underlying_type<PathSpace>::type>(lhs) & static_cast<std::underlying_type<PathSpace>::type>(rhs)); @@ -59,8 +51,7 @@ return lhs; } - inline PathSpace& operator^=(PathSpace& lhs, PathSpace rhs) - { + inline PathSpace& operator^=(PathSpace& lhs, PathSpace rhs) { lhs = static_cast<PathSpace>( static_cast<std::underlying_type<PathSpace>::type>(lhs) ^ static_cast<std::underlying_type<PathSpace>::type>(rhs));
diff --git a/include/rive/shapes/path_vertex.hpp b/include/rive/shapes/path_vertex.hpp index dbe7b47..d2b3054 100644 --- a/include/rive/shapes/path_vertex.hpp +++ b/include/rive/shapes/path_vertex.hpp
@@ -3,10 +3,8 @@ #include "rive/bones/weight.hpp" #include "rive/generated/shapes/path_vertex_base.hpp" #include "rive/math/mat2d.hpp" -namespace rive -{ - class PathVertex : public PathVertexBase - { +namespace rive { + class PathVertex : public PathVertexBase { friend class Weight; private:
diff --git a/include/rive/shapes/points_path.hpp b/include/rive/shapes/points_path.hpp index e6cc803..957c867 100644 --- a/include/rive/shapes/points_path.hpp +++ b/include/rive/shapes/points_path.hpp
@@ -2,10 +2,8 @@ #define _RIVE_POINTS_PATH_HPP_ #include "rive/bones/skinnable.hpp" #include "rive/generated/shapes/points_path_base.hpp" -namespace rive -{ - class PointsPath : public PointsPathBase, public Skinnable - { +namespace rive { + class PointsPath : public PointsPathBase, public Skinnable { public: bool isPathClosed() const override { return isClosed(); } void buildDependencies() override;
diff --git a/include/rive/shapes/polygon.hpp b/include/rive/shapes/polygon.hpp index 117d93c..97012bd 100644 --- a/include/rive/shapes/polygon.hpp +++ b/include/rive/shapes/polygon.hpp
@@ -4,10 +4,8 @@ #include "rive/shapes/path_vertex.hpp" #include "rive/shapes/straight_vertex.hpp" #include <vector> -namespace rive -{ - class Polygon : public PolygonBase - { +namespace rive { + class Polygon : public PolygonBase { protected: std::vector<StraightVertex> m_PolygonVertices;
diff --git a/include/rive/shapes/rectangle.hpp b/include/rive/shapes/rectangle.hpp index 1527b2d..9a47926 100644 --- a/include/rive/shapes/rectangle.hpp +++ b/include/rive/shapes/rectangle.hpp
@@ -3,10 +3,8 @@ #include "rive/generated/shapes/rectangle_base.hpp" #include "rive/shapes/straight_vertex.hpp" -namespace rive -{ - class Rectangle : public RectangleBase - { +namespace rive { + class Rectangle : public RectangleBase { StraightVertex m_Vertex1, m_Vertex2, m_Vertex3, m_Vertex4; public:
diff --git a/include/rive/shapes/shape.hpp b/include/rive/shapes/shape.hpp index 8a455c6..6361a2f 100644 --- a/include/rive/shapes/shape.hpp +++ b/include/rive/shapes/shape.hpp
@@ -5,12 +5,10 @@ #include "rive/shapes/shape_paint_container.hpp" #include <vector> -namespace rive -{ +namespace rive { class Path; class PathComposer; - class Shape : public ShapeBase, public ShapePaintContainer - { + class Shape : public ShapeBase, public ShapePaintContainer { private: PathComposer m_PathComposer; std::vector<Path*> m_Paths; @@ -28,8 +26,7 @@ void update(ComponentDirt value) override; void draw(Renderer* renderer) override; - PathComposer* pathComposer() const - { + PathComposer* pathComposer() const { return (PathComposer*)&m_PathComposer; }
diff --git a/include/rive/shapes/shape_paint_container.hpp b/include/rive/shapes/shape_paint_container.hpp index 366854d..56b3b5f 100644 --- a/include/rive/shapes/shape_paint_container.hpp +++ b/include/rive/shapes/shape_paint_container.hpp
@@ -4,15 +4,13 @@ #include "rive/shapes/path_space.hpp" #include <vector> -namespace rive -{ +namespace rive { class ShapePaint; class Component; class CommandPath; - class ShapePaintContainer - { + class ShapePaintContainer { friend class ShapePaint; protected:
diff --git a/include/rive/shapes/star.hpp b/include/rive/shapes/star.hpp index 490b46e..9d96190 100644 --- a/include/rive/shapes/star.hpp +++ b/include/rive/shapes/star.hpp
@@ -2,10 +2,8 @@ #define _RIVE_STAR_HPP_ #include "rive/generated/shapes/star_base.hpp" #include <stdio.h> -namespace rive -{ - class Star : public StarBase - { +namespace rive { + class Star : public StarBase { public: Star(); void update(ComponentDirt value) override;
diff --git a/include/rive/shapes/straight_vertex.hpp b/include/rive/shapes/straight_vertex.hpp index 5e4700a..1805a74 100644 --- a/include/rive/shapes/straight_vertex.hpp +++ b/include/rive/shapes/straight_vertex.hpp
@@ -1,10 +1,8 @@ #ifndef _RIVE_STRAIGHT_VERTEX_HPP_ #define _RIVE_STRAIGHT_VERTEX_HPP_ #include "rive/generated/shapes/straight_vertex_base.hpp" -namespace rive -{ - class StraightVertex : public StraightVertexBase - { +namespace rive { + class StraightVertex : public StraightVertexBase { protected: void radiusChanged() override; };
diff --git a/include/rive/shapes/triangle.hpp b/include/rive/shapes/triangle.hpp index 37ff151..b5203a6 100644 --- a/include/rive/shapes/triangle.hpp +++ b/include/rive/shapes/triangle.hpp
@@ -3,10 +3,8 @@ #include "rive/generated/shapes/triangle_base.hpp" #include "rive/shapes/straight_vertex.hpp" -namespace rive -{ - class Triangle : public TriangleBase - { +namespace rive { + class Triangle : public TriangleBase { private: StraightVertex m_Vertex1, m_Vertex2, m_Vertex3;
diff --git a/include/rive/status_code.hpp b/include/rive/status_code.hpp index 25b35a4..e1a5e5a 100644 --- a/include/rive/status_code.hpp +++ b/include/rive/status_code.hpp
@@ -1,9 +1,7 @@ #ifndef _RIVE_STATUS_CODE_HPP_ #define _RIVE_STATUS_CODE_HPP_ -namespace rive -{ - enum class StatusCode : unsigned char - { +namespace rive { + enum class StatusCode : unsigned char { Ok, MissingObject, InvalidObject,
diff --git a/include/rive/transform_component.hpp b/include/rive/transform_component.hpp index d965156..3ee689a 100644 --- a/include/rive/transform_component.hpp +++ b/include/rive/transform_component.hpp
@@ -3,12 +3,10 @@ #include "rive/generated/transform_component_base.hpp" #include "rive/math/mat2d.hpp" -namespace rive -{ +namespace rive { class Constraint; class WorldTransformComponent; - class TransformComponent : public TransformComponentBase - { + class TransformComponent : public TransformComponentBase { private: Mat2D m_Transform; float m_RenderOpacity = 0.0f; @@ -17,8 +15,7 @@ public: #ifdef TESTING - const std::vector<Constraint*>& constraints() const - { + const std::vector<Constraint*>& constraints() const { return m_Constraints; } #endif
diff --git a/include/rive/transform_space.hpp b/include/rive/transform_space.hpp index dc3af7d..2c44d92 100644 --- a/include/rive/transform_space.hpp +++ b/include/rive/transform_space.hpp
@@ -1,11 +1,6 @@ #ifndef _RIVE_TRANSFORM_SPACE_HPP_ #define _RIVE_TRANSFORM_SPACE_HPP_ -namespace rive -{ - enum class TransformSpace : unsigned int - { - world = 0, - local = 1 - }; +namespace rive { + enum class TransformSpace : unsigned int { world = 0, local = 1 }; } #endif \ No newline at end of file
diff --git a/include/rive/world_transform_component.hpp b/include/rive/world_transform_component.hpp index 000484a..320ba86 100644 --- a/include/rive/world_transform_component.hpp +++ b/include/rive/world_transform_component.hpp
@@ -3,11 +3,9 @@ #include "rive/generated/world_transform_component_base.hpp" #include "rive/math/mat2d.hpp" -namespace rive -{ +namespace rive { class TransformComponent; - class WorldTransformComponent : public WorldTransformComponentBase - { + class WorldTransformComponent : public WorldTransformComponentBase { friend class TransformComponent; protected:
diff --git a/skia/renderer/include/skia_renderer.hpp b/skia/renderer/include/skia_renderer.hpp index 8239567..d251f63 100644 --- a/skia/renderer/include/skia_renderer.hpp +++ b/skia/renderer/include/skia_renderer.hpp
@@ -8,114 +8,98 @@ #include "rive/renderer.hpp" #include <vector> -namespace rive -{ - class SkiaRenderPath : public RenderPath - { - private: - SkPath m_Path; +namespace rive { + class SkiaRenderPath : public RenderPath { + private: + SkPath m_Path; - public: - const SkPath& path() const { return m_Path; } - void reset() override; - void addRenderPath(RenderPath* path, const Mat2D& transform) override; - void fillRule(FillRule value) override; - void moveTo(float x, float y) override; - void lineTo(float x, float y) override; - void cubicTo( - float ox, float oy, float ix, float iy, float x, float y) override; - virtual void close() override; - }; + public: + const SkPath& path() const { return m_Path; } + void reset() override; + void addRenderPath(RenderPath* path, const Mat2D& transform) override; + void fillRule(FillRule value) override; + void moveTo(float x, float y) override; + void lineTo(float x, float y) override; + void cubicTo( + float ox, float oy, float ix, float iy, float x, float y) override; + virtual void close() override; + }; - struct GradientStop - { - unsigned int color; - float stop; - GradientStop(unsigned int color, float stop) : color(color), stop(stop) - { - } - }; + struct GradientStop { + unsigned int color; + float stop; + GradientStop(unsigned int color, float stop) : + color(color), stop(stop) {} + }; - class SkiaGradientBuilder - { - public: - std::vector<GradientStop> stops; - float sx, sy, ex, ey; - virtual ~SkiaGradientBuilder() {} - SkiaGradientBuilder(float sx, float sy, float ex, float ey) : - sx(sx), sy(sy), ex(ex), ey(ey) - { - } + class SkiaGradientBuilder { + public: + std::vector<GradientStop> stops; + float sx, sy, ex, ey; + virtual ~SkiaGradientBuilder() {} + SkiaGradientBuilder(float sx, float sy, float ex, float ey) : + sx(sx), sy(sy), ex(ex), ey(ey) {} - virtual void make(SkPaint& paint) = 0; - }; + virtual void make(SkPaint& paint) = 0; + }; - class SkiaRadialGradientBuilder : public SkiaGradientBuilder - { - public: - SkiaRadialGradientBuilder(float sx, float sy, float ex, float ey) : - SkiaGradientBuilder(sx, sy, ex, ey) - { - } - void make(SkPaint& paint) override; - }; + class SkiaRadialGradientBuilder : public SkiaGradientBuilder { + public: + SkiaRadialGradientBuilder(float sx, float sy, float ex, float ey) : + SkiaGradientBuilder(sx, sy, ex, ey) {} + void make(SkPaint& paint) override; + }; - class SkiaLinearGradientBuilder : public SkiaGradientBuilder - { - public: - SkiaLinearGradientBuilder(float sx, float sy, float ex, float ey) : - SkiaGradientBuilder(sx, sy, ex, ey) - { - } - void make(SkPaint& paint) override; - }; + class SkiaLinearGradientBuilder : public SkiaGradientBuilder { + public: + SkiaLinearGradientBuilder(float sx, float sy, float ex, float ey) : + SkiaGradientBuilder(sx, sy, ex, ey) {} + void make(SkPaint& paint) override; + }; - class SkiaRenderPaint : public RenderPaint - { - private: - SkPaint m_Paint; - SkiaGradientBuilder* m_GradientBuilder; + class SkiaRenderPaint : public RenderPaint { + private: + SkPaint m_Paint; + SkiaGradientBuilder* m_GradientBuilder; - public: - const SkPaint& paint() const { return m_Paint; } - SkiaRenderPaint(); - void style(RenderPaintStyle style) override; - void color(unsigned int value) override; - void thickness(float value) override; - void join(StrokeJoin value) override; - void cap(StrokeCap value) override; - void blendMode(BlendMode value) override; + public: + const SkPaint& paint() const { return m_Paint; } + SkiaRenderPaint(); + void style(RenderPaintStyle style) override; + void color(unsigned int value) override; + void thickness(float value) override; + void join(StrokeJoin value) override; + void cap(StrokeCap value) override; + void blendMode(BlendMode value) override; - void linearGradient(float sx, float sy, float ex, float ey) override; - void radialGradient(float sx, float sy, float ex, float ey) override; - void addStop(unsigned int color, float stop) override; - void completeGradient() override; - }; + void linearGradient(float sx, float sy, float ex, float ey) override; + void radialGradient(float sx, float sy, float ex, float ey) override; + void addStop(unsigned int color, float stop) override; + void completeGradient() override; + }; - class SkiaRenderImage : public RenderImage - { - private: - sk_sp<SkImage> m_SkImage; + class SkiaRenderImage : public RenderImage { + private: + sk_sp<SkImage> m_SkImage; - public: - sk_sp<SkImage> skImage() const { return m_SkImage; }; - bool decode(const uint8_t* bytes, std::size_t size) override; - }; + public: + sk_sp<SkImage> skImage() const { return m_SkImage; }; + bool decode(const uint8_t* bytes, std::size_t size) override; + }; - class SkiaRenderer : public Renderer - { - protected: - SkCanvas* m_Canvas; + class SkiaRenderer : public Renderer { + protected: + SkCanvas* m_Canvas; - public: - SkiaRenderer(SkCanvas* canvas) : m_Canvas(canvas) {} - void save() override; - void restore() override; - void transform(const Mat2D& transform) override; - void drawPath(RenderPath* path, RenderPaint* paint) override; - void - drawImage(RenderImage* image, BlendMode value, float opacity) override; - void clipPath(RenderPath* path) override; - }; + public: + SkiaRenderer(SkCanvas* canvas) : m_Canvas(canvas) {} + void save() override; + void restore() override; + void transform(const Mat2D& transform) override; + void drawPath(RenderPath* path, RenderPaint* paint) override; + void + drawImage(RenderImage* image, BlendMode value, float opacity) override; + void clipPath(RenderPath* path) override; + }; } // namespace rive #endif \ No newline at end of file
diff --git a/skia/renderer/include/to_skia.hpp b/skia/renderer/include/to_skia.hpp index cf3f7d9..5eccd26 100644 --- a/skia/renderer/include/to_skia.hpp +++ b/skia/renderer/include/to_skia.hpp
@@ -8,103 +8,93 @@ #include "rive/shapes/paint/stroke_join.hpp" #include "rive/shapes/paint/blend_mode.hpp" -namespace rive -{ - class ToSkia - { - public: - static SkMatrix convert(const rive::Mat2D& m) - { - SkMatrix skMatrix; - skMatrix.set9((SkScalar[9]) - // Skia Matrix is row major - {// Row 1 - m[0], - m[2], - m[4], - // Row 2 - m[1], - m[3], - m[5], - // Row 3 - 0.0, - 0.0, - 1.0}); - return skMatrix; - } +namespace rive { + class ToSkia { + public: + static SkMatrix convert(const rive::Mat2D& m) { + SkMatrix skMatrix; + skMatrix.set9((SkScalar[9]) + // Skia Matrix is row major + {// Row 1 + m[0], + m[2], + m[4], + // Row 2 + m[1], + m[3], + m[5], + // Row 3 + 0.0, + 0.0, + 1.0}); + return skMatrix; + } - static SkPoint convert(const rive::Vec2D& point) - { - return SkPoint::Make(point[0], point[1]); - } + static SkPoint convert(const rive::Vec2D& point) { + return SkPoint::Make(point[0], point[1]); + } - static SkPaint::Cap convert(rive::StrokeCap cap) - { - switch (cap) - { - case rive::StrokeCap::butt: - return SkPaint::Cap::kButt_Cap; - case rive::StrokeCap::round: - return SkPaint::Cap::kRound_Cap; - case rive::StrokeCap::square: - return SkPaint::Cap::kSquare_Cap; - } - return SkPaint::Cap::kButt_Cap; - } + static SkPaint::Cap convert(rive::StrokeCap cap) { + switch (cap) { + case rive::StrokeCap::butt: + return SkPaint::Cap::kButt_Cap; + case rive::StrokeCap::round: + return SkPaint::Cap::kRound_Cap; + case rive::StrokeCap::square: + return SkPaint::Cap::kSquare_Cap; + } + return SkPaint::Cap::kButt_Cap; + } - static SkPaint::Join convert(rive::StrokeJoin join) - { - switch (join) - { - case rive::StrokeJoin::bevel: - return SkPaint::Join::kBevel_Join; - case rive::StrokeJoin::round: - return SkPaint::Join::kRound_Join; - case rive::StrokeJoin::miter: - return SkPaint::Join::kMiter_Join; - } - return SkPaint::Join::kMiter_Join; - } + static SkPaint::Join convert(rive::StrokeJoin join) { + switch (join) { + case rive::StrokeJoin::bevel: + return SkPaint::Join::kBevel_Join; + case rive::StrokeJoin::round: + return SkPaint::Join::kRound_Join; + case rive::StrokeJoin::miter: + return SkPaint::Join::kMiter_Join; + } + return SkPaint::Join::kMiter_Join; + } - static SkBlendMode convert(rive::BlendMode blendMode) - { - switch (blendMode) - { - case rive::BlendMode::srcOver: - return SkBlendMode::kSrcOver; - case rive::BlendMode::screen: - return SkBlendMode::kScreen; - case rive::BlendMode::overlay: - return SkBlendMode::kOverlay; - case rive::BlendMode::darken: - return SkBlendMode::kDarken; - case rive::BlendMode::lighten: - return SkBlendMode::kLighten; - case rive::BlendMode::colorDodge: - return SkBlendMode::kColorDodge; - case rive::BlendMode::colorBurn: - return SkBlendMode::kColorBurn; - case rive::BlendMode::hardLight: - return SkBlendMode::kHardLight; - case rive::BlendMode::softLight: - return SkBlendMode::kSoftLight; - case rive::BlendMode::difference: - return SkBlendMode::kDifference; - case rive::BlendMode::exclusion: - return SkBlendMode::kExclusion; - case rive::BlendMode::multiply: - return SkBlendMode::kMultiply; - case rive::BlendMode::hue: - return SkBlendMode::kHue; - case rive::BlendMode::saturation: - return SkBlendMode::kSaturation; - case rive::BlendMode::color: - return SkBlendMode::kColor; - case rive::BlendMode::luminosity: - return SkBlendMode::kLuminosity; - } - return SkBlendMode::kSrcOver; - } - }; + static SkBlendMode convert(rive::BlendMode blendMode) { + switch (blendMode) { + case rive::BlendMode::srcOver: + return SkBlendMode::kSrcOver; + case rive::BlendMode::screen: + return SkBlendMode::kScreen; + case rive::BlendMode::overlay: + return SkBlendMode::kOverlay; + case rive::BlendMode::darken: + return SkBlendMode::kDarken; + case rive::BlendMode::lighten: + return SkBlendMode::kLighten; + case rive::BlendMode::colorDodge: + return SkBlendMode::kColorDodge; + case rive::BlendMode::colorBurn: + return SkBlendMode::kColorBurn; + case rive::BlendMode::hardLight: + return SkBlendMode::kHardLight; + case rive::BlendMode::softLight: + return SkBlendMode::kSoftLight; + case rive::BlendMode::difference: + return SkBlendMode::kDifference; + case rive::BlendMode::exclusion: + return SkBlendMode::kExclusion; + case rive::BlendMode::multiply: + return SkBlendMode::kMultiply; + case rive::BlendMode::hue: + return SkBlendMode::kHue; + case rive::BlendMode::saturation: + return SkBlendMode::kSaturation; + case rive::BlendMode::color: + return SkBlendMode::kColor; + case rive::BlendMode::luminosity: + return SkBlendMode::kLuminosity; + } + return SkBlendMode::kSrcOver; + } + }; } // namespace rive #endif \ No newline at end of file
diff --git a/skia/renderer/src/skia_renderer.cpp b/skia/renderer/src/skia_renderer.cpp index 8ffa4dc..afee006 100644 --- a/skia/renderer/src/skia_renderer.cpp +++ b/skia/renderer/src/skia_renderer.cpp
@@ -7,10 +7,8 @@ using namespace rive; -void SkiaRenderPath::fillRule(FillRule value) -{ - switch (value) - { +void SkiaRenderPath::fillRule(FillRule value) { + switch (value) { case FillRule::evenOdd: m_Path.setFillType(SkPathFillType::kEvenOdd); break; @@ -21,8 +19,7 @@ } void SkiaRenderPath::reset() { m_Path.reset(); } -void SkiaRenderPath::addRenderPath(RenderPath* path, const Mat2D& transform) -{ +void SkiaRenderPath::addRenderPath(RenderPath* path, const Mat2D& transform) { m_Path.addPath(reinterpret_cast<SkiaRenderPath*>(path)->m_Path, ToSkia::convert(transform)); } @@ -30,18 +27,15 @@ void SkiaRenderPath::moveTo(float x, float y) { m_Path.moveTo(x, y); } void SkiaRenderPath::lineTo(float x, float y) { m_Path.lineTo(x, y); } void SkiaRenderPath::cubicTo( - float ox, float oy, float ix, float iy, float x, float y) -{ + float ox, float oy, float ix, float iy, float x, float y) { m_Path.cubicTo(ox, oy, ix, iy, x, y); } void SkiaRenderPath::close() { m_Path.close(); } SkiaRenderPaint::SkiaRenderPaint() { m_Paint.setAntiAlias(true); } -void SkiaRenderPaint::style(RenderPaintStyle style) -{ - switch (style) - { +void SkiaRenderPaint::style(RenderPaintStyle style) { + switch (style) { case RenderPaintStyle::fill: m_Paint.setStyle(SkPaint::Style::kFill_Style); break; @@ -52,47 +46,38 @@ } void SkiaRenderPaint::color(unsigned int value) { m_Paint.setColor(value); } void SkiaRenderPaint::thickness(float value) { m_Paint.setStrokeWidth(value); } -void SkiaRenderPaint::join(StrokeJoin value) -{ +void SkiaRenderPaint::join(StrokeJoin value) { m_Paint.setStrokeJoin(ToSkia::convert(value)); } -void SkiaRenderPaint::cap(StrokeCap value) -{ +void SkiaRenderPaint::cap(StrokeCap value) { m_Paint.setStrokeCap(ToSkia::convert(value)); } -void SkiaRenderPaint::linearGradient(float sx, float sy, float ex, float ey) -{ +void SkiaRenderPaint::linearGradient(float sx, float sy, float ex, float ey) { m_GradientBuilder = new SkiaLinearGradientBuilder(sx, sy, ex, ey); } -void SkiaRenderPaint::radialGradient(float sx, float sy, float ex, float ey) -{ +void SkiaRenderPaint::radialGradient(float sx, float sy, float ex, float ey) { m_GradientBuilder = new SkiaRadialGradientBuilder(sx, sy, ex, ey); } -void SkiaRenderPaint::addStop(unsigned int color, float stop) -{ +void SkiaRenderPaint::addStop(unsigned int color, float stop) { m_GradientBuilder->stops.emplace_back(GradientStop(color, stop)); } -void SkiaRenderPaint::completeGradient() -{ +void SkiaRenderPaint::completeGradient() { m_GradientBuilder->make(m_Paint); delete m_GradientBuilder; } -void SkiaRenderPaint::blendMode(BlendMode value) -{ +void SkiaRenderPaint::blendMode(BlendMode value) { m_Paint.setBlendMode(ToSkia::convert(value)); } -void SkiaRadialGradientBuilder::make(SkPaint& paint) -{ +void SkiaRadialGradientBuilder::make(SkPaint& paint) { int numStops = stops.size(); SkColor colors[numStops]; SkScalar pos[numStops]; - for (int i = 0; i < numStops; i++) - { + for (int i = 0; i < numStops; i++) { const GradientStop& stop = stops[i]; colors[i] = SkColor(stop.color); pos[i] = stop.stop; @@ -109,15 +94,13 @@ nullptr)); } -void SkiaLinearGradientBuilder::make(SkPaint& paint) -{ +void SkiaLinearGradientBuilder::make(SkPaint& paint) { int numStops = stops.size(); SkPoint points[2] = {SkPoint::Make(sx, sy), SkPoint::Make(ex, ey)}; SkColor colors[numStops]; SkScalar pos[numStops]; - for (int i = 0; i < numStops; i++) - { + for (int i = 0; i < numStops; i++) { const GradientStop& stop = stops[i]; colors[i] = SkColor(stop.color); pos[i] = stop.stop; @@ -128,25 +111,21 @@ void SkiaRenderer::save() { m_Canvas->save(); } void SkiaRenderer::restore() { m_Canvas->restore(); } -void SkiaRenderer::transform(const Mat2D& transform) -{ +void SkiaRenderer::transform(const Mat2D& transform) { m_Canvas->concat(ToSkia::convert(transform)); } -void SkiaRenderer::drawPath(RenderPath* path, RenderPaint* paint) -{ +void SkiaRenderer::drawPath(RenderPath* path, RenderPaint* paint) { m_Canvas->drawPath(reinterpret_cast<SkiaRenderPath*>(path)->path(), reinterpret_cast<SkiaRenderPaint*>(paint)->paint()); } -void SkiaRenderer::clipPath(RenderPath* path) -{ +void SkiaRenderer::clipPath(RenderPath* path) { m_Canvas->clipPath(reinterpret_cast<SkiaRenderPath*>(path)->path(), true); } void SkiaRenderer::drawImage(RenderImage* image, BlendMode blendMode, - float opacity) -{ + float opacity) { SkPaint paint; paint.setAlphaf(opacity); paint.setBlendMode(ToSkia::convert(blendMode)); @@ -157,8 +136,7 @@ skiaImage->skImage(), 0.0f, 0.0f, samplingOptions, &paint); } -bool SkiaRenderImage::decode(const uint8_t* bytes, std::size_t size) -{ +bool SkiaRenderImage::decode(const uint8_t* bytes, std::size_t size) { sk_sp<SkData> data = SkData::MakeWithoutCopy(bytes, size); m_SkImage = SkImage::MakeFromEncoded(data); @@ -167,8 +145,7 @@ return true; } -namespace rive -{ +namespace rive { RenderPath* makeRenderPath() { return new SkiaRenderPath(); } RenderPaint* makeRenderPaint() { return new SkiaRenderPaint(); } RenderImage* makeRenderImage() { return new SkiaRenderImage(); }
diff --git a/skia/thumbnail_generator/src/main.cpp b/skia/thumbnail_generator/src/main.cpp index 88803cb..44ba911 100644 --- a/skia/thumbnail_generator/src/main.cpp +++ b/skia/thumbnail_generator/src/main.cpp
@@ -10,92 +10,81 @@ #include <stdio.h> #include <string> -std::string getFileName(char* path) -{ - std::string str(path); +std::string getFileName(char* path) { + std::string str(path); - const size_t from = str.find_last_of("\\/"); - const size_t to = str.find_last_of("."); - return str.substr(from + 1, to - from - 1); + const size_t from = str.find_last_of("\\/"); + const size_t to = str.find_last_of("."); + return str.substr(from + 1, to - from - 1); } -int main(int argc, char* argv[]) -{ - if (argc < 2) - { - fprintf(stderr, "must pass source file"); - return 1; - } - FILE* fp = fopen(argv[1], "r"); +int main(int argc, char* argv[]) { + if (argc < 2) { + fprintf(stderr, "must pass source file"); + return 1; + } + FILE* fp = fopen(argv[1], "r"); - const char* outPath; - std::string filename; - std::string fullName; - if (argc > 2) - { - outPath = argv[2]; - } - else - { - filename = getFileName(argv[1]); - fullName = filename + ".png"; - outPath = fullName.c_str(); - } + const char* outPath; + std::string filename; + std::string fullName; + if (argc > 2) { + outPath = argv[2]; + } else { + filename = getFileName(argv[1]); + fullName = filename + ".png"; + outPath = fullName.c_str(); + } - if (fp == nullptr) - { - fprintf(stderr, "Failed to open rive file.\n"); - return 1; - } - fseek(fp, 0, SEEK_END); - auto length = ftell(fp); - fseek(fp, 0, SEEK_SET); - uint8_t* bytes = new uint8_t[length]; - if (fread(bytes, 1, length, fp) != length) - { - fprintf(stderr, "Failed to read rive file.\n"); - return 1; - } + if (fp == nullptr) { + fprintf(stderr, "Failed to open rive file.\n"); + return 1; + } + fseek(fp, 0, SEEK_END); + auto length = ftell(fp); + fseek(fp, 0, SEEK_SET); + uint8_t* bytes = new uint8_t[length]; + if (fread(bytes, 1, length, fp) != length) { + fprintf(stderr, "Failed to read rive file.\n"); + return 1; + } - auto reader = rive::BinaryReader(bytes, length); - rive::File* file = nullptr; - auto result = rive::File::import(reader, &file); - if (result != rive::ImportResult::success) - { - fprintf(stderr, "Failed to read rive file.\n"); - return 1; - } - auto artboard = file->artboard(); - artboard->advance(0.0f); + auto reader = rive::BinaryReader(bytes, length); + rive::File* file = nullptr; + auto result = rive::File::import(reader, &file); + if (result != rive::ImportResult::success) { + fprintf(stderr, "Failed to read rive file.\n"); + return 1; + } + auto artboard = file->artboard(); + artboard->advance(0.0f); - delete[] bytes; + delete[] bytes; - int width = 256, height = 256; + int width = 256, height = 256; - sk_sp<SkSurface> rasterSurface = - SkSurface::MakeRasterN32Premul(width, height); - SkCanvas* rasterCanvas = rasterSurface->getCanvas(); + sk_sp<SkSurface> rasterSurface = + SkSurface::MakeRasterN32Premul(width, height); + SkCanvas* rasterCanvas = rasterSurface->getCanvas(); - rive::SkiaRenderer renderer(rasterCanvas); - renderer.save(); - renderer.align(rive::Fit::cover, - rive::Alignment::center, - rive::AABB(0, 0, width, height), - artboard->bounds()); - artboard->draw(&renderer); - renderer.restore(); + rive::SkiaRenderer renderer(rasterCanvas); + renderer.save(); + renderer.align(rive::Fit::cover, + rive::Alignment::center, + rive::AABB(0, 0, width, height), + artboard->bounds()); + artboard->draw(&renderer); + renderer.restore(); - sk_sp<SkImage> img(rasterSurface->makeImageSnapshot()); - if (!img) - { - return 1; - } - sk_sp<SkData> png(img->encodeToData()); - if (!png) - { - return 1; - } - SkFILEWStream out(outPath); - (void)out.write(png->data(), png->size()); - return 0; + sk_sp<SkImage> img(rasterSurface->makeImageSnapshot()); + if (!img) { + return 1; + } + sk_sp<SkData> png(img->encodeToData()); + if (!png) { + return 1; + } + SkFILEWStream out(outPath); + (void)out.write(png->data(), png->size()); + return 0; }
diff --git a/skia/viewer/src/main.cpp b/skia/viewer/src/main.cpp index 85ec800..a64d569 100644 --- a/skia/viewer/src/main.cpp +++ b/skia/viewer/src/main.cpp
@@ -42,364 +42,335 @@ int animationIndex = 0; int stateMachineIndex = -1; -void initStateMachine(int index) -{ - stateMachineIndex = index; - animationIndex = -1; - assert(fileBytes != nullptr); - auto reader = rive::BinaryReader(fileBytes, fileBytesLength); - rive::File* file = nullptr; - auto result = rive::File::import(reader, &file); - if (result != rive::ImportResult::success) - { - delete[] fileBytes; - fprintf(stderr, "failed to import file\n"); - return; - } - auto sourceArtboard = file->artboard(); - // Artboard should always be instance and hence must be deleted. - delete artboard; - artboard = sourceArtboard->instance(); - artboard->advance(0.0f); +void initStateMachine(int index) { + stateMachineIndex = index; + animationIndex = -1; + assert(fileBytes != nullptr); + auto reader = rive::BinaryReader(fileBytes, fileBytesLength); + rive::File* file = nullptr; + auto result = rive::File::import(reader, &file); + if (result != rive::ImportResult::success) { + delete[] fileBytes; + fprintf(stderr, "failed to import file\n"); + return; + } + auto sourceArtboard = file->artboard(); + // Artboard should always be instance and hence must be deleted. + delete artboard; + artboard = sourceArtboard->instance(); + artboard->advance(0.0f); - delete animationInstance; - delete stateMachineInstance; - delete currentFile; - animationInstance = nullptr; - stateMachineInstance = nullptr; + delete animationInstance; + delete stateMachineInstance; + delete currentFile; + animationInstance = nullptr; + stateMachineInstance = nullptr; - auto stateMachine = index >= 0 && index < artboard->stateMachineCount() - ? artboard->stateMachine(index) - : nullptr; - if (stateMachine != nullptr) - { - stateMachineInstance = new rive::StateMachineInstance(stateMachine); - } + auto stateMachine = index >= 0 && index < artboard->stateMachineCount() + ? artboard->stateMachine(index) + : nullptr; + if (stateMachine != nullptr) { + stateMachineInstance = new rive::StateMachineInstance(stateMachine); + } - currentFile = file; + currentFile = file; } -void initAnimation(int index) -{ - animationIndex = index; - stateMachineIndex = -1; - assert(fileBytes != nullptr); - auto reader = rive::BinaryReader(fileBytes, fileBytesLength); - rive::File* file = nullptr; - auto result = rive::File::import(reader, &file); - if (result != rive::ImportResult::success) - { - delete[] fileBytes; - fprintf(stderr, "failed to import file\n"); - return; - } - auto sourceArtboard = file->artboard(); - // Artboard should always be instance and hence must be deleted. - delete artboard; - artboard = sourceArtboard->instance(); - artboard->advance(0.0f); +void initAnimation(int index) { + animationIndex = index; + stateMachineIndex = -1; + assert(fileBytes != nullptr); + auto reader = rive::BinaryReader(fileBytes, fileBytesLength); + rive::File* file = nullptr; + auto result = rive::File::import(reader, &file); + if (result != rive::ImportResult::success) { + delete[] fileBytes; + fprintf(stderr, "failed to import file\n"); + return; + } + auto sourceArtboard = file->artboard(); + // Artboard should always be instance and hence must be deleted. + delete artboard; + artboard = sourceArtboard->instance(); + artboard->advance(0.0f); - delete animationInstance; - delete stateMachineInstance; - delete currentFile; - animationInstance = nullptr; - stateMachineInstance = nullptr; + delete animationInstance; + delete stateMachineInstance; + delete currentFile; + animationInstance = nullptr; + stateMachineInstance = nullptr; - auto animation = index >= 0 && index < artboard->animationCount() - ? artboard->animation(index) - : nullptr; - if (animation != nullptr) - { - animationInstance = new rive::LinearAnimationInstance(animation); - } + auto animation = index >= 0 && index < artboard->animationCount() + ? artboard->animation(index) + : nullptr; + if (animation != nullptr) { + animationInstance = new rive::LinearAnimationInstance(animation); + } - currentFile = file; + currentFile = file; } -void glfwErrorCallback(int error, const char* description) -{ - puts(description); +void glfwErrorCallback(int error, const char* description) { + puts(description); } -void glfwDropCallback(GLFWwindow* window, int count, const char** paths) -{ - // Just get the last dropped file for now... - filename = paths[count - 1]; +void glfwDropCallback(GLFWwindow* window, int count, const char** paths) { + // Just get the last dropped file for now... + filename = paths[count - 1]; - FILE* fp = fopen(filename.c_str(), "r"); - fseek(fp, 0, SEEK_END); - fileBytesLength = ftell(fp); - fseek(fp, 0, SEEK_SET); - delete[] fileBytes; - fileBytes = new uint8_t[fileBytesLength]; - if (fread(fileBytes, 1, fileBytesLength, fp) != fileBytesLength) - { - delete[] fileBytes; - fprintf(stderr, "failed to read all of %s\n", filename.c_str()); - return; - } - initAnimation(0); + FILE* fp = fopen(filename.c_str(), "r"); + fseek(fp, 0, SEEK_END); + fileBytesLength = ftell(fp); + fseek(fp, 0, SEEK_SET); + delete[] fileBytes; + fileBytes = new uint8_t[fileBytesLength]; + if (fread(fileBytes, 1, fileBytesLength, fp) != fileBytesLength) { + delete[] fileBytes; + fprintf(stderr, "failed to read all of %s\n", filename.c_str()); + return; + } + initAnimation(0); } -int main() -{ - if (!glfwInit()) - { - fprintf(stderr, "Failed to initialize glfw.\n"); - return 1; - } - glfwSetErrorCallback(glfwErrorCallback); +int main() { + if (!glfwInit()) { + fprintf(stderr, "Failed to initialize glfw.\n"); + return 1; + } + glfwSetErrorCallback(glfwErrorCallback); - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); - GLFWwindow* window = glfwCreateWindow(1280, 720, "Rive Viewer", NULL, NULL); - if (window == nullptr) - { - fprintf(stderr, "Failed to make window or GL.\n"); - glfwTerminate(); - return 1; - } + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); + GLFWwindow* window = glfwCreateWindow(1280, 720, "Rive Viewer", NULL, NULL); + if (window == nullptr) { + fprintf(stderr, "Failed to make window or GL.\n"); + glfwTerminate(); + return 1; + } - glfwSetDropCallback(window, glfwDropCallback); - glfwMakeContextCurrent(window); - if (gl3wInit() != 0) - { - fprintf(stderr, "Failed to make initialize gl3w.\n"); - glfwTerminate(); - return 1; - } - // Enable VSYNC. - glfwSwapInterval(1); + glfwSetDropCallback(window, glfwDropCallback); + glfwMakeContextCurrent(window); + if (gl3wInit() != 0) { + fprintf(stderr, "Failed to make initialize gl3w.\n"); + glfwTerminate(); + return 1; + } + // Enable VSYNC. + glfwSwapInterval(1); - // Setup ImGui - ImGui::CreateContext(); - ImGuiIO& io = ImGui::GetIO(); - (void)io; + // Setup ImGui + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); + (void)io; - ImGui::StyleColorsDark(); - ImGui_ImplGlfw_InitForOpenGL(window, true); - ImGui_ImplOpenGL3_Init("#version 150"); - io.Fonts->AddFontDefault(); + ImGui::StyleColorsDark(); + ImGui_ImplGlfw_InitForOpenGL(window, true); + ImGui_ImplOpenGL3_Init("#version 150"); + io.Fonts->AddFontDefault(); - // Setup Skia - GrContextOptions options; - sk_sp<GrDirectContext> context = GrDirectContext::MakeGL(nullptr, options); - GrGLFramebufferInfo framebufferInfo; - framebufferInfo.fFBOID = 0; - framebufferInfo.fFormat = GL_RGBA8; + // Setup Skia + GrContextOptions options; + sk_sp<GrDirectContext> context = GrDirectContext::MakeGL(nullptr, options); + GrGLFramebufferInfo framebufferInfo; + framebufferInfo.fFBOID = 0; + framebufferInfo.fFormat = GL_RGBA8; - SkSurface* surface = nullptr; - SkCanvas* canvas = nullptr; + SkSurface* surface = nullptr; + SkCanvas* canvas = nullptr; - // Render loop. - int width = 0, height = 0; - int lastScreenWidth = 0, lastScreenHeight = 0; - double lastTime = glfwGetTime(); - while (!glfwWindowShouldClose(window)) - { - glfwGetFramebufferSize(window, &width, &height); + // Render loop. + int width = 0, height = 0; + int lastScreenWidth = 0, lastScreenHeight = 0; + double lastTime = glfwGetTime(); + while (!glfwWindowShouldClose(window)) { + glfwGetFramebufferSize(window, &width, &height); - // Update surface. - if (surface == nullptr || width != lastScreenWidth || - height != lastScreenHeight) - { - lastScreenWidth = width; - lastScreenHeight = height; + // Update surface. + if (surface == nullptr || width != lastScreenWidth || + height != lastScreenHeight) + { + lastScreenWidth = width; + lastScreenHeight = height; - SkColorType colorType = - kRGBA_8888_SkColorType; // GrColorTypeToSkColorType(GrPixelConfigToColorType(kRGBA_8888_GrPixelConfig)); - // - // if (kRGBA_8888_GrPixelConfig == kSkia8888_GrPixelConfig) - // { - // colorType = kRGBA_8888_SkColorType; - // } - // else - // { - // colorType = kBGRA_8888_SkColorType; - // } + SkColorType colorType = + kRGBA_8888_SkColorType; // GrColorTypeToSkColorType(GrPixelConfigToColorType(kRGBA_8888_GrPixelConfig)); + // + // if (kRGBA_8888_GrPixelConfig == kSkia8888_GrPixelConfig) + // { + // colorType = kRGBA_8888_SkColorType; + // } + // else + // { + // colorType = kBGRA_8888_SkColorType; + // } - GrBackendRenderTarget backendRenderTarget(width, - height, - 0, // sample count - 0, // stencil bits - framebufferInfo); + GrBackendRenderTarget backendRenderTarget(width, + height, + 0, // sample count + 0, // stencil bits + framebufferInfo); - delete surface; - surface = SkSurface::MakeFromBackendRenderTarget( - context.get(), - backendRenderTarget, - kBottomLeft_GrSurfaceOrigin, - colorType, - nullptr, - nullptr) - .release(); - if (surface == nullptr) - { - fprintf(stderr, "Failed to create Skia surface\n"); - return 1; - } - canvas = surface->getCanvas(); - } + delete surface; + surface = SkSurface::MakeFromBackendRenderTarget( + context.get(), + backendRenderTarget, + kBottomLeft_GrSurfaceOrigin, + colorType, + nullptr, + nullptr) + .release(); + if (surface == nullptr) { + fprintf(stderr, "Failed to create Skia surface\n"); + return 1; + } + canvas = surface->getCanvas(); + } - double time = glfwGetTime(); - float elapsed = (float)(time - lastTime); - lastTime = time; + double time = glfwGetTime(); + float elapsed = (float)(time - lastTime); + lastTime = time; - // Clear screen. - SkPaint paint; - paint.setColor(SK_ColorDKGRAY); - canvas->drawPaint(paint); + // Clear screen. + SkPaint paint; + paint.setColor(SK_ColorDKGRAY); + canvas->drawPaint(paint); - if (artboard != nullptr) - { - if (animationInstance != nullptr) - { - animationInstance->advance(elapsed); - animationInstance->apply(artboard); - } - else if (stateMachineInstance != nullptr) - { - stateMachineInstance->advance(artboard, elapsed); - } - artboard->advance(elapsed); + if (artboard != nullptr) { + if (animationInstance != nullptr) { + animationInstance->advance(elapsed); + animationInstance->apply(artboard); + } else if (stateMachineInstance != nullptr) { + stateMachineInstance->advance(artboard, elapsed); + } + artboard->advance(elapsed); - rive::SkiaRenderer renderer(canvas); - renderer.save(); - renderer.align(rive::Fit::contain, - rive::Alignment::center, - rive::AABB(0, 0, width, height), - artboard->bounds()); - artboard->draw(&renderer); - renderer.restore(); - } + rive::SkiaRenderer renderer(canvas); + renderer.save(); + renderer.align(rive::Fit::contain, + rive::Alignment::center, + rive::AABB(0, 0, width, height), + artboard->bounds()); + artboard->draw(&renderer); + renderer.restore(); + } - context->flush(); + context->flush(); - ImGui_ImplOpenGL3_NewFrame(); - ImGui_ImplGlfw_NewFrame(); - ImGui::NewFrame(); + ImGui_ImplOpenGL3_NewFrame(); + ImGui_ImplGlfw_NewFrame(); + ImGui::NewFrame(); - if (artboard != nullptr) - { - ImGui::Begin(filename.c_str(), nullptr); - if (ImGui::ListBox( - "Animations", - &animationIndex, - [](void* data, int index, const char** name) { - const char* animationName = - artboard->animation(index)->name().c_str(); - *name = animationName; - return true; - }, - artboard, - artboard->animationCount(), - 4)) - { - stateMachineIndex = -1; - initAnimation(animationIndex); - } - if (ImGui::ListBox( - "State Machines", - &stateMachineIndex, - [](void* data, int index, const char** name) { - const char* machineName = - artboard->stateMachine(index)->name().c_str(); - *name = machineName; - return true; - }, - artboard, - artboard->stateMachineCount(), - 4)) - { - animationIndex = -1; - initStateMachine(stateMachineIndex); - } - if (stateMachineInstance != nullptr) - { + if (artboard != nullptr) { + ImGui::Begin(filename.c_str(), nullptr); + if (ImGui::ListBox( + "Animations", + &animationIndex, + [](void* data, int index, const char** name) { + const char* animationName = + artboard->animation(index)->name().c_str(); + *name = animationName; + return true; + }, + artboard, + artboard->animationCount(), + 4)) + { + stateMachineIndex = -1; + initAnimation(animationIndex); + } + if (ImGui::ListBox( + "State Machines", + &stateMachineIndex, + [](void* data, int index, const char** name) { + const char* machineName = + artboard->stateMachine(index)->name().c_str(); + *name = machineName; + return true; + }, + artboard, + artboard->stateMachineCount(), + 4)) + { + animationIndex = -1; + initStateMachine(stateMachineIndex); + } + if (stateMachineInstance != nullptr) { - ImGui::Columns(2); - ImGui::SetColumnWidth(0, ImGui::GetWindowWidth() * 0.6666); + ImGui::Columns(2); + ImGui::SetColumnWidth(0, ImGui::GetWindowWidth() * 0.6666); - for (int i = 0; i < stateMachineInstance->inputCount(); i++) - { - auto inputInstance = stateMachineInstance->input(i); + for (int i = 0; i < stateMachineInstance->inputCount(); i++) { + auto inputInstance = stateMachineInstance->input(i); - if (inputInstance->input()->is<rive::StateMachineNumber>()) - { - // ImGui requires names as id's, use ## to hide the - // label but still give it an id. - char label[256]; - snprintf(label, 256, "##%u", i); + if (inputInstance->input()->is<rive::StateMachineNumber>()) + { + // ImGui requires names as id's, use ## to hide the + // label but still give it an id. + char label[256]; + snprintf(label, 256, "##%u", i); - auto number = - static_cast<rive::SMINumber*>(inputInstance); - float v = number->value(); - ImGui::InputFloat(label, &v, 1.0f, 2.0f, "%.3f"); - number->value(v); - ImGui::NextColumn(); - } - else if (inputInstance->input() - ->is<rive::StateMachineTrigger>()) - { - // ImGui requires names as id's, use ## to hide the - // label but still give it an id. - char label[256]; - snprintf(label, 256, "Fire##%u", i); - if (ImGui::Button(label)) - { - auto trigger = - static_cast<rive::SMITrigger*>(inputInstance); - trigger->fire(); - } - ImGui::NextColumn(); - } - else if (inputInstance->input() - ->is<rive::StateMachineBool>()) - { - // ImGui requires names as id's, use ## to hide the - // label but still give it an id. - char label[256]; - snprintf(label, 256, "##%u", i); - auto boolInput = - static_cast<rive::SMIBool*>(inputInstance); - bool value = boolInput->value(); + auto number = + static_cast<rive::SMINumber*>(inputInstance); + float v = number->value(); + ImGui::InputFloat(label, &v, 1.0f, 2.0f, "%.3f"); + number->value(v); + ImGui::NextColumn(); + } else if (inputInstance->input() + ->is<rive::StateMachineTrigger>()) { + // ImGui requires names as id's, use ## to hide the + // label but still give it an id. + char label[256]; + snprintf(label, 256, "Fire##%u", i); + if (ImGui::Button(label)) { + auto trigger = + static_cast<rive::SMITrigger*>(inputInstance); + trigger->fire(); + } + ImGui::NextColumn(); + } else if (inputInstance->input() + ->is<rive::StateMachineBool>()) { + // ImGui requires names as id's, use ## to hide the + // label but still give it an id. + char label[256]; + snprintf(label, 256, "##%u", i); + auto boolInput = + static_cast<rive::SMIBool*>(inputInstance); + bool value = boolInput->value(); - ImGui::Checkbox(label, &value); - boolInput->value(value); - ImGui::NextColumn(); - } - ImGui::Text("%s", inputInstance->input()->name().c_str()); - ImGui::NextColumn(); - } + ImGui::Checkbox(label, &value); + boolInput->value(value); + ImGui::NextColumn(); + } + ImGui::Text("%s", inputInstance->input()->name().c_str()); + ImGui::NextColumn(); + } - ImGui::Columns(1); - } - ImGui::End(); - } - else - { - ImGui::Text("Drop a .riv file to preview."); - } + ImGui::Columns(1); + } + ImGui::End(); + } else { + ImGui::Text("Drop a .riv file to preview."); + } - ImGui::Render(); - ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); + ImGui::Render(); + ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); - glfwSwapBuffers(window); - glfwPollEvents(); - } + glfwSwapBuffers(window); + glfwPollEvents(); + } - delete currentFile; - delete[] fileBytes; + delete currentFile; + delete[] fileBytes; - // Cleanup Skia. - delete surface; - context = nullptr; + // Cleanup Skia. + delete surface; + context = nullptr; - ImGui_ImplGlfw_Shutdown(); + ImGui_ImplGlfw_Shutdown(); - // Cleanup GLFW. - glfwDestroyWindow(window); - glfwTerminate(); + // Cleanup GLFW. + glfwDestroyWindow(window); + glfwTerminate(); - return 0; + return 0; } \ No newline at end of file
diff --git a/src/animation/animation_state.cpp b/src/animation/animation_state.cpp index e8547f1..b6e85a8 100644 --- a/src/animation/animation_state.cpp +++ b/src/animation/animation_state.cpp
@@ -7,10 +7,8 @@ using namespace rive; -StateInstance* AnimationState::makeInstance() const -{ - if (animation() == nullptr) - { +StateInstance* AnimationState::makeInstance() const { + if (animation() == nullptr) { // Failed to load at runtime/some new type we don't understand. return new SystemStateInstance(this); }
diff --git a/src/animation/animation_state_instance.cpp b/src/animation/animation_state_instance.cpp index d6b2d0f..09619f1 100644 --- a/src/animation/animation_state_instance.cpp +++ b/src/animation/animation_state_instance.cpp
@@ -6,17 +6,13 @@ AnimationStateInstance::AnimationStateInstance(const AnimationState* state) : StateInstance(state), m_AnimationInstance(state->animation()), - m_KeepGoing(true) -{ -} + m_KeepGoing(true) {} -void AnimationStateInstance::advance(float seconds, SMIInput** inputs) -{ +void AnimationStateInstance::advance(float seconds, SMIInput** inputs) { m_KeepGoing = m_AnimationInstance.advance(seconds); } -void AnimationStateInstance::apply(Artboard* artboard, float mix) -{ +void AnimationStateInstance::apply(Artboard* artboard, float mix) { m_AnimationInstance.apply(artboard, mix); }
diff --git a/src/animation/blend_animation.cpp b/src/animation/blend_animation.cpp index 75675d3..bca5529 100644 --- a/src/animation/blend_animation.cpp +++ b/src/animation/blend_animation.cpp
@@ -6,30 +6,24 @@ using namespace rive; -StatusCode BlendAnimation::import(ImportStack& importStack) -{ +StatusCode BlendAnimation::import(ImportStack& importStack) { auto importer = importStack.latest<LayerStateImporter>(LayerStateBase::typeKey); - if (importer == nullptr) - { + if (importer == nullptr) { return StatusCode::MissingObject; - } - else if (!importer->addBlendAnimation(this)) - { + } else if (!importer->addBlendAnimation(this)) { return StatusCode::InvalidObject; } auto artboardImporter = importStack.latest<ArtboardImporter>(ArtboardBase::typeKey); - if (artboardImporter == nullptr) - { + if (artboardImporter == nullptr) { return StatusCode::MissingObject; } auto artboard = artboardImporter->artboard(); auto animationCount = artboard->animationCount(); - if (animationId() >= 0 && animationId() < animationCount) - { + if (animationId() >= 0 && animationId() < animationCount) { m_Animation = artboardImporter->artboard()->animation(animationId()); }
diff --git a/src/animation/blend_animation_1d.cpp b/src/animation/blend_animation_1d.cpp index 286c537..338dcca 100644 --- a/src/animation/blend_animation_1d.cpp +++ b/src/animation/blend_animation_1d.cpp
@@ -2,12 +2,10 @@ using namespace rive; -StatusCode BlendAnimation1D::onAddedDirty(CoreContext* context) -{ +StatusCode BlendAnimation1D::onAddedDirty(CoreContext* context) { return StatusCode::Ok; } -StatusCode BlendAnimation1D::onAddedClean(CoreContext* context) -{ +StatusCode BlendAnimation1D::onAddedClean(CoreContext* context) { return StatusCode::Ok; } \ No newline at end of file
diff --git a/src/animation/blend_animation_direct.cpp b/src/animation/blend_animation_direct.cpp index bf51e65..ab82fe9 100644 --- a/src/animation/blend_animation_direct.cpp +++ b/src/animation/blend_animation_direct.cpp
@@ -5,22 +5,18 @@ using namespace rive; -StatusCode BlendAnimationDirect::onAddedDirty(CoreContext* context) -{ +StatusCode BlendAnimationDirect::onAddedDirty(CoreContext* context) { return StatusCode::Ok; } -StatusCode BlendAnimationDirect::onAddedClean(CoreContext* context) -{ +StatusCode BlendAnimationDirect::onAddedClean(CoreContext* context) { return StatusCode::Ok; } -StatusCode BlendAnimationDirect::import(ImportStack& importStack) -{ +StatusCode BlendAnimationDirect::import(ImportStack& importStack) { auto stateMachineImporter = importStack.latest<StateMachineImporter>(StateMachine::typeKey); - if (stateMachineImporter == nullptr) - { + if (stateMachineImporter == nullptr) { return StatusCode::MissingObject; } @@ -31,8 +27,7 @@ return StatusCode::InvalidObject; } auto input = stateMachineImporter->stateMachine()->input((size_t)inputId()); - if (input == nullptr || !input->is<StateMachineNumber>()) - { + if (input == nullptr || !input->is<StateMachineNumber>()) { return StatusCode::InvalidObject; } return Super::import(importStack);
diff --git a/src/animation/blend_state.cpp b/src/animation/blend_state.cpp index ed83d63..fdfb41a 100644 --- a/src/animation/blend_state.cpp +++ b/src/animation/blend_state.cpp
@@ -3,16 +3,13 @@ using namespace rive; -BlendState::~BlendState() -{ - for (auto anim : m_Animations) - { +BlendState::~BlendState() { + for (auto anim : m_Animations) { delete anim; } } -void BlendState::addAnimation(BlendAnimation* animation) -{ +void BlendState::addAnimation(BlendAnimation* animation) { // Assert it's not already contained. assert(std::find(m_Animations.begin(), m_Animations.end(), animation) == m_Animations.end());
diff --git a/src/animation/blend_state_1d.cpp b/src/animation/blend_state_1d.cpp index 1b1a98c..d8506cd 100644 --- a/src/animation/blend_state_1d.cpp +++ b/src/animation/blend_state_1d.cpp
@@ -6,32 +6,26 @@ using namespace rive; -StateInstance* BlendState1D::makeInstance() const -{ +StateInstance* BlendState1D::makeInstance() const { return new BlendState1DInstance(this); } -StatusCode BlendState1D::import(ImportStack& importStack) -{ +StatusCode BlendState1D::import(ImportStack& importStack) { auto stateMachineImporter = importStack.latest<StateMachineImporter>(StateMachine::typeKey); - if (stateMachineImporter == nullptr) - { + if (stateMachineImporter == nullptr) { return StatusCode::MissingObject; } // A negative inputId means it wasn't set, we actually allow this as the // editor does too. - if (inputId() >= 0) - { + if (inputId() >= 0) { // Make sure the inputId doesn't overflow the input buffer. - if (inputId() >= stateMachineImporter->stateMachine()->inputCount()) - { + if (inputId() >= stateMachineImporter->stateMachine()->inputCount()) { return StatusCode::InvalidObject; } auto input = stateMachineImporter->stateMachine()->input((size_t)inputId()); - if (input == nullptr || !input->is<StateMachineNumber>()) - { + if (input == nullptr || !input->is<StateMachineNumber>()) { return StatusCode::InvalidObject; } }
diff --git a/src/animation/blend_state_1d_instance.cpp b/src/animation/blend_state_1d_instance.cpp index cd07f6a..a186f50 100644 --- a/src/animation/blend_state_1d_instance.cpp +++ b/src/animation/blend_state_1d_instance.cpp
@@ -4,32 +4,23 @@ using namespace rive; BlendState1DInstance::BlendState1DInstance(const BlendState1D* blendState) : - BlendStateInstance<BlendState1D, BlendAnimation1D>(blendState) -{ -} + BlendStateInstance<BlendState1D, BlendAnimation1D>(blendState) {} -int BlendState1DInstance::animationIndex(float value) -{ +int BlendState1DInstance::animationIndex(float value) { int idx = 0; int mid = 0; float closestValue = 0; int start = 0; int end = static_cast<int>(m_AnimationInstances.size()) - 1; - while (start <= end) - { + while (start <= end) { mid = (start + end) >> 1; closestValue = m_AnimationInstances[mid].blendAnimation()->value(); - if (closestValue < value) - { + if (closestValue < value) { start = mid + 1; - } - else if (closestValue > value) - { + } else if (closestValue > value) { end = mid - 1; - } - else - { + } else { idx = start = mid; break; } @@ -39,15 +30,13 @@ return idx; } -void BlendState1DInstance::advance(float seconds, SMIInput** inputs) -{ +void BlendState1DInstance::advance(float seconds, SMIInput** inputs) { BlendStateInstance<BlendState1D, BlendAnimation1D>::advance(seconds, inputs); auto id = state()->as<BlendState1D>()->inputId(); float value = 0.0f; - if (id >= 0) - { + if (id >= 0) { auto inputInstance = inputs[state()->as<BlendState1D>()->inputId()]; auto numberInput = reinterpret_cast<const SMINumber*>(inputInstance); value = numberInput->value(); @@ -65,29 +54,20 @@ auto fromValue = m_From == nullptr ? 0.0f : m_From->blendAnimation()->value(); - if (m_To == nullptr || m_From == nullptr || toValue == fromValue) - { + if (m_To == nullptr || m_From == nullptr || toValue == fromValue) { mix = mixFrom = 1.0f; - } - else - { + } else { mix = (value - fromValue) / (toValue - fromValue); mixFrom = 1.0f - mix; } - for (auto& animation : m_AnimationInstances) - { + for (auto& animation : m_AnimationInstances) { auto animationValue = animation.blendAnimation()->value(); - if (m_To != nullptr && animationValue == toValue) - { + if (m_To != nullptr && animationValue == toValue) { animation.mix(mix); - } - else if (m_From != nullptr && animationValue == fromValue) - { + } else if (m_From != nullptr && animationValue == fromValue) { animation.mix(mixFrom); - } - else - { + } else { animation.mix(0.0f); } }
diff --git a/src/animation/blend_state_direct.cpp b/src/animation/blend_state_direct.cpp index 480fbd7..3dd5deb 100644 --- a/src/animation/blend_state_direct.cpp +++ b/src/animation/blend_state_direct.cpp
@@ -6,7 +6,6 @@ using namespace rive; -StateInstance* BlendStateDirect::makeInstance() const -{ +StateInstance* BlendStateDirect::makeInstance() const { return new BlendStateDirectInstance(this); } \ No newline at end of file
diff --git a/src/animation/blend_state_direct_instance.cpp b/src/animation/blend_state_direct_instance.cpp index aeefae1..a969825 100644 --- a/src/animation/blend_state_direct_instance.cpp +++ b/src/animation/blend_state_direct_instance.cpp
@@ -5,16 +5,12 @@ BlendStateDirectInstance::BlendStateDirectInstance( const BlendStateDirect* blendState) : - BlendStateInstance<BlendStateDirect, BlendAnimationDirect>(blendState) -{ -} + BlendStateInstance<BlendStateDirect, BlendAnimationDirect>(blendState) {} -void BlendStateDirectInstance::advance(float seconds, SMIInput** inputs) -{ +void BlendStateDirectInstance::advance(float seconds, SMIInput** inputs) { BlendStateInstance<BlendStateDirect, BlendAnimationDirect>::advance(seconds, inputs); - for (auto& animation : m_AnimationInstances) - { + for (auto& animation : m_AnimationInstances) { auto inputInstance = inputs[animation.blendAnimation()->inputId()]; auto numberInput = reinterpret_cast<const SMINumber*>(inputInstance);
diff --git a/src/animation/blend_state_transition.cpp b/src/animation/blend_state_transition.cpp index 3e3565b..28c2b61 100644 --- a/src/animation/blend_state_transition.cpp +++ b/src/animation/blend_state_transition.cpp
@@ -8,13 +8,10 @@ using namespace rive; -const LinearAnimationInstance* -BlendStateTransition::exitTimeAnimationInstance(const StateInstance* from) const -{ - if (from != nullptr) - { - switch (from->state()->coreType()) - { +const LinearAnimationInstance* BlendStateTransition::exitTimeAnimationInstance( + const StateInstance* from) const { + if (from != nullptr) { + switch (from->state()->coreType()) { case BlendState1D::typeKey: return static_cast<const BlendState1DInstance*>(from) @@ -31,10 +28,8 @@ } const LinearAnimation* -BlendStateTransition::exitTimeAnimation(const LayerState* from) const -{ - if (m_ExitBlendAnimation != nullptr) - { +BlendStateTransition::exitTimeAnimation(const LayerState* from) const { + if (m_ExitBlendAnimation != nullptr) { return m_ExitBlendAnimation->animation(); } return nullptr;
diff --git a/src/animation/cubic_interpolator.cpp b/src/animation/cubic_interpolator.cpp index d06b65f..215ccdd 100644 --- a/src/animation/cubic_interpolator.cpp +++ b/src/animation/cubic_interpolator.cpp
@@ -12,8 +12,7 @@ const int SubdivisionMaxIterations = 10; // Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2. -static float calcBezier(float aT, float aA1, float aA2) -{ +static float calcBezier(float aT, float aA1, float aA2) { return (((1.0f - 3.0f * aA2 + 3.0f * aA1) * aT + (3.0f * aA2 - 6.0f * aA1)) * aT + @@ -22,23 +21,19 @@ } // Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2. -static float getSlope(float aT, float aA1, float aA2) -{ +static float getSlope(float aT, float aA1, float aA2) { return 3.0f * (1.0f - 3.0f * aA2 + 3.0f * aA1) * aT * aT + 2.0f * (3.0f * aA2 - 6.0f * aA1) * aT + (3.0f * aA1); } -StatusCode CubicInterpolator::onAddedDirty(CoreContext* context) -{ - for (int i = 0; i < SplineTableSize; ++i) - { +StatusCode CubicInterpolator::onAddedDirty(CoreContext* context) { + for (int i = 0; i < SplineTableSize; ++i) { m_Values[i] = calcBezier(i * SampleStepSize, x1(), x2()); } return StatusCode::Ok; } -float CubicInterpolator::getT(float x) const -{ +float CubicInterpolator::getT(float x) const { float intervalStart = 0.0f; int currentSample = 1; int lastSample = SplineTableSize - 1; @@ -58,39 +53,28 @@ float _x1 = x1(), _x2 = x2(); float initialSlope = getSlope(guessForT, _x1, _x2); - if (initialSlope >= NewtonMinSlope) - { - for (int i = 0; i < NewtonIterations; ++i) - { + if (initialSlope >= NewtonMinSlope) { + for (int i = 0; i < NewtonIterations; ++i) { float currentSlope = getSlope(guessForT, _x1, _x2); - if (currentSlope == 0.0f) - { + if (currentSlope == 0.0f) { return guessForT; } float currentX = calcBezier(guessForT, _x1, _x2) - x; guessForT -= currentX / currentSlope; } return guessForT; - } - else if (initialSlope == 0.0f) - { + } else if (initialSlope == 0.0f) { return guessForT; - } - else - { + } else { float aB = intervalStart + SampleStepSize; float currentX, currentT; int i = 0; - do - { + do { currentT = intervalStart + (aB - intervalStart) / 2.0f; currentX = calcBezier(currentT, _x1, _x2) - x; - if (currentX > 0.0f) - { + if (currentX > 0.0f) { aB = currentT; - } - else - { + } else { intervalStart = currentT; } } while (std::abs(currentX) > SubdivisionPrecision && @@ -99,17 +83,14 @@ } } -float CubicInterpolator::transform(float mix) const -{ +float CubicInterpolator::transform(float mix) const { return calcBezier(getT(mix), y1(), y2()); } -StatusCode CubicInterpolator::import(ImportStack& importStack) -{ +StatusCode CubicInterpolator::import(ImportStack& importStack) { auto artboardImporter = importStack.latest<ArtboardImporter>(ArtboardBase::typeKey); - if (artboardImporter == nullptr) - { + if (artboardImporter == nullptr) { return StatusCode::MissingObject; } artboardImporter->addComponent(this);
diff --git a/src/animation/keyed_object.cpp b/src/animation/keyed_object.cpp index 11eb99d..bb0943b 100644 --- a/src/animation/keyed_object.cpp +++ b/src/animation/keyed_object.cpp
@@ -6,65 +6,51 @@ using namespace rive; -KeyedObject::~KeyedObject() -{ - for (auto property : m_KeyedProperties) - { +KeyedObject::~KeyedObject() { + for (auto property : m_KeyedProperties) { delete property; } } -void KeyedObject::addKeyedProperty(KeyedProperty* property) -{ +void KeyedObject::addKeyedProperty(KeyedProperty* property) { m_KeyedProperties.push_back(property); } -StatusCode KeyedObject::onAddedDirty(CoreContext* context) -{ +StatusCode KeyedObject::onAddedDirty(CoreContext* context) { // Make sure we're keying a valid object. - if (context->resolve(objectId()) == nullptr) - { + if (context->resolve(objectId()) == nullptr) { return StatusCode::MissingObject; } - for (auto property : m_KeyedProperties) - { + for (auto property : m_KeyedProperties) { StatusCode code; - if ((code = property->onAddedDirty(context)) != StatusCode::Ok) - { + if ((code = property->onAddedDirty(context)) != StatusCode::Ok) { return code; } } return StatusCode::Ok; } -StatusCode KeyedObject::onAddedClean(CoreContext* context) -{ - for (auto property : m_KeyedProperties) - { +StatusCode KeyedObject::onAddedClean(CoreContext* context) { + for (auto property : m_KeyedProperties) { property->onAddedClean(context); } return StatusCode::Ok; } -void KeyedObject::apply(Artboard* artboard, float time, float mix) -{ +void KeyedObject::apply(Artboard* artboard, float time, float mix) { Core* object = artboard->resolve(objectId()); - if (object == nullptr) - { + if (object == nullptr) { return; } - for (auto property : m_KeyedProperties) - { + for (auto property : m_KeyedProperties) { property->apply(object, time, mix); } } -StatusCode KeyedObject::import(ImportStack& importStack) -{ +StatusCode KeyedObject::import(ImportStack& importStack) { auto importer = importStack.latest<LinearAnimationImporter>( LinearAnimationBase::typeKey); - if (importer == nullptr) - { + if (importer == nullptr) { return StatusCode::MissingObject; } importer->addKeyedObject(this);
diff --git a/src/animation/keyed_property.cpp b/src/animation/keyed_property.cpp index f7a6e20..46db944 100644 --- a/src/animation/keyed_property.cpp +++ b/src/animation/keyed_property.cpp
@@ -6,21 +6,17 @@ using namespace rive; -KeyedProperty::~KeyedProperty() -{ - for (auto keyframe : m_KeyFrames) - { +KeyedProperty::~KeyedProperty() { + for (auto keyframe : m_KeyFrames) { delete keyframe; } } -void KeyedProperty::addKeyFrame(KeyFrame* keyframe) -{ +void KeyedProperty::addKeyFrame(KeyFrame* keyframe) { m_KeyFrames.push_back(keyframe); } -void KeyedProperty::apply(Core* object, float seconds, float mix) -{ +void KeyedProperty::apply(Core* object, float seconds, float mix) { assert(!m_KeyFrames.empty()); int idx = 0; @@ -29,20 +25,14 @@ int start = 0; auto numKeyFrames = static_cast<int>(m_KeyFrames.size()); int end = numKeyFrames - 1; - while (start <= end) - { + while (start <= end) { mid = (start + end) >> 1; closestSeconds = m_KeyFrames[mid]->seconds(); - if (closestSeconds < seconds) - { + if (closestSeconds < seconds) { start = mid + 1; - } - else if (closestSeconds > seconds) - { + } else if (closestSeconds > seconds) { end = mid - 1; - } - else - { + } else { idx = start = mid; break; } @@ -50,72 +40,52 @@ } int pk = propertyKey(); - if (idx == 0) - { + if (idx == 0) { m_KeyFrames[0]->apply(object, pk, mix); - } - else - { - if (idx < numKeyFrames) - { + } else { + if (idx < numKeyFrames) { KeyFrame* fromFrame = m_KeyFrames[idx - 1]; KeyFrame* toFrame = m_KeyFrames[idx]; - if (seconds == toFrame->seconds()) - { + if (seconds == toFrame->seconds()) { toFrame->apply(object, pk, mix); - } - else - { - if (fromFrame->interpolationType() == 0) - { + } else { + if (fromFrame->interpolationType() == 0) { fromFrame->apply(object, pk, mix); - } - else - { + } else { fromFrame->applyInterpolation( object, pk, seconds, toFrame, mix); } } - } - else - { + } else { m_KeyFrames[idx - 1]->apply(object, pk, mix); } } } -StatusCode KeyedProperty::onAddedDirty(CoreContext* context) -{ +StatusCode KeyedProperty::onAddedDirty(CoreContext* context) { StatusCode code; - for (auto keyframe : m_KeyFrames) - { - if ((code = keyframe->onAddedDirty(context)) != StatusCode::Ok) - { + for (auto keyframe : m_KeyFrames) { + if ((code = keyframe->onAddedDirty(context)) != StatusCode::Ok) { return code; } } return StatusCode::Ok; } -StatusCode KeyedProperty::onAddedClean(CoreContext* context) -{ +StatusCode KeyedProperty::onAddedClean(CoreContext* context) { StatusCode code; - for (auto keyframe : m_KeyFrames) - { - if ((code = keyframe->onAddedClean(context)) != StatusCode::Ok) - { + for (auto keyframe : m_KeyFrames) { + if ((code = keyframe->onAddedClean(context)) != StatusCode::Ok) { return code; } } return StatusCode::Ok; } -StatusCode KeyedProperty::import(ImportStack& importStack) -{ +StatusCode KeyedProperty::import(ImportStack& importStack) { auto importer = importStack.latest<KeyedObjectImporter>(KeyedObjectBase::typeKey); - if (importer == nullptr) - { + if (importer == nullptr) { return StatusCode::MissingObject; } importer->addKeyedProperty(this);
diff --git a/src/animation/keyframe.cpp b/src/animation/keyframe.cpp index 657d56f..37ad9fe 100644 --- a/src/animation/keyframe.cpp +++ b/src/animation/keyframe.cpp
@@ -7,13 +7,10 @@ using namespace rive; -StatusCode KeyFrame::onAddedDirty(CoreContext* context) -{ - if (interpolatorId() > 0) - { +StatusCode KeyFrame::onAddedDirty(CoreContext* context) { + if (interpolatorId() > 0) { auto coreObject = context->resolve(interpolatorId()); - if (coreObject == nullptr || !coreObject->is<CubicInterpolator>()) - { + if (coreObject == nullptr || !coreObject->is<CubicInterpolator>()) { return StatusCode::MissingObject; } m_Interpolator = coreObject->as<CubicInterpolator>(); @@ -24,12 +21,10 @@ void KeyFrame::computeSeconds(int fps) { m_Seconds = frame() / (float)fps; } -StatusCode KeyFrame::import(ImportStack& importStack) -{ +StatusCode KeyFrame::import(ImportStack& importStack) { auto importer = importStack.latest<KeyedPropertyImporter>(KeyedProperty::typeKey); - if (importer == nullptr) - { + if (importer == nullptr) { return StatusCode::MissingObject; } importer->addKeyFrame(this);
diff --git a/src/animation/keyframe_bool.cpp b/src/animation/keyframe_bool.cpp index 401a655..a7eba61 100644 --- a/src/animation/keyframe_bool.cpp +++ b/src/animation/keyframe_bool.cpp
@@ -3,8 +3,7 @@ using namespace rive; -void KeyFrameBool::apply(Core* object, int propertyKey, float mix) -{ +void KeyFrameBool::apply(Core* object, int propertyKey, float mix) { CoreRegistry::setBool(object, propertyKey, value()); } @@ -12,7 +11,6 @@ int propertyKey, float currentTime, const KeyFrame* nextFrame, - float mix) -{ + float mix) { CoreRegistry::setBool(object, propertyKey, value()); } \ No newline at end of file
diff --git a/src/animation/keyframe_color.cpp b/src/animation/keyframe_color.cpp index 5210f32..3accfcd 100644 --- a/src/animation/keyframe_color.cpp +++ b/src/animation/keyframe_color.cpp
@@ -4,22 +4,17 @@ using namespace rive; -static void applyColor(Core* object, int propertyKey, float mix, int value) -{ - if (mix == 1.0f) - { +static void applyColor(Core* object, int propertyKey, float mix, int value) { + if (mix == 1.0f) { CoreRegistry::setColor(object, propertyKey, value); - } - else - { + } else { auto mixedColor = colorLerp(CoreRegistry::getColor(object, propertyKey), value, mix); CoreRegistry::setColor(object, propertyKey, mixedColor); } } -void KeyFrameColor::apply(Core* object, int propertyKey, float mix) -{ +void KeyFrameColor::apply(Core* object, int propertyKey, float mix) { applyColor(object, propertyKey, mix, value()); } @@ -27,14 +22,12 @@ int propertyKey, float currentTime, const KeyFrame* nextFrame, - float mix) -{ + float mix) { auto kfc = nextFrame->as<KeyFrameColor>(); const KeyFrameColor& nextColor = *kfc; float f = (currentTime - seconds()) / (nextColor.seconds() - seconds()); - if (CubicInterpolator* cubic = interpolator()) - { + if (CubicInterpolator* cubic = interpolator()) { f = cubic->transform(f); }
diff --git a/src/animation/keyframe_double.cpp b/src/animation/keyframe_double.cpp index d6895f8..bb4776f 100644 --- a/src/animation/keyframe_double.cpp +++ b/src/animation/keyframe_double.cpp
@@ -8,14 +8,10 @@ // floating point numbers suffice. So even though this is a "double keyframe" to // match editor names, the actual values are stored and applied in 32 bits. -static void applyDouble(Core* object, int propertyKey, float mix, float value) -{ - if (mix == 1.0f) - { +static void applyDouble(Core* object, int propertyKey, float mix, float value) { + if (mix == 1.0f) { CoreRegistry::setDouble(object, propertyKey, value); - } - else - { + } else { float mixi = 1.0 - mix; CoreRegistry::setDouble( object, @@ -24,8 +20,7 @@ } } -void KeyFrameDouble::apply(Core* object, int propertyKey, float mix) -{ +void KeyFrameDouble::apply(Core* object, int propertyKey, float mix) { applyDouble(object, propertyKey, mix, value()); } @@ -33,14 +28,12 @@ int propertyKey, float currentTime, const KeyFrame* nextFrame, - float mix) -{ + float mix) { auto kfd = nextFrame->as<KeyFrameDouble>(); const KeyFrameDouble& nextDouble = *kfd; float f = (currentTime - seconds()) / (nextDouble.seconds() - seconds()); - if (CubicInterpolator* cubic = interpolator()) - { + if (CubicInterpolator* cubic = interpolator()) { f = cubic->transform(f); }
diff --git a/src/animation/keyframe_id.cpp b/src/animation/keyframe_id.cpp index dfa8fcc..00be39a 100644 --- a/src/animation/keyframe_id.cpp +++ b/src/animation/keyframe_id.cpp
@@ -3,8 +3,7 @@ using namespace rive; -void KeyFrameId::apply(Core* object, int propertyKey, float mix) -{ +void KeyFrameId::apply(Core* object, int propertyKey, float mix) { CoreRegistry::setUint(object, propertyKey, value()); } @@ -12,7 +11,6 @@ int propertyKey, float currentTime, const KeyFrame* nextFrame, - float mix) -{ + float mix) { CoreRegistry::setUint(object, propertyKey, value()); } \ No newline at end of file
diff --git a/src/animation/layer_state.cpp b/src/animation/layer_state.cpp index 572f53b..20c3679 100644 --- a/src/animation/layer_state.cpp +++ b/src/animation/layer_state.cpp
@@ -8,58 +8,46 @@ using namespace rive; -LayerState::~LayerState() -{ - for (auto transition : m_Transitions) - { +LayerState::~LayerState() { + for (auto transition : m_Transitions) { delete transition; } } -StatusCode LayerState::onAddedDirty(CoreContext* context) -{ +StatusCode LayerState::onAddedDirty(CoreContext* context) { StatusCode code; - for (auto transition : m_Transitions) - { - if ((code = transition->onAddedDirty(context)) != StatusCode::Ok) - { + for (auto transition : m_Transitions) { + if ((code = transition->onAddedDirty(context)) != StatusCode::Ok) { return code; } } return StatusCode::Ok; } -StatusCode LayerState::onAddedClean(CoreContext* context) -{ +StatusCode LayerState::onAddedClean(CoreContext* context) { StatusCode code; - for (auto transition : m_Transitions) - { - if ((code = transition->onAddedClean(context)) != StatusCode::Ok) - { + for (auto transition : m_Transitions) { + if ((code = transition->onAddedClean(context)) != StatusCode::Ok) { return code; } } return StatusCode::Ok; } -StatusCode LayerState::import(ImportStack& importStack) -{ +StatusCode LayerState::import(ImportStack& importStack) { auto layerImporter = importStack.latest<StateMachineLayerImporter>( StateMachineLayerBase::typeKey); - if (layerImporter == nullptr) - { + if (layerImporter == nullptr) { return StatusCode::MissingObject; } layerImporter->addState(this); return Super::import(importStack); } -void LayerState::addTransition(StateTransition* transition) -{ +void LayerState::addTransition(StateTransition* transition) { m_Transitions.push_back(transition); } -StateInstance* LayerState::makeInstance() const -{ +StateInstance* LayerState::makeInstance() const { return new SystemStateInstance(this); } \ No newline at end of file
diff --git a/src/animation/linear_animation.cpp b/src/animation/linear_animation.cpp index 9e7f7f6..c7a8e46 100644 --- a/src/animation/linear_animation.cpp +++ b/src/animation/linear_animation.cpp
@@ -10,77 +10,61 @@ int LinearAnimation::deleteCount = 0; #endif -LinearAnimation::~LinearAnimation() -{ +LinearAnimation::~LinearAnimation() { #ifdef TESTING deleteCount++; #endif - for (auto object : m_KeyedObjects) - { + for (auto object : m_KeyedObjects) { delete object; } } -StatusCode LinearAnimation::onAddedDirty(CoreContext* context) -{ +StatusCode LinearAnimation::onAddedDirty(CoreContext* context) { StatusCode code; - for (auto object : m_KeyedObjects) - { - if ((code = object->onAddedDirty(context)) != StatusCode::Ok) - { + for (auto object : m_KeyedObjects) { + if ((code = object->onAddedDirty(context)) != StatusCode::Ok) { return code; } } return StatusCode::Ok; } -StatusCode LinearAnimation::onAddedClean(CoreContext* context) -{ +StatusCode LinearAnimation::onAddedClean(CoreContext* context) { StatusCode code; - for (auto object : m_KeyedObjects) - { - if ((code = object->onAddedClean(context)) != StatusCode::Ok) - { + for (auto object : m_KeyedObjects) { + if ((code = object->onAddedClean(context)) != StatusCode::Ok) { return code; } } return StatusCode::Ok; } -void LinearAnimation::addKeyedObject(KeyedObject* object) -{ +void LinearAnimation::addKeyedObject(KeyedObject* object) { m_KeyedObjects.push_back(object); } -void LinearAnimation::apply(Artboard* artboard, float time, float mix) const -{ - for (auto object : m_KeyedObjects) - { +void LinearAnimation::apply(Artboard* artboard, float time, float mix) const { + for (auto object : m_KeyedObjects) { object->apply(artboard, time, mix); } } -StatusCode LinearAnimation::import(ImportStack& importStack) -{ +StatusCode LinearAnimation::import(ImportStack& importStack) { auto artboardImporter = importStack.latest<ArtboardImporter>(ArtboardBase::typeKey); - if (artboardImporter == nullptr) - { + if (artboardImporter == nullptr) { return StatusCode::MissingObject; } artboardImporter->addAnimation(this); return Super::import(importStack); } -float LinearAnimation::startSeconds() const -{ +float LinearAnimation::startSeconds() const { return (enableWorkArea() ? workStart() : 0) / (float)fps(); } -float LinearAnimation::endSeconds() const -{ +float LinearAnimation::endSeconds() const { return (enableWorkArea() ? workEnd() : duration()) / (float)fps(); } -float LinearAnimation::durationSeconds() const -{ +float LinearAnimation::durationSeconds() const { return endSeconds() - startSeconds(); } \ No newline at end of file
diff --git a/src/animation/linear_animation_instance.cpp b/src/animation/linear_animation_instance.cpp index 40f82f5..b9a27eb 100644 --- a/src/animation/linear_animation_instance.cpp +++ b/src/animation/linear_animation_instance.cpp
@@ -14,12 +14,9 @@ m_TotalTime(0.0f), m_LastTotalTime(0.0f), m_SpilledTime(0.0f), - m_Direction(1) -{ -} + m_Direction(1) {} -bool LinearAnimationInstance::advance(float elapsedSeconds) -{ +bool LinearAnimationInstance::advance(float elapsedSeconds) { const LinearAnimation& animation = *m_Animation; m_Time += elapsedSeconds * animation.speed() * m_Direction; m_LastTotalTime = m_TotalTime; @@ -38,19 +35,15 @@ bool didLoop = false; m_SpilledTime = 0.0f; - switch (loop()) - { + switch (loop()) { case Loop::oneShot: - if (m_Direction == 1 && frames > end) - { + if (m_Direction == 1 && frames > end) { keepGoing = false; m_SpilledTime = (frames - end) / fps; frames = end; m_Time = frames / fps; didLoop = true; - } - else if (m_Direction == -1 && frames < start) - { + } else if (m_Direction == -1 && frames < start) { keepGoing = false; m_SpilledTime = (start - frames) / fps; frames = start; @@ -59,17 +52,14 @@ } break; case Loop::loop: - if (m_Direction == 1 && frames >= end) - { + if (m_Direction == 1 && frames >= end) { m_SpilledTime = (frames - end) / fps; frames = m_Time * fps; frames = start + std::fmod(frames - start, range); m_Time = frames / fps; didLoop = true; - } - else if (m_Direction == -1 && frames <= start) - { + } else if (m_Direction == -1 && frames <= start) { m_SpilledTime = (start - frames) / fps; frames = m_Time * fps; @@ -79,26 +69,20 @@ } break; case Loop::pingPong: - while (true) - { - if (m_Direction == 1 && frames >= end) - { + while (true) { + if (m_Direction == 1 && frames >= end) { m_SpilledTime = (frames - end) / fps; m_Direction = -1; frames = end + (end - frames); m_Time = frames / fps; didLoop = true; - } - else if (m_Direction == -1 && frames < start) - { + } else if (m_Direction == -1 && frames < start) { m_SpilledTime = (start - frames) / fps; m_Direction = 1; frames = start + (start - frames); m_Time = frames / fps; didLoop = true; - } - else - { + } else { // we're within the range, we can stop fixing. We do this in // a loop to fix conditions when time has advanced so far // that we've ping-ponged back and forth a few times in a @@ -114,10 +98,8 @@ return keepGoing; } -void LinearAnimationInstance::time(float value) -{ - if (m_Time == value) - { +void LinearAnimationInstance::time(float value) { + if (m_Time == value) { return; } m_Time = value; @@ -136,30 +118,24 @@ } // Returns either the animation's default or overridden loop values -int LinearAnimationInstance::loopValue() -{ - if (m_LoopValue != -1) - { +int LinearAnimationInstance::loopValue() { + if (m_LoopValue != -1) { return m_LoopValue; } return m_Animation->loopValue(); } // Override the animation's loop value -void LinearAnimationInstance::loopValue(int value) -{ - if (m_LoopValue == value) - { +void LinearAnimationInstance::loopValue(int value) { + if (m_LoopValue == value) { return; } - if (m_LoopValue == -1 && m_Animation->loopValue() == value) - { + if (m_LoopValue == -1 && m_Animation->loopValue() == value) { return; } m_LoopValue = value; } -float LinearAnimationInstance::durationSeconds() const -{ +float LinearAnimationInstance::durationSeconds() const { return m_Animation->durationSeconds(); } \ No newline at end of file
diff --git a/src/animation/nested_animation.cpp b/src/animation/nested_animation.cpp index 7916e88..b1a26f0 100644 --- a/src/animation/nested_animation.cpp +++ b/src/animation/nested_animation.cpp
@@ -4,13 +4,10 @@ using namespace rive; -StatusCode NestedAnimation::onAddedDirty(CoreContext* context) -{ +StatusCode NestedAnimation::onAddedDirty(CoreContext* context) { StatusCode code = Super::onAddedDirty(context); - if (code == StatusCode::Ok) - { - if (!parent()->is<NestedArtboard>()) - { + if (code == StatusCode::Ok) { + if (!parent()->is<NestedArtboard>()) { return StatusCode::InvalidObject; } auto nestedArtboard = parent()->as<NestedArtboard>();
diff --git a/src/animation/nested_linear_animation.cpp b/src/animation/nested_linear_animation.cpp index 87985c1..631194b 100644 --- a/src/animation/nested_linear_animation.cpp +++ b/src/animation/nested_linear_animation.cpp
@@ -5,8 +5,7 @@ NestedLinearAnimation::~NestedLinearAnimation() { delete m_AnimationInstance; } -void NestedLinearAnimation::initializeAnimation(Artboard* artboard) -{ +void NestedLinearAnimation::initializeAnimation(Artboard* artboard) { assert(m_AnimationInstance == nullptr); m_AnimationInstance = new LinearAnimationInstance(artboard->animation(animationId()));
diff --git a/src/animation/nested_remap_animation.cpp b/src/animation/nested_remap_animation.cpp index a4652b1..ba76daa 100644 --- a/src/animation/nested_remap_animation.cpp +++ b/src/animation/nested_remap_animation.cpp
@@ -3,25 +3,20 @@ using namespace rive; -void NestedRemapAnimation::timeChanged() -{ - if (m_AnimationInstance != nullptr) - { +void NestedRemapAnimation::timeChanged() { + if (m_AnimationInstance != nullptr) { m_AnimationInstance->time(m_AnimationInstance->durationSeconds() * time()); } } -void NestedRemapAnimation::initializeAnimation(Artboard* artboard) -{ +void NestedRemapAnimation::initializeAnimation(Artboard* artboard) { Super::initializeAnimation(artboard); timeChanged(); } -void NestedRemapAnimation::advance(float elapsedSeconds, Artboard* artboard) -{ - if (m_AnimationInstance != nullptr) - { +void NestedRemapAnimation::advance(float elapsedSeconds, Artboard* artboard) { + if (m_AnimationInstance != nullptr) { m_AnimationInstance->apply(artboard, mix()); } } \ No newline at end of file
diff --git a/src/animation/nested_simple_animation.cpp b/src/animation/nested_simple_animation.cpp index 0d9ec94..5f595f7 100644 --- a/src/animation/nested_simple_animation.cpp +++ b/src/animation/nested_simple_animation.cpp
@@ -3,12 +3,9 @@ using namespace rive; -void NestedSimpleAnimation::advance(float elapsedSeconds, Artboard* artboard) -{ - if (m_AnimationInstance != nullptr) - { - if (isPlaying()) - { +void NestedSimpleAnimation::advance(float elapsedSeconds, Artboard* artboard) { + if (m_AnimationInstance != nullptr) { + if (isPlaying()) { m_AnimationInstance->advance(elapsedSeconds * speed()); } m_AnimationInstance->apply(artboard, mix());
diff --git a/src/animation/state_instance.cpp b/src/animation/state_instance.cpp index b39b08d..d27cef7 100644 --- a/src/animation/state_instance.cpp +++ b/src/animation/state_instance.cpp
@@ -2,9 +2,7 @@ using namespace rive; StateInstance::StateInstance(const LayerState* layerState) : - m_LayerState(layerState) -{ -} + m_LayerState(layerState) {} StateInstance::~StateInstance() {}
diff --git a/src/animation/state_machine.cpp b/src/animation/state_machine.cpp index 0e81f94..885000d 100644 --- a/src/animation/state_machine.cpp +++ b/src/animation/state_machine.cpp
@@ -6,117 +6,90 @@ using namespace rive; -StateMachine::~StateMachine() -{ - for (auto object : m_Inputs) - { +StateMachine::~StateMachine() { + for (auto object : m_Inputs) { delete object; } - for (auto object : m_Layers) - { + for (auto object : m_Layers) { delete object; } } -StatusCode StateMachine::onAddedDirty(CoreContext* context) -{ +StatusCode StateMachine::onAddedDirty(CoreContext* context) { StatusCode code; - for (auto object : m_Inputs) - { - if ((code = object->onAddedDirty(context)) != StatusCode::Ok) - { + for (auto object : m_Inputs) { + if ((code = object->onAddedDirty(context)) != StatusCode::Ok) { return code; } } - for (auto object : m_Layers) - { - if ((code = object->onAddedDirty(context)) != StatusCode::Ok) - { + for (auto object : m_Layers) { + if ((code = object->onAddedDirty(context)) != StatusCode::Ok) { return code; } } return StatusCode::Ok; } -StatusCode StateMachine::onAddedClean(CoreContext* context) -{ +StatusCode StateMachine::onAddedClean(CoreContext* context) { StatusCode code; - for (auto object : m_Inputs) - { - if ((code = object->onAddedClean(context)) != StatusCode::Ok) - { + for (auto object : m_Inputs) { + if ((code = object->onAddedClean(context)) != StatusCode::Ok) { return code; } } - for (auto object : m_Layers) - { - if ((code = object->onAddedClean(context)) != StatusCode::Ok) - { + for (auto object : m_Layers) { + if ((code = object->onAddedClean(context)) != StatusCode::Ok) { return code; } } return StatusCode::Ok; } -StatusCode StateMachine::import(ImportStack& importStack) -{ +StatusCode StateMachine::import(ImportStack& importStack) { auto artboardImporter = importStack.latest<ArtboardImporter>(ArtboardBase::typeKey); - if (artboardImporter == nullptr) - { + if (artboardImporter == nullptr) { return StatusCode::MissingObject; } artboardImporter->addStateMachine(this); return Super::import(importStack); } -void StateMachine::addLayer(StateMachineLayer* layer) -{ +void StateMachine::addLayer(StateMachineLayer* layer) { m_Layers.push_back(layer); } -void StateMachine::addInput(StateMachineInput* input) -{ +void StateMachine::addInput(StateMachineInput* input) { m_Inputs.push_back(input); } -const StateMachineInput* StateMachine::input(std::string name) const -{ - for (auto input : m_Inputs) - { - if (input->name() == name) - { +const StateMachineInput* StateMachine::input(std::string name) const { + for (auto input : m_Inputs) { + if (input->name() == name) { return input; } } return nullptr; } -const StateMachineInput* StateMachine::input(size_t index) const -{ - if (index >= 0 && index < m_Inputs.size()) - { +const StateMachineInput* StateMachine::input(size_t index) const { + if (index >= 0 && index < m_Inputs.size()) { return m_Inputs[index]; } return nullptr; } -const StateMachineLayer* StateMachine::layer(std::string name) const -{ - for (auto layer : m_Layers) - { - if (layer->name() == name) - { +const StateMachineLayer* StateMachine::layer(std::string name) const { + for (auto layer : m_Layers) { + if (layer->name() == name) { return layer; } } return nullptr; } -const StateMachineLayer* StateMachine::layer(size_t index) const -{ - if (index >= 0 && index < m_Layers.size()) - { +const StateMachineLayer* StateMachine::layer(size_t index) const { + if (index >= 0 && index < m_Layers.size()) { return m_Layers[index]; } return nullptr;
diff --git a/src/animation/state_machine_input.cpp b/src/animation/state_machine_input.cpp index e53fd84..bf22152 100644 --- a/src/animation/state_machine_input.cpp +++ b/src/animation/state_machine_input.cpp
@@ -5,22 +5,18 @@ using namespace rive; -StatusCode StateMachineInput::onAddedDirty(CoreContext* context) -{ +StatusCode StateMachineInput::onAddedDirty(CoreContext* context) { return StatusCode::Ok; } -StatusCode StateMachineInput::onAddedClean(CoreContext* context) -{ +StatusCode StateMachineInput::onAddedClean(CoreContext* context) { return StatusCode::Ok; } -StatusCode StateMachineInput::import(ImportStack& importStack) -{ +StatusCode StateMachineInput::import(ImportStack& importStack) { auto stateMachineImporter = importStack.latest<StateMachineImporter>(StateMachineBase::typeKey); - if (stateMachineImporter == nullptr) - { + if (stateMachineImporter == nullptr) { return StatusCode::MissingObject; } stateMachineImporter->addInput(this);
diff --git a/src/animation/state_machine_input_instance.cpp b/src/animation/state_machine_input_instance.cpp index eeb89fa..f3f99df 100644 --- a/src/animation/state_machine_input_instance.cpp +++ b/src/animation/state_machine_input_instance.cpp
@@ -8,9 +8,7 @@ SMIInput::SMIInput(const StateMachineInput* input, StateMachineInstance* machineInstance) : - m_MachineInstance(machineInstance), m_Input(input) -{ -} + m_MachineInstance(machineInstance), m_Input(input) {} uint16_t SMIInput::inputCoreType() const { return m_Input->coreType(); } @@ -22,14 +20,10 @@ SMIBool::SMIBool(const StateMachineBool* input, StateMachineInstance* machineInstance) : - SMIInput(input, machineInstance), m_Value(input->value()) -{ -} + SMIInput(input, machineInstance), m_Value(input->value()) {} -void SMIBool::value(bool newValue) -{ - if (m_Value == newValue) - { +void SMIBool::value(bool newValue) { + if (m_Value == newValue) { return; } m_Value = newValue; @@ -39,14 +33,10 @@ // number SMINumber::SMINumber(const StateMachineNumber* input, StateMachineInstance* machineInstance) : - SMIInput(input, machineInstance), m_Value(input->value()) -{ -} + SMIInput(input, machineInstance), m_Value(input->value()) {} -void SMINumber::value(float newValue) -{ - if (m_Value == newValue) - { +void SMINumber::value(float newValue) { + if (m_Value == newValue) { return; } m_Value = newValue; @@ -56,14 +46,10 @@ // trigger SMITrigger::SMITrigger(const StateMachineTrigger* input, StateMachineInstance* machineInstance) : - SMIInput(input, machineInstance) -{ -} + SMIInput(input, machineInstance) {} -void SMITrigger::fire() -{ - if (m_Fired) - { +void SMITrigger::fire() { + if (m_Fired) { return; } m_Fired = true;
diff --git a/src/animation/state_machine_instance.cpp b/src/animation/state_machine_instance.cpp index 0e62747..c285912 100644 --- a/src/animation/state_machine_instance.cpp +++ b/src/animation/state_machine_instance.cpp
@@ -15,10 +15,8 @@ #include "rive/animation/animation_state_instance.hpp" using namespace rive; -namespace rive -{ - class StateMachineLayerInstance - { +namespace rive { + class StateMachineLayerInstance { private: static const int maxIterations = 100; const StateMachineLayer* m_Layer = nullptr; @@ -44,23 +42,20 @@ float m_HoldTime = 0.0f; public: - ~StateMachineLayerInstance() - { + ~StateMachineLayerInstance() { delete m_AnyStateInstance; delete m_CurrentState; delete m_StateFrom; } - void init(const StateMachineLayer* layer) - { + void init(const StateMachineLayer* layer) { assert(m_Layer == nullptr); m_AnyStateInstance = layer->anyState()->makeInstance(); m_Layer = layer; changeState(m_Layer->entryState()); } - void updateMix(float seconds) - { + void updateMix(float seconds) { if (m_Transition != nullptr && m_StateFrom != nullptr && m_Transition->duration() != 0) { @@ -69,9 +64,7 @@ std::max(0.0f, (m_Mix + seconds / m_Transition->mixTime( m_StateFrom->state())))); - } - else - { + } else { m_Mix = 1.0f; } } @@ -79,12 +72,10 @@ bool advance(Artboard* artboard, float seconds, SMIInput** inputs, - size_t inputCount) - { + size_t inputCount) { m_StateChangedOnAdvance = false; - if (m_CurrentState != nullptr) - { + if (m_CurrentState != nullptr) { m_CurrentState->advance(seconds, inputs); } @@ -97,12 +88,10 @@ m_StateFrom->advance(seconds, inputs); } - for (int i = 0; updateState(inputs, i != 0); i++) - { + for (int i = 0; updateState(inputs, i != 0); i++) { apply(artboard); - if (i == maxIterations) - { + if (i == maxIterations) { fprintf(stderr, "StateMachine exceeded max iterations.\n"); return false; } @@ -114,37 +103,31 @@ (m_CurrentState != nullptr && m_CurrentState->keepGoing()); } - bool isTransitioning() - { + bool isTransitioning() { return m_Transition != nullptr && m_StateFrom != nullptr && m_Transition->duration() != 0 && m_Mix < 1.0f; } - bool updateState(SMIInput** inputs, bool ignoreTriggers) - { + bool updateState(SMIInput** inputs, bool ignoreTriggers) { // Don't allow changing state while a transition is taking place // (we're mixing one state onto another). - if (isTransitioning()) - { + if (isTransitioning()) { return false; } m_WaitingForExit = false; - if (tryChangeState(m_AnyStateInstance, inputs, ignoreTriggers)) - { + if (tryChangeState(m_AnyStateInstance, inputs, ignoreTriggers)) { return true; } return tryChangeState(m_CurrentState, inputs, ignoreTriggers); } - bool changeState(const LayerState* stateTo) - { + bool changeState(const LayerState* stateTo) { if ((m_CurrentState == nullptr ? nullptr - : m_CurrentState->state()) == stateTo) - { + : m_CurrentState->state()) == stateTo) { return false; } m_CurrentState = @@ -154,29 +137,24 @@ bool tryChangeState(StateInstance* stateFromInstance, SMIInput** inputs, - bool ignoreTriggers) - { - if (stateFromInstance == nullptr) - { + bool ignoreTriggers) { + if (stateFromInstance == nullptr) { return false; } auto stateFrom = stateFromInstance->state(); auto outState = m_CurrentState; for (size_t i = 0, length = stateFrom->transitionCount(); i < length; - i++) - { + i++) { auto transition = stateFrom->transition(i); auto allowed = transition->allowed( stateFromInstance, inputs, ignoreTriggers); if (allowed == AllowTransition::yes && - changeState(transition->stateTo())) - { + changeState(transition->stateTo())) { m_StateChangedOnAdvance = true; // state actually has changed m_Transition = transition; - if (m_StateFrom != m_AnyStateInstance) - { + if (m_StateFrom != m_AnyStateInstance) { // Old state from is done. delete m_StateFrom; } @@ -186,8 +164,7 @@ // sure to hold the exit time. Delegate this to the // transition by telling it that it was completed. if (outState != nullptr && - transition->applyExitCondition(outState)) - { + transition->applyExitCondition(outState)) { // Make sure we apply this state. This only returns true // when it's an animation state instance. auto instance = @@ -200,8 +177,7 @@ m_MixFrom = m_Mix; // Keep mixing last animation that was mixed in. - if (m_Mix != 0.0f) - { + if (m_Mix != 0.0f) { m_HoldAnimationFrom = transition->pauseOnExit(); } if (m_StateFrom != nullptr && @@ -219,46 +195,37 @@ updateMix(0.0f); m_WaitingForExit = false; return true; - } - else if (allowed == AllowTransition::waitingForExit) - { + } else if (allowed == AllowTransition::waitingForExit) { m_WaitingForExit = true; } } return false; } - void apply(Artboard* artboard) - { - if (m_HoldAnimation != nullptr) - { + void apply(Artboard* artboard) { + if (m_HoldAnimation != nullptr) { m_HoldAnimation->apply(artboard, m_HoldTime, m_MixFrom); m_HoldAnimation = nullptr; } - if (m_StateFrom != nullptr && m_Mix < 1.0f) - { + if (m_StateFrom != nullptr && m_Mix < 1.0f) { m_StateFrom->apply(artboard, m_MixFrom); } - if (m_CurrentState != nullptr) - { + if (m_CurrentState != nullptr) { m_CurrentState->apply(artboard, m_Mix); } } bool stateChangedOnAdvance() const { return m_StateChangedOnAdvance; } - const LayerState* currentState() - { + const LayerState* currentState() { return m_CurrentState == nullptr ? nullptr : m_CurrentState->state(); } - const LinearAnimationInstance* currentAnimation() const - { + const LinearAnimationInstance* currentAnimation() const { if (m_CurrentState == nullptr || - !m_CurrentState->state()->is<AnimationState>()) - { + !m_CurrentState->state()->is<AnimationState>()) { return nullptr; } return static_cast<AnimationStateInstance*>(m_CurrentState) @@ -268,20 +235,16 @@ } // namespace rive StateMachineInstance::StateMachineInstance(const StateMachine* machine) : - m_Machine(machine) -{ + m_Machine(machine) { m_InputCount = machine->inputCount(); m_InputInstances = new SMIInput*[m_InputCount]; - for (int i = 0; i < m_InputCount; i++) - { + for (int i = 0; i < m_InputCount; i++) { auto input = machine->input(i); - if (input == nullptr) - { + if (input == nullptr) { m_InputInstances[i] = nullptr; continue; } - switch (input->coreType()) - { + switch (input->coreType()) { case StateMachineBool::typeKey: m_InputInstances[i] = new SMIBool(input->as<StateMachineBool>(), this); @@ -303,36 +266,29 @@ m_LayerCount = machine->layerCount(); m_Layers = new StateMachineLayerInstance[m_LayerCount]; - for (int i = 0; i < m_LayerCount; i++) - { + for (int i = 0; i < m_LayerCount; i++) { m_Layers[i].init(machine->layer(i)); } } -StateMachineInstance::~StateMachineInstance() -{ - for (int i = 0; i < m_InputCount; i++) - { +StateMachineInstance::~StateMachineInstance() { + for (int i = 0; i < m_InputCount; i++) { delete m_InputInstances[i]; } delete[] m_InputInstances; delete[] m_Layers; } -bool StateMachineInstance::advance(Artboard* artboard, float seconds) -{ +bool StateMachineInstance::advance(Artboard* artboard, float seconds) { m_NeedsAdvance = false; - for (int i = 0; i < m_LayerCount; i++) - { + for (int i = 0; i < m_LayerCount; i++) { if (m_Layers[i].advance( - artboard, seconds, m_InputInstances, m_InputCount)) - { + artboard, seconds, m_InputInstances, m_InputCount)) { m_NeedsAdvance = true; } } - for (int i = 0; i < m_InputCount; i++) - { + for (int i = 0; i < m_InputCount; i++) { m_InputInstances[i]->advanced(); } @@ -342,75 +298,58 @@ void StateMachineInstance::markNeedsAdvance() { m_NeedsAdvance = true; } bool StateMachineInstance::needsAdvance() const { return m_NeedsAdvance; } -SMIInput* StateMachineInstance::input(size_t index) const -{ - if (index < m_InputCount) - { +SMIInput* StateMachineInstance::input(size_t index) const { + if (index < m_InputCount) { return m_InputInstances[index]; } return nullptr; } -SMIBool* StateMachineInstance::getBool(std::string name) const -{ - for (int i = 0; i < m_InputCount; i++) - { +SMIBool* StateMachineInstance::getBool(std::string name) const { + for (int i = 0; i < m_InputCount; i++) { auto input = m_InputInstances[i]->input(); - if (input->is<StateMachineBool>() && input->name() == name) - { + if (input->is<StateMachineBool>() && input->name() == name) { return static_cast<SMIBool*>(m_InputInstances[i]); } } return nullptr; } -SMINumber* StateMachineInstance::getNumber(std::string name) const -{ - for (int i = 0; i < m_InputCount; i++) - { +SMINumber* StateMachineInstance::getNumber(std::string name) const { + for (int i = 0; i < m_InputCount; i++) { auto input = m_InputInstances[i]->input(); - if (input->is<StateMachineNumber>() && input->name() == name) - { + if (input->is<StateMachineNumber>() && input->name() == name) { return static_cast<SMINumber*>(m_InputInstances[i]); } } return nullptr; } -SMITrigger* StateMachineInstance::getTrigger(std::string name) const -{ - for (int i = 0; i < m_InputCount; i++) - { +SMITrigger* StateMachineInstance::getTrigger(std::string name) const { + for (int i = 0; i < m_InputCount; i++) { auto input = m_InputInstances[i]->input(); - if (input->is<StateMachineTrigger>() && input->name() == name) - { + if (input->is<StateMachineTrigger>() && input->name() == name) { return static_cast<SMITrigger*>(m_InputInstances[i]); } } return nullptr; } -size_t StateMachineInstance::stateChangedCount() const -{ +size_t StateMachineInstance::stateChangedCount() const { size_t count = 0; - for (int i = 0; i < m_LayerCount; i++) - { - if (m_Layers[i].stateChangedOnAdvance()) - { + for (int i = 0; i < m_LayerCount; i++) { + if (m_Layers[i].stateChangedOnAdvance()) { count++; } } return count; } -const LayerState* StateMachineInstance::stateChangedByIndex(size_t index) const -{ +const LayerState* +StateMachineInstance::stateChangedByIndex(size_t index) const { size_t count = 0; - for (int i = 0; i < m_LayerCount; i++) - { - if (m_Layers[i].stateChangedOnAdvance()) - { - if (count == index) - { + for (int i = 0; i < m_LayerCount; i++) { + if (m_Layers[i].stateChangedOnAdvance()) { + if (count == index) { return m_Layers[i].currentState(); } count++; @@ -419,13 +358,10 @@ return nullptr; } -const size_t StateMachineInstance::currentAnimationCount() const -{ +const size_t StateMachineInstance::currentAnimationCount() const { size_t count = 0; - for (int i = 0; i < m_LayerCount; i++) - { - if (m_Layers[i].currentAnimation() != nullptr) - { + for (int i = 0; i < m_LayerCount; i++) { + if (m_Layers[i].currentAnimation() != nullptr) { count++; } } @@ -433,15 +369,11 @@ } const LinearAnimationInstance* -StateMachineInstance::currentAnimationByIndex(size_t index) const -{ +StateMachineInstance::currentAnimationByIndex(size_t index) const { size_t count = 0; - for (int i = 0; i < m_LayerCount; i++) - { - if (m_Layers[i].currentAnimation() != nullptr) - { - if (count == index) - { + for (int i = 0; i < m_LayerCount; i++) { + if (m_Layers[i].currentAnimation() != nullptr) { + if (count == index) { return m_Layers[i].currentAnimation(); } count++;
diff --git a/src/animation/state_machine_layer.cpp b/src/animation/state_machine_layer.cpp index 68a4369..a75ce1b 100644 --- a/src/animation/state_machine_layer.cpp +++ b/src/animation/state_machine_layer.cpp
@@ -8,25 +8,19 @@ using namespace rive; -StateMachineLayer::~StateMachineLayer() -{ - for (auto state : m_States) - { +StateMachineLayer::~StateMachineLayer() { + for (auto state : m_States) { delete state; } } -StatusCode StateMachineLayer::onAddedDirty(CoreContext* context) -{ +StatusCode StateMachineLayer::onAddedDirty(CoreContext* context) { StatusCode code; - for (auto state : m_States) - { - if ((code = state->onAddedDirty(context)) != StatusCode::Ok) - { + for (auto state : m_States) { + if ((code = state->onAddedDirty(context)) != StatusCode::Ok) { return code; } - switch (state->coreType()) - { + switch (state->coreType()) { case AnyState::typeKey: m_Any = state->as<AnyState>(); break; @@ -38,8 +32,7 @@ break; } } - if (m_Any == nullptr || m_Entry == nullptr || m_Exit == nullptr) - { + if (m_Any == nullptr || m_Entry == nullptr || m_Exit == nullptr) { // The layer is corrupt, we must have all three of these states. return StatusCode::InvalidObject; } @@ -47,13 +40,10 @@ return StatusCode::Ok; } -StatusCode StateMachineLayer::onAddedClean(CoreContext* context) -{ +StatusCode StateMachineLayer::onAddedClean(CoreContext* context) { StatusCode code; - for (auto state : m_States) - { - if ((code = state->onAddedClean(context)) != StatusCode::Ok) - { + for (auto state : m_States) { + if ((code = state->onAddedClean(context)) != StatusCode::Ok) { return code; } } @@ -61,17 +51,14 @@ return StatusCode::Ok; } -void StateMachineLayer::addState(LayerState* state) -{ +void StateMachineLayer::addState(LayerState* state) { m_States.push_back(state); } -StatusCode StateMachineLayer::import(ImportStack& importStack) -{ +StatusCode StateMachineLayer::import(ImportStack& importStack) { auto stateMachineImporter = importStack.latest<StateMachineImporter>(StateMachineBase::typeKey); - if (stateMachineImporter == nullptr) - { + if (stateMachineImporter == nullptr) { return StatusCode::MissingObject; } stateMachineImporter->addLayer(this);
diff --git a/src/animation/state_transition.cpp b/src/animation/state_transition.cpp index b273436..11cda62 100644 --- a/src/animation/state_transition.cpp +++ b/src/animation/state_transition.cpp
@@ -12,86 +12,68 @@ using namespace rive; -StateTransition::~StateTransition() -{ - for (auto condition : m_Conditions) - { +StateTransition::~StateTransition() { + for (auto condition : m_Conditions) { delete condition; } } -StatusCode StateTransition::onAddedDirty(CoreContext* context) -{ +StatusCode StateTransition::onAddedDirty(CoreContext* context) { StatusCode code; - for (auto condition : m_Conditions) - { - if ((code = condition->onAddedDirty(context)) != StatusCode::Ok) - { + for (auto condition : m_Conditions) { + if ((code = condition->onAddedDirty(context)) != StatusCode::Ok) { return code; } } return StatusCode::Ok; } -StatusCode StateTransition::onAddedClean(CoreContext* context) -{ +StatusCode StateTransition::onAddedClean(CoreContext* context) { StatusCode code; - for (auto condition : m_Conditions) - { - if ((code = condition->onAddedClean(context)) != StatusCode::Ok) - { + for (auto condition : m_Conditions) { + if ((code = condition->onAddedClean(context)) != StatusCode::Ok) { return code; } } return StatusCode::Ok; } -StatusCode StateTransition::import(ImportStack& importStack) -{ +StatusCode StateTransition::import(ImportStack& importStack) { auto stateImporter = importStack.latest<LayerStateImporter>(LayerState::typeKey); - if (stateImporter == nullptr) - { + if (stateImporter == nullptr) { return StatusCode::MissingObject; } stateImporter->addTransition(this); return Super::import(importStack); } -void StateTransition::addCondition(TransitionCondition* condition) -{ +void StateTransition::addCondition(TransitionCondition* condition) { m_Conditions.push_back(condition); } -float StateTransition::mixTime(const LayerState* stateFrom) const -{ - if (duration() == 0) - { +float StateTransition::mixTime(const LayerState* stateFrom) const { + if (duration() == 0) { return 0; } if ((transitionFlags() & StateTransitionFlags::DurationIsPercentage) == StateTransitionFlags::DurationIsPercentage) { float animationDuration = 0.0f; - if (stateFrom->is<AnimationState>()) - { + if (stateFrom->is<AnimationState>()) { auto animation = stateFrom->as<AnimationState>()->animation(); - if (animation != nullptr) - { + if (animation != nullptr) { animationDuration = animation->durationSeconds(); } } return duration() / 100.0f * animationDuration; - } - else - { + } else { return duration() / 1000.0f; } } float StateTransition::exitTimeSeconds(const LayerState* stateFrom, - bool absolute) const -{ + bool absolute) const { if ((transitionFlags() & StateTransitionFlags::ExitTimeIsPercentage) == StateTransitionFlags::ExitTimeIsPercentage) { @@ -99,8 +81,7 @@ float start = 0.0f; auto exitAnimation = exitTimeAnimation(stateFrom); - if (exitAnimation != nullptr) - { + if (exitAnimation != nullptr) { start = absolute ? exitAnimation->startSeconds() : 0.0f; animationDuration = exitAnimation->durationSeconds(); } @@ -111,8 +92,7 @@ } const LinearAnimationInstance* -StateTransition::exitTimeAnimationInstance(const StateInstance* from) const -{ +StateTransition::exitTimeAnimationInstance(const StateInstance* from) const { return from != nullptr && from->state()->is<AnimationState>() ? static_cast<const AnimationStateInstance*>(from) ->animationInstance() @@ -120,8 +100,7 @@ } const LinearAnimation* -StateTransition::exitTimeAnimation(const LayerState* from) const -{ +StateTransition::exitTimeAnimation(const LayerState* from) const { return from != nullptr && from->is<AnimationState>() ? from->as<AnimationState>()->animation() : nullptr; @@ -129,15 +108,12 @@ AllowTransition StateTransition::allowed(StateInstance* stateFrom, SMIInput** inputs, - bool ignoreTriggers) const -{ - if (isDisabled()) - { + bool ignoreTriggers) const { + if (isDisabled()) { return AllowTransition::no; } - for (auto condition : m_Conditions) - { + for (auto condition : m_Conditions) { // N.B. state machine instance sanitizes these for us... auto input = inputs[condition->inputId()]; @@ -148,11 +124,9 @@ } } - if (enableExitTime()) - { + if (enableExitTime()) { auto exitAnimation = exitTimeAnimationInstance(stateFrom); - if (exitAnimation != nullptr) - { + if (exitAnimation != nullptr) { // Exit time is specified in a value less than a single loop, so we // want to allow exiting regardless of which loop we're on. To do // that we bring the exit time up to the loop our lastTime is at. @@ -181,8 +155,7 @@ exitTime += std::floor(lastTime / duration) * duration; } - if (time < exitTime) - { + if (time < exitTime) { return AllowTransition::waitingForExit; } } @@ -190,14 +163,12 @@ return AllowTransition::yes; } -bool StateTransition::applyExitCondition(StateInstance* from) const -{ +bool StateTransition::applyExitCondition(StateInstance* from) const { // Hold exit time when the user has set to pauseOnExit on this condition // (only valid when exiting from an Animation). bool useExitTime = enableExitTime() && (from != nullptr && from->state()->is<AnimationState>()); - if (pauseOnExit() && useExitTime) - { + if (pauseOnExit() && useExitTime) { static_cast<AnimationStateInstance*>(from)->animationInstance()->time( exitTimeSeconds(from->state(), true)); return true;
diff --git a/src/animation/system_state_instance.cpp b/src/animation/system_state_instance.cpp index 347f7d5..3b361fd 100644 --- a/src/animation/system_state_instance.cpp +++ b/src/animation/system_state_instance.cpp
@@ -2,9 +2,7 @@ using namespace rive; SystemStateInstance::SystemStateInstance(const LayerState* layerState) : - StateInstance(layerState) -{ -} + StateInstance(layerState) {} void SystemStateInstance::advance(float seconds, SMIInput** inputs) {} void SystemStateInstance::apply(Artboard* artboard, float mix) {}
diff --git a/src/animation/transition_bool_condition.cpp b/src/animation/transition_bool_condition.cpp index 00fa1f7..1b9ca6b 100644 --- a/src/animation/transition_bool_condition.cpp +++ b/src/animation/transition_bool_condition.cpp
@@ -6,18 +6,15 @@ using namespace rive; bool TransitionBoolCondition::validateInputType( - const StateMachineInput* input) const -{ + const StateMachineInput* input) const { // A null input is valid as the StateMachine can attempt to limp along if we // introduce new input types that old conditions are expected to handle in // newer runtimes. The older runtimes will just evaluate them to true. return input == nullptr || input->is<StateMachineBool>(); } -bool TransitionBoolCondition::evaluate(const SMIInput* inputInstance) const -{ - if (inputInstance == nullptr) - { +bool TransitionBoolCondition::evaluate(const SMIInput* inputInstance) const { + if (inputInstance == nullptr) { return true; } auto boolInput = reinterpret_cast<const SMIBool*>(inputInstance);
diff --git a/src/animation/transition_condition.cpp b/src/animation/transition_condition.cpp index 42ed719..e9d307b 100644 --- a/src/animation/transition_condition.cpp +++ b/src/animation/transition_condition.cpp
@@ -6,22 +6,18 @@ using namespace rive; -StatusCode TransitionCondition::onAddedDirty(CoreContext* context) -{ +StatusCode TransitionCondition::onAddedDirty(CoreContext* context) { return StatusCode::Ok; } -StatusCode TransitionCondition::onAddedClean(CoreContext* context) -{ +StatusCode TransitionCondition::onAddedClean(CoreContext* context) { return StatusCode::Ok; } -StatusCode TransitionCondition::import(ImportStack& importStack) -{ +StatusCode TransitionCondition::import(ImportStack& importStack) { auto stateMachineImporter = importStack.latest<StateMachineImporter>(StateMachine::typeKey); - if (stateMachineImporter == nullptr) - { + if (stateMachineImporter == nullptr) { return StatusCode::MissingObject; } @@ -39,8 +35,7 @@ auto transitionImporter = importStack.latest<StateTransitionImporter>(StateTransition::typeKey); - if (transitionImporter == nullptr) - { + if (transitionImporter == nullptr) { return StatusCode::MissingObject; } transitionImporter->addCondition(this);
diff --git a/src/animation/transition_number_condition.cpp b/src/animation/transition_number_condition.cpp index df6214e..b6bbd8d 100644 --- a/src/animation/transition_number_condition.cpp +++ b/src/animation/transition_number_condition.cpp
@@ -6,24 +6,20 @@ using namespace rive; bool TransitionNumberCondition::validateInputType( - const StateMachineInput* input) const -{ + const StateMachineInput* input) const { // A null input is valid as the StateMachine can attempt to limp along if we // introduce new input types that old conditions are expected to handle in // newer runtimes. The older runtimes will just evaluate them to true. return input == nullptr || input->is<StateMachineNumber>(); } -bool TransitionNumberCondition::evaluate(const SMIInput* inputInstance) const -{ - if (inputInstance == nullptr) - { +bool TransitionNumberCondition::evaluate(const SMIInput* inputInstance) const { + if (inputInstance == nullptr) { return true; } auto numberInput = reinterpret_cast<const SMINumber*>(inputInstance); - switch (op()) - { + switch (op()) { case TransitionConditionOp::equal: return numberInput->value() == value(); case TransitionConditionOp::notEqual:
diff --git a/src/animation/transition_trigger_condition.cpp b/src/animation/transition_trigger_condition.cpp index d3d79f2..0587062 100644 --- a/src/animation/transition_trigger_condition.cpp +++ b/src/animation/transition_trigger_condition.cpp
@@ -6,24 +6,20 @@ using namespace rive; bool TransitionTriggerCondition::validateInputType( - const StateMachineInput* input) const -{ + const StateMachineInput* input) const { // A null input is valid as the StateMachine can attempt to limp along if we // introduce new input types that old conditions are expected to handle in // newer runtimes. The older runtimes will just evaluate them to true. return input == nullptr || input->is<StateMachineTrigger>(); } -bool TransitionTriggerCondition::evaluate(const SMIInput* inputInstance) const -{ - if (inputInstance == nullptr) - { +bool TransitionTriggerCondition::evaluate(const SMIInput* inputInstance) const { + if (inputInstance == nullptr) { return true; } auto triggerInput = reinterpret_cast<const SMITrigger*>(inputInstance); - if (triggerInput->m_Fired) - { + if (triggerInput->m_Fired) { return true; } return false;
diff --git a/src/artboard.cpp b/src/artboard.cpp index f060d11..f358abc 100644 --- a/src/artboard.cpp +++ b/src/artboard.cpp
@@ -17,13 +17,10 @@ using namespace rive; -Artboard::~Artboard() -{ - for (auto object : m_Objects) - { +Artboard::~Artboard() { + for (auto object : m_Objects) { // First object is artboard - if (object == this) - { + if (object == this) { continue; } delete object; @@ -32,14 +29,11 @@ // Instances reference back to the original artboard's animations and state // machines, so don't delete them here, they'll get cleaned up when the // source is deleted. - if (!m_IsInstance) - { - for (auto object : m_Animations) - { + if (!m_IsInstance) { + for (auto object : m_Animations) { delete object; } - for (auto object : m_StateMachines) - { + for (auto object : m_StateMachines) { delete object; } } @@ -48,14 +42,12 @@ delete m_BackgroundPath; } -static bool canContinue(StatusCode code) -{ +static bool canContinue(StatusCode code) { // We currently only cease loading on invalid object. return code != StatusCode::InvalidObject; } -StatusCode Artboard::initialize() -{ +StatusCode Artboard::initialize() { StatusCode code; m_BackgroundPath = makeCommandPath(PathSpace::Neither); @@ -64,31 +56,24 @@ // onAddedDirty guarantees that all objects are now available so they can be // looked up by index/id. This is where nodes find their parents, but they // can't assume that their parent's parent will have resolved yet. - for (auto object : m_Objects) - { - if (object == nullptr) - { + for (auto object : m_Objects) { + if (object == nullptr) { // objects can be null if they were not understood by this runtime. continue; } - if (!canContinue(code = object->onAddedDirty(this))) - { + if (!canContinue(code = object->onAddedDirty(this))) { return code; } } - for (auto object : m_Animations) - { - if (!canContinue(code = object->onAddedDirty(this))) - { + for (auto object : m_Animations) { + if (!canContinue(code = object->onAddedDirty(this))) { return code; } } - for (auto object : m_StateMachines) - { - if (!canContinue(code = object->onAddedDirty(this))) - { + for (auto object : m_StateMachines) { + if (!canContinue(code = object->onAddedDirty(this))) { return code; } } @@ -101,28 +86,20 @@ // assume that they have resolved too. This is where the whole hierarchy is // linked up and we can traverse it to find other references (my parent's // parent should be type X can be checked now). - for (auto object : m_Objects) - { - if (object == nullptr) - { + for (auto object : m_Objects) { + if (object == nullptr) { continue; } - if (!canContinue(code = object->onAddedClean(this))) - { + if (!canContinue(code = object->onAddedClean(this))) { return code; } - switch (object->coreType()) - { - case DrawRulesBase::typeKey: - { + switch (object->coreType()) { + case DrawRulesBase::typeKey: { DrawRules* rules = reinterpret_cast<DrawRules*>(object); Core* component = resolve(rules->parentId()); - if (component != nullptr) - { + if (component != nullptr) { componentDrawRules[component] = rules; - } - else - { + } else { fprintf(stderr, "Artboard::initialize - Draw rule targets missing " "component width id %d\n", @@ -136,36 +113,28 @@ } } - for (auto object : m_Animations) - { - if (!canContinue(code = object->onAddedClean(this))) - { + for (auto object : m_Animations) { + if (!canContinue(code = object->onAddedClean(this))) { return code; } } - for (auto object : m_StateMachines) - { - if (!canContinue(code = object->onAddedClean(this))) - { + for (auto object : m_StateMachines) { + if (!canContinue(code = object->onAddedClean(this))) { return code; } } // Multi-level references have been built up, now we can // actually mark what's dependent on what. - for (auto object : m_Objects) - { - if (object == nullptr) - { + for (auto object : m_Objects) { + if (object == nullptr) { continue; } - if (object->is<Component>()) - { + if (object->is<Component>()) { object->as<Component>()->buildDependencies(); } - if (object->is<Drawable>()) - { + if (object->is<Drawable>()) { Drawable* drawable = object->as<Drawable>(); m_Drawables.push_back(drawable); @@ -173,8 +142,7 @@ parent = parent->parent()) { auto itr = componentDrawRules.find(parent); - if (itr != componentDrawRules.end()) - { + if (itr != componentDrawRules.end()) { drawable->flattenedDrawRules = itr->second; break; } @@ -187,30 +155,23 @@ DrawTarget root; // Build up the draw order. Look for draw targets and build // their dependencies. - for (auto object : m_Objects) - { - if (object == nullptr) - { + for (auto object : m_Objects) { + if (object == nullptr) { continue; } - if (object->is<DrawTarget>()) - { + if (object->is<DrawTarget>()) { DrawTarget* target = object->as<DrawTarget>(); root.addDependent(target); auto dependentRules = target->drawable()->flattenedDrawRules; - if (dependentRules != nullptr) - { + if (dependentRules != nullptr) { // Because we don't store targets on rules, we need // to find the targets that belong to this rule // here. - for (auto object : m_Objects) - { - if (object != nullptr && object->is<DrawTarget>()) - { + for (auto object : m_Objects) { + if (object != nullptr && object->is<DrawTarget>()) { DrawTarget* dependentTarget = object->as<DrawTarget>(); - if (dependentTarget->parent() == dependentRules) - { + if (dependentTarget->parent() == dependentRules) { dependentTarget->addDependent(target); } } @@ -223,92 +184,70 @@ sorter.sort(&root, drawTargetOrder); auto itr = drawTargetOrder.begin(); itr++; - while (itr != drawTargetOrder.end()) - { + while (itr != drawTargetOrder.end()) { m_DrawTargets.push_back(reinterpret_cast<DrawTarget*>(*itr++)); } return StatusCode::Ok; } -void Artboard::sortDrawOrder() -{ - for (auto target : m_DrawTargets) - { +void Artboard::sortDrawOrder() { + for (auto target : m_DrawTargets) { target->first = target->last = nullptr; } m_FirstDrawable = nullptr; Drawable* lastDrawable = nullptr; - for (auto drawable : m_Drawables) - { + for (auto drawable : m_Drawables) { auto rules = drawable->flattenedDrawRules; - if (rules != nullptr && rules->activeTarget() != nullptr) - { + if (rules != nullptr && rules->activeTarget() != nullptr) { auto target = rules->activeTarget(); - if (target->first == nullptr) - { + if (target->first == nullptr) { target->first = target->last = drawable; drawable->prev = drawable->next = nullptr; - } - else - { + } else { target->last->next = drawable; drawable->prev = target->last; target->last = drawable; drawable->next = nullptr; } - } - else - { + } else { drawable->prev = lastDrawable; drawable->next = nullptr; - if (lastDrawable == nullptr) - { + if (lastDrawable == nullptr) { lastDrawable = m_FirstDrawable = drawable; - } - else - { + } else { lastDrawable->next = drawable; lastDrawable = drawable; } } } - for (auto rule : m_DrawTargets) - { - if (rule->first == nullptr) - { + for (auto rule : m_DrawTargets) { + if (rule->first == nullptr) { continue; } auto targetDrawable = rule->drawable(); - switch (rule->placement()) - { - case DrawTargetPlacement::before: - { - if (targetDrawable->prev != nullptr) - { + switch (rule->placement()) { + case DrawTargetPlacement::before: { + if (targetDrawable->prev != nullptr) { targetDrawable->prev->next = rule->first; rule->first->prev = targetDrawable->prev; } - if (targetDrawable == m_FirstDrawable) - { + if (targetDrawable == m_FirstDrawable) { m_FirstDrawable = rule->first; } targetDrawable->prev = rule->last; rule->last->next = targetDrawable; break; } - case DrawTargetPlacement::after: - { - if (targetDrawable->next != nullptr) - { + case DrawTargetPlacement::after: { + if (targetDrawable->next != nullptr) { targetDrawable->next->prev = rule->last; rule->last->next = targetDrawable->next; } - if (targetDrawable == lastDrawable) - { + if (targetDrawable == lastDrawable) { lastDrawable = rule->last; } targetDrawable->next = rule->first; @@ -321,13 +260,11 @@ m_FirstDrawable = lastDrawable; } -void Artboard::sortDependencies() -{ +void Artboard::sortDependencies() { DependencySorter sorter; sorter.sort(this, m_DependencyOrder); unsigned int graphOrder = 0; - for (auto component : m_DependencyOrder) - { + for (auto component : m_DependencyOrder) { component->m_GraphOrder = graphOrder++; } m_Dirt |= ComponentDirt::Components; @@ -335,63 +272,49 @@ void Artboard::addObject(Core* object) { m_Objects.push_back(object); } -void Artboard::addAnimation(LinearAnimation* object) -{ +void Artboard::addAnimation(LinearAnimation* object) { m_Animations.push_back(object); } -void Artboard::addStateMachine(StateMachine* object) -{ +void Artboard::addStateMachine(StateMachine* object) { m_StateMachines.push_back(object); } -void Artboard::addNestedArtboard(NestedArtboard* artboard) -{ +void Artboard::addNestedArtboard(NestedArtboard* artboard) { m_NestedArtboards.push_back(artboard); } -Core* Artboard::resolve(int id) const -{ - if (id < 0 || id >= static_cast<int>(m_Objects.size())) - { +Core* Artboard::resolve(int id) const { + if (id < 0 || id >= static_cast<int>(m_Objects.size())) { return nullptr; } return m_Objects[id]; } -void Artboard::onComponentDirty(Component* component) -{ +void Artboard::onComponentDirty(Component* component) { m_Dirt |= ComponentDirt::Components; /// If the order of the component is less than the current dirt /// depth, update the dirt depth so that the update loop can break /// out early and re-run (something up the tree is dirty). - if (component->graphOrder() < m_DirtDepth) - { + if (component->graphOrder() < m_DirtDepth) { m_DirtDepth = component->graphOrder(); } } -void Artboard::onDirty(ComponentDirt dirt) -{ +void Artboard::onDirty(ComponentDirt dirt) { m_Dirt |= ComponentDirt::Components; } -void Artboard::update(ComponentDirt value) -{ - if (hasDirt(value, ComponentDirt::DrawOrder)) - { +void Artboard::update(ComponentDirt value) { + if (hasDirt(value, ComponentDirt::DrawOrder)) { sortDrawOrder(); } - if (hasDirt(value, ComponentDirt::Path)) - { + if (hasDirt(value, ComponentDirt::Path)) { m_ClipPath->reset(); - if (m_FrameOrigin) - { + if (m_FrameOrigin) { m_ClipPath->addRect(0.0f, 0.0f, width(), height()); - } - else - { + } else { m_ClipPath->addRect( -width() * originX(), -height() * originY(), width(), height()); } @@ -400,26 +323,21 @@ } } -bool Artboard::updateComponents() -{ - if (hasDirt(ComponentDirt::Components)) - { +bool Artboard::updateComponents() { + if (hasDirt(ComponentDirt::Components)) { const int maxSteps = 100; int step = 0; auto count = m_DependencyOrder.size(); - while (hasDirt(ComponentDirt::Components) && step < maxSteps) - { + while (hasDirt(ComponentDirt::Components) && step < maxSteps) { m_Dirt = m_Dirt & ~ComponentDirt::Components; // Track dirt depth here so that if something else marks // dirty, we restart. - for (unsigned int i = 0; i < count; i++) - { + for (unsigned int i = 0; i < count; i++) { auto component = m_DependencyOrder[i]; m_DirtDepth = i; auto d = component->m_Dirt; - if (d == ComponentDirt::None) - { + if (d == ComponentDirt::None) { continue; } component->m_Dirt = ComponentDirt::None; @@ -428,8 +346,7 @@ // If the update changed the dirt depth by adding dirt // to something before us (in the DAG), early out and // re-run the update. - if (m_DirtDepth < i) - { + if (m_DirtDepth < i) { // We put this in here just to know if we need to // keep this around... assert(false); @@ -443,46 +360,37 @@ return false; } -bool Artboard::advance(double elapsedSeconds) -{ - for (auto nestedArtboard : m_NestedArtboards) - { +bool Artboard::advance(double elapsedSeconds) { + for (auto nestedArtboard : m_NestedArtboards) { nestedArtboard->advance(elapsedSeconds); } return updateComponents(); } -void Artboard::draw(Renderer* renderer, DrawOption option) -{ +void Artboard::draw(Renderer* renderer, DrawOption option) { renderer->save(); - if (clip()) - { + if (clip()) { renderer->clipPath(m_ClipPath->renderPath()); } - if (m_FrameOrigin) - { + if (m_FrameOrigin) { Mat2D artboardTransform; artboardTransform[4] = width() * originX(); artboardTransform[5] = height() * originY(); renderer->transform(artboardTransform); } - if (option != DrawOption::kHideBG) - { - for (auto shapePaint : m_ShapePaints) - { + if (option != DrawOption::kHideBG) { + for (auto shapePaint : m_ShapePaints) { shapePaint->draw(renderer, m_BackgroundPath); } } - if (option != DrawOption::kHideFG) - { + if (option != DrawOption::kHideFG) { for (auto drawable = m_FirstDrawable; drawable != nullptr; drawable = drawable->prev) { - if (drawable->isHidden()) - { + if (drawable->isHidden()) { continue; } drawable->draw(renderer); @@ -495,8 +403,8 @@ AABB Artboard::bounds() const { return AABB(0.0f, 0.0f, width(), height()); } bool Artboard::isTranslucent(const LinearAnimation* anim) const { - // For now we're conservative/lazy -- if we see that any of our paints are animated - // we assume that might make it non-opaque, so we early out + // For now we're conservative/lazy -- if we see that any of our paints are + // animated we assume that might make it non-opaque, so we early out for (const auto obj : anim->m_KeyedObjects) { const auto ptr = this->resolve(obj->objectId()); for (const auto sp : m_ShapePaints) { @@ -506,78 +414,64 @@ } } - // If we get here, we have no animations, so just check our paints for opacity + // If we get here, we have no animations, so just check our paints for + // opacity for (const auto sp : m_ShapePaints) { if (!sp->isTranslucent()) { - return false; // one opaque fill is sufficient to be opaque + return false; // one opaque fill is sufficient to be opaque } } return true; } -LinearAnimation* Artboard::firstAnimation() const -{ - if (m_Animations.empty()) - { +LinearAnimation* Artboard::firstAnimation() const { + if (m_Animations.empty()) { return nullptr; } return m_Animations.front(); } -LinearAnimation* Artboard::animation(std::string name) const -{ - for (auto animation : m_Animations) - { - if (animation->name() == name) - { +LinearAnimation* Artboard::animation(std::string name) const { + for (auto animation : m_Animations) { + if (animation->name() == name) { return animation; } } return nullptr; } -LinearAnimation* Artboard::animation(size_t index) const -{ - if (index >= m_Animations.size()) - { +LinearAnimation* Artboard::animation(size_t index) const { + if (index >= m_Animations.size()) { return nullptr; } return m_Animations[index]; } -StateMachine* Artboard::firstStateMachine() const -{ - if (m_StateMachines.empty()) - { +StateMachine* Artboard::firstStateMachine() const { + if (m_StateMachines.empty()) { return nullptr; } return m_StateMachines.front(); } -StateMachine* Artboard::stateMachine(std::string name) const -{ - for (auto machine : m_StateMachines) - { - if (machine->name() == name) - { +StateMachine* Artboard::stateMachine(std::string name) const { + for (auto machine : m_StateMachines) { + if (machine->name() == name) { return machine; } } return nullptr; } -StateMachine* Artboard::stateMachine(size_t index) const -{ - if (index >= m_StateMachines.size()) - { +StateMachine* Artboard::stateMachine(size_t index) const { + if (index >= m_StateMachines.size()) { return nullptr; } return m_StateMachines[index]; } -Artboard* Artboard::instance() const -{ +Artboard* Artboard::instance() const { auto artboardClone = clone()->as<Artboard>(); artboardClone->m_FrameOrigin = m_FrameOrigin; @@ -586,60 +480,47 @@ // Skip first object (artboard). auto itr = m_Objects.begin(); - while (++itr != m_Objects.end()) - { + while (++itr != m_Objects.end()) { auto object = *itr; cloneObjects.push_back(object == nullptr ? nullptr : object->clone()); } - for (auto animation : m_Animations) - { + for (auto animation : m_Animations) { artboardClone->m_Animations.push_back(animation); } - for (auto stateMachine : m_StateMachines) - { + for (auto stateMachine : m_StateMachines) { artboardClone->m_StateMachines.push_back(stateMachine); } - if (artboardClone->initialize() != StatusCode::Ok) - { + if (artboardClone->initialize() != StatusCode::Ok) { delete artboardClone; artboardClone = nullptr; - } - else - { + } else { artboardClone->m_IsInstance = true; } return artboardClone; } -void Artboard::frameOrigin(bool value) -{ - if (value == m_FrameOrigin) - { +void Artboard::frameOrigin(bool value) { + if (value == m_FrameOrigin) { return; } m_FrameOrigin = value; addDirt(ComponentDirt::Path); } -StatusCode Artboard::import(ImportStack& importStack) -{ +StatusCode Artboard::import(ImportStack& importStack) { auto backboardImporter = importStack.latest<BackboardImporter>(Backboard::typeKey); - if (backboardImporter == nullptr) - { + if (backboardImporter == nullptr) { return StatusCode::MissingObject; } StatusCode result = Super::import(importStack); - if (result == StatusCode::Ok) - { + if (result == StatusCode::Ok) { backboardImporter->addArtboard(this); - } - else - { + } else { backboardImporter->addMissingArtboard(); } return result;
diff --git a/src/assets/file_asset.cpp b/src/assets/file_asset.cpp index 2592ee4..edd4eb8 100644 --- a/src/assets/file_asset.cpp +++ b/src/assets/file_asset.cpp
@@ -4,12 +4,10 @@ using namespace rive; -StatusCode FileAsset::import(ImportStack& importStack) -{ +StatusCode FileAsset::import(ImportStack& importStack) { auto backboardImporter = importStack.latest<BackboardImporter>(Backboard::typeKey); - if (backboardImporter == nullptr) - { + if (backboardImporter == nullptr) { return StatusCode::MissingObject; } backboardImporter->addFileAsset(this); @@ -17,14 +15,12 @@ return Super::import(importStack); } -std::string FileAsset::uniqueFilename() -{ +std::string FileAsset::uniqueFilename() { // remove final extension std::string uniqueFilename = name(); std::size_t finalDot = uniqueFilename.rfind('.'); - if (finalDot != std::string::npos) - { + if (finalDot != std::string::npos) { uniqueFilename = uniqueFilename.substr(0, finalDot); } return uniqueFilename + "-" + std::to_string(assetId()) + "." +
diff --git a/src/assets/file_asset_contents.cpp b/src/assets/file_asset_contents.cpp index 1af41ef..1f552f6 100644 --- a/src/assets/file_asset_contents.cpp +++ b/src/assets/file_asset_contents.cpp
@@ -4,12 +4,10 @@ using namespace rive; -StatusCode FileAssetContents::import(ImportStack& importStack) -{ +StatusCode FileAssetContents::import(ImportStack& importStack) { auto fileAssetImporter = importStack.latest<FileAssetImporter>(FileAsset::typeKey); - if (fileAssetImporter == nullptr) - { + if (fileAssetImporter == nullptr) { return StatusCode::MissingObject; } fileAssetImporter->loadContents(*this);
diff --git a/src/assets/image_asset.cpp b/src/assets/image_asset.cpp index 415012d..8433680 100644 --- a/src/assets/image_asset.cpp +++ b/src/assets/image_asset.cpp
@@ -6,8 +6,7 @@ ImageAsset::ImageAsset() : m_RenderImage(makeRenderImage()) {} ImageAsset::~ImageAsset() { delete m_RenderImage; } -bool ImageAsset::decode(const uint8_t* bytes, std::size_t size) -{ +bool ImageAsset::decode(const uint8_t* bytes, std::size_t size) { #ifdef TESTING decodedByteSize = size; #endif
diff --git a/src/bones/bone.cpp b/src/bones/bone.cpp index e612724..217738c 100644 --- a/src/bones/bone.cpp +++ b/src/bones/bone.cpp
@@ -6,21 +6,17 @@ void Bone::addChildBone(Bone* bone) { m_ChildBones.push_back(bone); } -StatusCode Bone::onAddedClean(CoreContext* context) -{ +StatusCode Bone::onAddedClean(CoreContext* context) { Super::onAddedClean(context); - if (!parent()->is<Bone>()) - { + if (!parent()->is<Bone>()) { return StatusCode::MissingObject; } parent()->as<Bone>()->addChildBone(this); return StatusCode::Ok; } -void Bone::lengthChanged() -{ - for (auto bone : m_ChildBones) - { +void Bone::lengthChanged() { + for (auto bone : m_ChildBones) { bone->markTransformDirty(); } } @@ -29,15 +25,13 @@ float Bone::y() const { return 0.0f; } -void Bone::tipWorldTranslation(Vec2D& result) -{ +void Bone::tipWorldTranslation(Vec2D& result) { result[0] = length(); result[1] = 0.0f; Vec2D::transform(result, result, worldTransform()); } -void Bone::addPeerConstraint(Constraint* peer) -{ +void Bone::addPeerConstraint(Constraint* peer) { assert(std::find(m_PeerConstraints.begin(), m_PeerConstraints.end(), peer) == m_PeerConstraints.end());
diff --git a/src/bones/root_bone.cpp b/src/bones/root_bone.cpp index ff592f9..354555b 100644 --- a/src/bones/root_bone.cpp +++ b/src/bones/root_bone.cpp
@@ -2,8 +2,7 @@ using namespace rive; -StatusCode RootBone::onAddedClean(CoreContext* context) -{ +StatusCode RootBone::onAddedClean(CoreContext* context) { // Intentionally doesn't call Super(Bone)::onAddedClean and goes straight to // the super.super TransformComponent as that assumes the parent must be a // Bone while a root bone is a special case Bone that can be parented to
diff --git a/src/bones/skin.cpp b/src/bones/skin.cpp index 345dda2..1e38a25 100644 --- a/src/bones/skin.cpp +++ b/src/bones/skin.cpp
@@ -9,8 +9,7 @@ Skin::~Skin() { delete[] m_BoneTransforms; } -StatusCode Skin::onAddedClean(CoreContext* context) -{ +StatusCode Skin::onAddedClean(CoreContext* context) { m_WorldTransform[0] = xx(); m_WorldTransform[1] = xy(); m_WorldTransform[2] = yx(); @@ -19,8 +18,7 @@ m_WorldTransform[5] = ty(); m_Skinnable = Skinnable::from(parent()); - if (m_Skinnable == nullptr) - { + if (m_Skinnable == nullptr) { return StatusCode::MissingObject; } @@ -29,12 +27,10 @@ return StatusCode::Ok; } -void Skin::update(ComponentDirt value) -{ +void Skin::update(ComponentDirt value) { int bidx = 6; Mat2D world; - for (auto tendon : m_Tendons) - { + for (auto tendon : m_Tendons) { Mat2D::multiply( world, tendon->bone()->worldTransform(), tendon->inverseBind()); m_BoneTransforms[bidx++] = world[0]; @@ -46,15 +42,12 @@ } } -void Skin::buildDependencies() -{ +void Skin::buildDependencies() { // depend on bones from tendons - for (auto tendon : m_Tendons) - { + for (auto tendon : m_Tendons) { auto bone = tendon->bone(); bone->addDependent(this); - for (auto constraint : bone->peerConstraints()) - { + for (auto constraint : bone->peerConstraints()) { constraint->parent()->addDependent(this); } } @@ -72,10 +65,8 @@ m_BoneTransforms[5] = 0; } -void Skin::deform(std::vector<PathVertex*>& vertices) -{ - for (auto vertex : vertices) - { +void Skin::deform(std::vector<PathVertex*>& vertices) { + for (auto vertex : vertices) { vertex->deform(m_WorldTransform, m_BoneTransforms); } }
diff --git a/src/bones/skinnable.cpp b/src/bones/skinnable.cpp index 35fc533..8dabc6f 100644 --- a/src/bones/skinnable.cpp +++ b/src/bones/skinnable.cpp
@@ -3,10 +3,8 @@ using namespace rive; -Skinnable* Skinnable::from(Component* component) -{ - switch (component->coreType()) - { +Skinnable* Skinnable::from(Component* component) { + switch (component->coreType()) { case PointsPath::typeKey: return component->as<PointsPath>(); break;
diff --git a/src/bones/tendon.cpp b/src/bones/tendon.cpp index 9b8cd74..9e66364 100644 --- a/src/bones/tendon.cpp +++ b/src/bones/tendon.cpp
@@ -5,8 +5,7 @@ using namespace rive; -StatusCode Tendon::onAddedDirty(CoreContext* context) -{ +StatusCode Tendon::onAddedDirty(CoreContext* context) { Mat2D bind; bind[0] = xx(); bind[1] = xy(); @@ -15,19 +14,16 @@ bind[4] = tx(); bind[5] = ty(); - if (!Mat2D::invert(m_InverseBind, bind)) - { + if (!Mat2D::invert(m_InverseBind, bind)) { return StatusCode::FailedInversion; } StatusCode code = Super::onAddedDirty(context); - if (code != StatusCode::Ok) - { + if (code != StatusCode::Ok) { return code; } auto coreObject = context->resolve(boneId()); - if (coreObject == nullptr || !coreObject->is<Bone>()) - { + if (coreObject == nullptr || !coreObject->is<Bone>()) { return StatusCode::MissingObject; } @@ -36,10 +32,8 @@ return StatusCode::Ok; } -StatusCode Tendon::onAddedClean(CoreContext* context) -{ - if (!parent()->is<Skin>()) - { +StatusCode Tendon::onAddedClean(CoreContext* context) { + if (!parent()->is<Skin>()) { return StatusCode::MissingObject; }
diff --git a/src/bones/weight.cpp b/src/bones/weight.cpp index 48b08a3..69935d6 100644 --- a/src/bones/weight.cpp +++ b/src/bones/weight.cpp
@@ -4,15 +4,12 @@ using namespace rive; -StatusCode Weight::onAddedDirty(CoreContext* context) -{ +StatusCode Weight::onAddedDirty(CoreContext* context) { StatusCode code = Super::onAddedDirty(context); - if (code != StatusCode::Ok) - { + if (code != StatusCode::Ok) { return code; } - if (!parent()->is<PathVertex>()) - { + if (!parent()->is<PathVertex>()) { return StatusCode::MissingObject; } @@ -21,8 +18,7 @@ return StatusCode::Ok; } -static int encodedWeightValue(unsigned int index, unsigned int data) -{ +static int encodedWeightValue(unsigned int index, unsigned int data) { return (data >> (index * 8)) & 0xFF; } @@ -32,16 +28,13 @@ unsigned int weights, const Mat2D& world, const float* boneTransforms, - Vec2D& result) -{ + Vec2D& result) { float xx = 0, xy = 0, yx = 0, yy = 0, tx = 0, ty = 0; float rx = world[0] * x + world[2] * y + world[4]; float ry = world[1] * x + world[3] * y + world[5]; - for (int i = 0; i < 4; i++) - { + for (int i = 0; i < 4; i++) { int weight = encodedWeightValue(i, weights); - if (weight == 0) - { + if (weight == 0) { continue; }
diff --git a/src/component.cpp b/src/component.cpp index 3049649..ae09548 100644 --- a/src/component.cpp +++ b/src/component.cpp
@@ -8,25 +8,21 @@ using namespace rive; -StatusCode Component::onAddedDirty(CoreContext* context) -{ +StatusCode Component::onAddedDirty(CoreContext* context) { m_Artboard = static_cast<Artboard*>(context); - if (this == m_Artboard) - { + if (this == m_Artboard) { // We're the artboard, don't parent to ourselves. return StatusCode::Ok; } auto coreObject = context->resolve(parentId()); - if (coreObject == nullptr || !coreObject->is<ContainerComponent>()) - { + if (coreObject == nullptr || !coreObject->is<ContainerComponent>()) { return StatusCode::MissingObject; } m_Parent = reinterpret_cast<ContainerComponent*>(coreObject); return StatusCode::Ok; } -void Component::addDependent(Component* component) -{ +void Component::addDependent(Component* component) { // Make it's not already a dependent. if (std::find(m_Dependents.begin(), m_Dependents.end(), component) != m_Dependents.end()) @@ -36,10 +32,8 @@ m_Dependents.push_back(component); } -bool Component::addDirt(ComponentDirt value, bool recurse) -{ - if ((m_Dirt & value) == value) - { +bool Component::addDirt(ComponentDirt value, bool recurse) { + if ((m_Dirt & value) == value) { // Already marked. return false; } @@ -51,22 +45,18 @@ m_Artboard->onComponentDirty(this); - if (!recurse) - { + if (!recurse) { return true; } - for (auto d : m_Dependents) - { + for (auto d : m_Dependents) { d->addDirt(value, true); } return true; } -StatusCode Component::import(ImportStack& importStack) -{ - if (is<Artboard>()) - { +StatusCode Component::import(ImportStack& importStack) { + if (is<Artboard>()) { // Artboards are always their first object. assert(as<Artboard>()->objects().size() == 0); as<Artboard>()->addObject(this); @@ -75,8 +65,7 @@ auto artboardImporter = importStack.latest<ArtboardImporter>(ArtboardBase::typeKey); - if (artboardImporter == nullptr) - { + if (artboardImporter == nullptr) { return StatusCode::MissingObject; } artboardImporter->addComponent(this);
diff --git a/src/constraints/constraint.cpp b/src/constraints/constraint.cpp index 7da213c..ec207c4 100644 --- a/src/constraints/constraint.cpp +++ b/src/constraints/constraint.cpp
@@ -6,10 +6,8 @@ using namespace rive; -StatusCode Constraint::onAddedClean(CoreContext* context) -{ - if (!parent()->is<TransformComponent>()) - { +StatusCode Constraint::onAddedClean(CoreContext* context) { + if (!parent()->is<TransformComponent>()) { return StatusCode::InvalidObject; } @@ -18,32 +16,27 @@ return StatusCode::Ok; } -void Constraint::markConstraintDirty() -{ +void Constraint::markConstraintDirty() { parent()->as<TransformComponent>()->markTransformDirty(); } void Constraint::strengthChanged() { markConstraintDirty(); } -void Constraint::buildDependencies() -{ +void Constraint::buildDependencies() { Super::buildDependencies(); parent()->addDependent(this); } -void Constraint::onDirty(ComponentDirt dirt) -{ +void Constraint::onDirty(ComponentDirt dirt) { // Whenever the constraint gets any dirt, make sure to mark the constrained // component dirty. markConstraintDirty(); } static Mat2D identity; -const Mat2D& rive::getParentWorld(const TransformComponent& component) -{ +const Mat2D& rive::getParentWorld(const TransformComponent& component) { auto parent = component.parent(); - if (parent->is<WorldTransformComponent>()) - { + if (parent->is<WorldTransformComponent>()) { return parent->as<WorldTransformComponent>()->worldTransform(); } return identity;
diff --git a/src/constraints/distance_constraint.cpp b/src/constraints/distance_constraint.cpp index e93ce59..186a523 100644 --- a/src/constraints/distance_constraint.cpp +++ b/src/constraints/distance_constraint.cpp
@@ -5,17 +5,10 @@ using namespace rive; -enum class Mode -{ - Closer = 0, - Further = 1, - Exact = 2 -}; +enum class Mode { Closer = 0, Further = 1, Exact = 2 }; -void DistanceConstraint::constrain(TransformComponent* component) -{ - if (m_Target == nullptr) - { +void DistanceConstraint::constrain(TransformComponent* component) { + if (m_Target == nullptr) { return; } @@ -28,25 +21,21 @@ Vec2D toTarget; Vec2D::subtract(toTarget, ourTranslation, targetTranslation); float currentDistance = Vec2D::length(toTarget); - switch (static_cast<Mode>(modeValue())) - { + switch (static_cast<Mode>(modeValue())) { case Mode::Closer: - if (currentDistance < distance()) - { + if (currentDistance < distance()) { return; } break; case Mode::Further: - if (currentDistance > distance()) - { + if (currentDistance > distance()) { return; } break; default: break; } - if (currentDistance < 0.001f) - { + if (currentDistance < 0.001f) { return; }
diff --git a/src/constraints/ik_constraint.cpp b/src/constraints/ik_constraint.cpp index 568946a..be80b26 100644 --- a/src/constraints/ik_constraint.cpp +++ b/src/constraints/ik_constraint.cpp
@@ -6,10 +6,8 @@ using namespace rive; -StatusCode IKConstraint::onAddedClean(CoreContext* context) -{ - if (!parent()->is<Bone>()) - { +StatusCode IKConstraint::onAddedClean(CoreContext* context) { + if (!parent()->is<Bone>()) { return StatusCode::InvalidObject; } @@ -18,8 +16,7 @@ std::vector<Bone*> bones; bones.push_back(bone); // Get the reverse FK chain of bones (from tip up). - while (bone->parent()->is<Bone>() && boneCount > 0) - { + while (bone->parent()->is<Bone>() && boneCount > 0) { boneCount--; bone = bone->parent()->as<Bone>(); bone->addPeerConstraint(this); @@ -29,8 +26,7 @@ m_FkChain.resize(numBones); // Now put them in FK order (top to bottom). int idx = 0; - for (auto boneItr = bones.rbegin(); boneItr != bones.rend(); ++boneItr) - { + for (auto boneItr = bones.rbegin(); boneItr != bones.rend(); ++boneItr) { BoneChainLink& link = m_FkChain[idx]; link.index = idx++; link.bone = *boneItr; @@ -46,16 +42,13 @@ // Find all children of this bone (we don't directly build up // hierarchy at runtime, so we have to traverse everything and check // parents). - for (auto core : artboard->objects()) - { - if (core == nullptr || !core->is<TransformComponent>()) - { + for (auto core : artboard->objects()) { + if (core == nullptr || !core->is<TransformComponent>()) { continue; } auto transformComponent = core->as<TransformComponent>(); - for (int i = 1; i < numBones; i++) - { + for (int i = 1; i < numBones; i++) { auto bone = bones[i]; if (transformComponent->parent() == bone && std::find(bones.begin(), bones.end(), transformComponent) == @@ -68,21 +61,18 @@ return Super::onAddedClean(context); } -void IKConstraint::markConstraintDirty() -{ +void IKConstraint::markConstraintDirty() { Super::markConstraintDirty(); // We automatically propagate dirt to the parent constrained bone, but we // also need to make sure the other bones we influence above it rebuild // their transforms. - for (int i = 0, length = (int)m_FkChain.size() - 1; i < length; i++) - { + for (int i = 0, length = (int)m_FkChain.size() - 1; i < length; i++) { m_FkChain[i].bone->markTransformDirty(); } } void IKConstraint::solve1(BoneChainLink* fk1, - const Vec2D& worldTargetTranslation) -{ + const Vec2D& worldTargetTranslation) { Mat2D iworld = fk1->parentWorldInverse; Vec2D pA; fk1->bone->worldTranslation(pA); @@ -103,8 +93,7 @@ void IKConstraint::solve2(BoneChainLink* fk1, BoneChainLink* fk2, - const Vec2D& worldTargetTranslation) -{ + const Vec2D& worldTargetTranslation) { Bone* b1 = fk1->bone; Bone* b2 = fk2->bone; BoneChainLink* firstChild = &(m_FkChain[fk1->index + 1]); @@ -139,8 +128,7 @@ -1.0f, std::min(1.0f, (a * a + b * b - c * c) / (2.0f * a * b)))); float r1, r2; - if (b2->parent() != b1) - { + if (b2->parent() != b1) { BoneChainLink& secondChild = m_FkChain[fk1->index + 2]; const Mat2D& secondChildWorldInverse = secondChild.parentWorldInverse; @@ -154,32 +142,24 @@ Vec2D::transformDir(avLocal, avec, secondChildWorldInverse); float angleCorrection = -std::atan2(avLocal[1], avLocal[0]); - if (invertDirection()) - { + if (invertDirection()) { r1 = std::atan2(cv[1], cv[0]) - A; r2 = -C + M_PI + angleCorrection; - } - else - { + } else { r1 = A + std::atan2(cv[1], cv[0]); r2 = C - M_PI + angleCorrection; } - } - else if (invertDirection()) - { + } else if (invertDirection()) { r1 = std::atan2(cv[1], cv[0]) - A; r2 = -C + M_PI; - } - else - { + } else { r1 = A + std::atan2(cv[1], cv[0]); r2 = C - M_PI; } constrainRotation(*fk1, r1); constrainRotation(*firstChild, r2); - if (firstChild != fk2) - { + if (firstChild != fk2) { Bone* bone = fk2->bone; Mat2D::multiply(bone->mutableWorldTransform(), getParentWorld(*bone), @@ -191,19 +171,15 @@ firstChild->angle = r2; } -void IKConstraint::constrainRotation(BoneChainLink& fk, float rotation) -{ +void IKConstraint::constrainRotation(BoneChainLink& fk, float rotation) { Bone* bone = fk.bone; const Mat2D& parentWorld = getParentWorld(*bone); Mat2D& transform = bone->mutableTransform(); TransformComponents& c = fk.transformComponents; - if (rotation == 0.0f) - { + if (rotation == 0.0f) { Mat2D::identity(transform); - } - else - { + } else { Mat2D::fromRotation(transform, rotation); } @@ -220,8 +196,7 @@ // Skew const float skew = c.skew(); - if (skew != 0.0f) - { + if (skew != 0.0f) { transform[2] = transform[0] * skew + transform[2]; transform[3] = transform[1] * skew + transform[3]; } @@ -229,10 +204,8 @@ Mat2D::multiply(bone->mutableWorldTransform(), parentWorld, transform); } -void IKConstraint::constrain(TransformComponent* component) -{ - if (m_Target == nullptr) - { +void IKConstraint::constrain(TransformComponent* component) { + if (m_Target == nullptr) { return; } @@ -240,8 +213,7 @@ m_Target->worldTranslation(worldTargetTranslation); // Decompose the chain. - for (BoneChainLink& item : m_FkChain) - { + for (BoneChainLink& item : m_FkChain) { auto bone = item.bone; const Mat2D& parentWorld = getParentWorld(*bone); Mat2D::invert(item.parentWorldInverse, parentWorld); @@ -253,26 +225,22 @@ } int count = (int)m_FkChain.size(); - switch (count) - { + switch (count) { case 1: solve1(&m_FkChain[0], worldTargetTranslation); break; case 2: solve2(&m_FkChain[0], &m_FkChain[1], worldTargetTranslation); break; - default: - { + default: { auto last = count - 1; BoneChainLink* tip = &m_FkChain[last]; - for (int i = 0; i < last; i++) - { + for (int i = 0; i < last; i++) { BoneChainLink* item = &m_FkChain[i]; solve2(item, tip, worldTargetTranslation); for (int j = item->index + 1, end = m_FkChain.size() - 1; j < end; - j++) - { + j++) { BoneChainLink& fk = m_FkChain[j]; Mat2D::invert(fk.parentWorldInverse, getParentWorld(*fk.bone)); @@ -282,20 +250,15 @@ } } // At the end, mix the FK angle with the IK angle by strength - if (strength() != 1.0f) - { - for (BoneChainLink& fk : m_FkChain) - { + if (strength() != 1.0f) { + for (BoneChainLink& fk : m_FkChain) { float fromAngle = std::fmod(fk.transformComponents.rotation(), (float)M_PI * 2); float toAngle = std::fmod(fk.angle, (float)M_PI * 2); float diff = toAngle - fromAngle; - if (diff > M_PI) - { + if (diff > M_PI) { diff -= M_PI * 2; - } - else if (diff < -M_PI) - { + } else if (diff < -M_PI) { diff += M_PI * 2; } float angle = fromAngle + diff * strength();
diff --git a/src/constraints/rotation_constraint.cpp b/src/constraints/rotation_constraint.cpp index 728b09c..08fc61c 100644 --- a/src/constraints/rotation_constraint.cpp +++ b/src/constraints/rotation_constraint.cpp
@@ -5,25 +5,19 @@ using namespace rive; -void RotationConstraint::constrain(TransformComponent* component) -{ +void RotationConstraint::constrain(TransformComponent* component) { const Mat2D& transformA = component->worldTransform(); Mat2D transformB; Mat2D::decompose(m_ComponentsA, transformA); - if (m_Target == nullptr) - { + if (m_Target == nullptr) { Mat2D::copy(transformB, transformA); TransformComponents::copy(m_ComponentsB, m_ComponentsA); - } - else - { + } else { Mat2D::copy(transformB, m_Target->worldTransform()); - if (sourceSpace() == TransformSpace::local) - { + if (sourceSpace() == TransformSpace::local) { Mat2D inverse; - if (!Mat2D::invert(inverse, getParentWorld(*m_Target))) - { + if (!Mat2D::invert(inverse, getParentWorld(*m_Target))) { return; } Mat2D::multiply(transformB, inverse, transformB); @@ -31,24 +25,19 @@ Mat2D::decompose(m_ComponentsB, transformB); - if (!doesCopy()) - { + if (!doesCopy()) { m_ComponentsB.rotation(destSpace() == TransformSpace::local ? 0.0f : m_ComponentsA.rotation()); - } - else - { + } else { m_ComponentsB.rotation(m_ComponentsB.rotation() * copyFactor()); - if (offset()) - { + if (offset()) { m_ComponentsB.rotation(m_ComponentsB.rotation() + component->rotation()); } } - if (destSpace() == TransformSpace::local) - { + if (destSpace() == TransformSpace::local) { // Destination space is in parent transform coordinates. Recompose // the parent local transform and get it in world, then decompose // the world for interpolation. @@ -59,29 +48,24 @@ } } bool clampLocal = minMaxSpace() == TransformSpace::local; - if (clampLocal) - { + if (clampLocal) { // Apply min max in local space, so transform to local coordinates // first. Mat2D::compose(transformB, m_ComponentsB); Mat2D inverse = Mat2D(); - if (!Mat2D::invert(inverse, getParentWorld(*component))) - { + if (!Mat2D::invert(inverse, getParentWorld(*component))) { return; } Mat2D::multiply(transformB, inverse, transformB); Mat2D::decompose(m_ComponentsB, transformB); } - if (max() && m_ComponentsB.rotation() > maxValue()) - { + if (max() && m_ComponentsB.rotation() > maxValue()) { m_ComponentsB.rotation(maxValue()); } - if (min() && m_ComponentsB.rotation() < minValue()) - { + if (min() && m_ComponentsB.rotation() < minValue()) { m_ComponentsB.rotation(minValue()); } - if (clampLocal) - { + if (clampLocal) { // Transform back to world. Mat2D::compose(transformB, m_ComponentsB); Mat2D::multiply(transformB, getParentWorld(*component), transformB); @@ -92,12 +76,9 @@ float angleB = std::fmod(m_ComponentsB.rotation(), (float)M_PI * 2); float diff = angleB - angleA; - if (diff > M_PI) - { + if (diff > M_PI) { diff -= M_PI * 2; - } - else if (diff < -M_PI) - { + } else if (diff < -M_PI) { diff += M_PI * 2; }
diff --git a/src/constraints/scale_constraint.cpp b/src/constraints/scale_constraint.cpp index 176321c..87208a0 100644 --- a/src/constraints/scale_constraint.cpp +++ b/src/constraints/scale_constraint.cpp
@@ -5,64 +5,49 @@ using namespace rive; -void ScaleConstraint::constrain(TransformComponent* component) -{ +void ScaleConstraint::constrain(TransformComponent* component) { const Mat2D& transformA = component->worldTransform(); Mat2D transformB; Mat2D::decompose(m_ComponentsA, transformA); - if (m_Target == nullptr) - { + if (m_Target == nullptr) { Mat2D::copy(transformB, transformA); TransformComponents::copy(m_ComponentsB, m_ComponentsA); - } - else - { + } else { Mat2D::copy(transformB, m_Target->worldTransform()); - if (sourceSpace() == TransformSpace::local) - { + if (sourceSpace() == TransformSpace::local) { Mat2D inverse; - if (!Mat2D::invert(inverse, getParentWorld(*m_Target))) - { + if (!Mat2D::invert(inverse, getParentWorld(*m_Target))) { return; } Mat2D::multiply(transformB, inverse, transformB); } Mat2D::decompose(m_ComponentsB, transformB); - if (!doesCopy()) - { + if (!doesCopy()) { m_ComponentsB.scaleX(destSpace() == TransformSpace::local ? 1.0f : m_ComponentsA.scaleX()); - } - else - { + } else { m_ComponentsB.scaleX(m_ComponentsB.scaleX() * copyFactor()); - if (offset()) - { + if (offset()) { m_ComponentsB.scaleX(m_ComponentsB.scaleX() * component->scaleX()); } } - if (!doesCopyY()) - { + if (!doesCopyY()) { m_ComponentsB.scaleY(destSpace() == TransformSpace::local ? 1.0f : m_ComponentsA.scaleY()); - } - else - { + } else { m_ComponentsB.scaleY(m_ComponentsB.scaleY() * copyFactorY()); - if (offset()) - { + if (offset()) { m_ComponentsB.scaleY(m_ComponentsB.scaleY() * component->scaleY()); } } - if (destSpace() == TransformSpace::local) - { + if (destSpace() == TransformSpace::local) { // Destination space is in parent transform coordinates. Recompose // the parent local transform and get it in world, then decompose // the world for interpolation. @@ -74,37 +59,30 @@ } bool clamplocal = minMaxSpace() == TransformSpace::local; - if (clamplocal) - { + if (clamplocal) { // Apply min max in local space, so transform to local coordinates // first. Mat2D::compose(transformB, m_ComponentsB); Mat2D inverse; - if (!Mat2D::invert(inverse, getParentWorld(*component))) - { + if (!Mat2D::invert(inverse, getParentWorld(*component))) { return; } Mat2D::multiply(transformB, inverse, transformB); Mat2D::decompose(m_ComponentsB, transformB); } - if (max() && m_ComponentsB.scaleX() > maxValue()) - { + if (max() && m_ComponentsB.scaleX() > maxValue()) { m_ComponentsB.scaleX(maxValue()); } - if (min() && m_ComponentsB.scaleX() < minValue()) - { + if (min() && m_ComponentsB.scaleX() < minValue()) { m_ComponentsB.scaleX(minValue()); } - if (maxY() && m_ComponentsB.scaleY() > maxValueY()) - { + if (maxY() && m_ComponentsB.scaleY() > maxValueY()) { m_ComponentsB.scaleY(maxValueY()); } - if (minY() && m_ComponentsB.scaleY() < minValueY()) - { + if (minY() && m_ComponentsB.scaleY() < minValueY()) { m_ComponentsB.scaleY(minValueY()); } - if (clamplocal) - { + if (clamplocal) { // Transform back to world. Mat2D::compose(transformB, m_ComponentsB); Mat2D::multiply(transformB, getParentWorld(*component), transformB);
diff --git a/src/constraints/targeted_constraint.cpp b/src/constraints/targeted_constraint.cpp index 2daaa29..9f7802e 100644 --- a/src/constraints/targeted_constraint.cpp +++ b/src/constraints/targeted_constraint.cpp
@@ -4,16 +4,13 @@ using namespace rive; -StatusCode TargetedConstraint::onAddedDirty(CoreContext* context) -{ +StatusCode TargetedConstraint::onAddedDirty(CoreContext* context) { StatusCode code = Super::onAddedDirty(context); - if (code != StatusCode::Ok) - { + if (code != StatusCode::Ok) { return code; } auto coreObject = context->resolve(targetId()); - if (coreObject == nullptr || !coreObject->is<TransformComponent>()) - { + if (coreObject == nullptr || !coreObject->is<TransformComponent>()) { return StatusCode::MissingObject; } @@ -22,12 +19,10 @@ return StatusCode::Ok; } -void TargetedConstraint::buildDependencies() -{ +void TargetedConstraint::buildDependencies() { // Targeted constraints must have their constrained component (parent) // update after the target. - if (m_Target != nullptr) - { + if (m_Target != nullptr) { m_Target->addDependent(parent()); } } \ No newline at end of file
diff --git a/src/constraints/transform_constraint.cpp b/src/constraints/transform_constraint.cpp index 9c4f756..0e9df72 100644 --- a/src/constraints/transform_constraint.cpp +++ b/src/constraints/transform_constraint.cpp
@@ -5,28 +5,23 @@ using namespace rive; -void TransformConstraint::constrain(TransformComponent* component) -{ - if (m_Target == nullptr) - { +void TransformConstraint::constrain(TransformComponent* component) { + if (m_Target == nullptr) { return; } const Mat2D& transformA = component->worldTransform(); Mat2D transformB(m_Target->worldTransform()); - if (sourceSpace() == TransformSpace::local) - { + if (sourceSpace() == TransformSpace::local) { const Mat2D& targetParentWorld = getParentWorld(*m_Target); Mat2D inverse; - if (!Mat2D::invert(inverse, targetParentWorld)) - { + if (!Mat2D::invert(inverse, targetParentWorld)) { return; } Mat2D::multiply(transformB, inverse, transformB); } - if (destSpace() == TransformSpace::local) - { + if (destSpace() == TransformSpace::local) { const Mat2D& targetParentWorld = getParentWorld(*component); Mat2D::multiply(transformB, targetParentWorld, transformB); } @@ -37,12 +32,9 @@ float angleA = std::fmod(m_ComponentsA.rotation(), (float)M_PI * 2); float angleB = std::fmod(m_ComponentsB.rotation(), (float)M_PI * 2); float diff = angleB - angleA; - if (diff > M_PI) - { + if (diff > M_PI) { diff -= M_PI * 2; - } - else if (diff < -M_PI) - { + } else if (diff < -M_PI) { diff += M_PI * 2; }
diff --git a/src/constraints/translation_constraint.cpp b/src/constraints/translation_constraint.cpp index 308c82b..db2db8a 100644 --- a/src/constraints/translation_constraint.cpp +++ b/src/constraints/translation_constraint.cpp
@@ -6,25 +6,19 @@ using namespace rive; -void TranslationConstraint::constrain(TransformComponent* component) -{ +void TranslationConstraint::constrain(TransformComponent* component) { Mat2D& transformA = component->mutableWorldTransform(); Vec2D translationA(transformA[4], transformA[5]); Vec2D translationB; - if (m_Target == nullptr) - { + if (m_Target == nullptr) { Vec2D::copy(translationB, translationA); - } - else - { + } else { Mat2D transformB(m_Target->worldTransform()); - if (sourceSpace() == TransformSpace::local) - { + if (sourceSpace() == TransformSpace::local) { const Mat2D& targetParentWorld = getParentWorld(*m_Target); Mat2D inverse; - if (!Mat2D::invert(inverse, targetParentWorld)) - { + if (!Mat2D::invert(inverse, targetParentWorld)) { return; } Mat2D::multiply(transformB, inverse, transformB); @@ -32,37 +26,28 @@ translationB[0] = transformB[4]; translationB[1] = transformB[5]; - if (!doesCopy()) - { + if (!doesCopy()) { translationB[0] = destSpace() == TransformSpace::local ? 0.0f : translationA[0]; - } - else - { + } else { translationB[0] *= copyFactor(); - if (offset()) - { + if (offset()) { translationB[0] += component->x(); } } - if (!doesCopyY()) - { + if (!doesCopyY()) { translationB[1] = destSpace() == TransformSpace::local ? 0.0f : translationA[1]; - } - else - { + } else { translationB[1] *= copyFactorY(); - if (offset()) - { + if (offset()) { translationB[1] += component->y(); } } - if (destSpace() == TransformSpace::local) - { + if (destSpace() == TransformSpace::local) { // Destination space is in parent transform coordinates. Vec2D::transform( translationB, translationB, getParentWorld(*component)); @@ -70,36 +55,29 @@ } bool clampLocal = minMaxSpace() == TransformSpace::local; - if (clampLocal) - { + if (clampLocal) { // Apply min max in local space, so transform to local coordinates // first. Mat2D invert; - if (!Mat2D::invert(invert, getParentWorld(*component))) - { + if (!Mat2D::invert(invert, getParentWorld(*component))) { return; } // Get our target world coordinates in parent local. Vec2D::transform(translationB, translationB, invert); } - if (max() && translationB[0] > maxValue()) - { + if (max() && translationB[0] > maxValue()) { translationB[0] = maxValue(); } - if (min() && translationB[0] < minValue()) - { + if (min() && translationB[0] < minValue()) { translationB[0] = minValue(); } - if (maxY() && translationB[1] > maxValueY()) - { + if (maxY() && translationB[1] > maxValueY()) { translationB[1] = maxValueY(); } - if (minY() && translationB[1] < minValueY()) - { + if (minY() && translationB[1] < minValueY()) { translationB[1] = minValueY(); } - if (clampLocal) - { + if (clampLocal) { // Transform back to world. Vec2D::transform( translationB, translationB, getParentWorld(*component));
diff --git a/src/core/binary_reader.cpp b/src/core/binary_reader.cpp index 175db50..c5e31e4 100644 --- a/src/core/binary_reader.cpp +++ b/src/core/binary_reader.cpp
@@ -8,12 +8,9 @@ m_Position(bytes), m_End(bytes + length), m_Overflowed(false), - m_Length(length) -{ -} + m_Length(length) {} -bool BinaryReader::reachedEnd() const -{ +bool BinaryReader::reachedEnd() const { return m_Position == m_End || didOverflow(); } @@ -21,18 +18,15 @@ bool BinaryReader::didOverflow() const { return m_Overflowed; } -void BinaryReader::overflow() -{ +void BinaryReader::overflow() { m_Overflowed = true; m_Position = m_End; } -uint64_t BinaryReader::readVarUint64() -{ +uint64_t BinaryReader::readVarUint64() { uint64_t value; auto readBytes = decode_uint_leb(m_Position, m_End, &value); - if (readBytes == 0) - { + if (readBytes == 0) { overflow(); return 0; } @@ -40,18 +34,15 @@ return value; } -std::string BinaryReader::readString() -{ +std::string BinaryReader::readString() { uint64_t length = readVarUint64(); - if (didOverflow()) - { + if (didOverflow()) { return std::string(); } std::vector<char> rawValue(length + 1); auto readBytes = decode_string(length, m_Position, m_End, &rawValue[0]); - if (readBytes != length) - { + if (readBytes != length) { overflow(); return std::string(); } @@ -59,11 +50,9 @@ return std::string(rawValue.data(), length); } -std::vector<uint8_t> BinaryReader::readBytes() -{ +std::vector<uint8_t> BinaryReader::readBytes() { uint64_t length = readVarUint64(); - if (didOverflow()) - { + if (didOverflow()) { return std::vector<uint8_t>(); } @@ -72,12 +61,10 @@ return std::vector<uint8_t>(start, start + length); } -double BinaryReader::readFloat64() -{ +double BinaryReader::readFloat64() { double value; auto readBytes = decode_double(m_Position, m_End, &value); - if (readBytes == 0) - { + if (readBytes == 0) { overflow(); return 0.0; } @@ -85,12 +72,10 @@ return value; } -float BinaryReader::readFloat32() -{ +float BinaryReader::readFloat32() { float value; auto readBytes = decode_float(m_Position, m_End, &value); - if (readBytes == 0) - { + if (readBytes == 0) { overflow(); return 0.0f; } @@ -98,22 +83,18 @@ return value; } -uint8_t BinaryReader::readByte() -{ - if (m_End - m_Position < 1) - { +uint8_t BinaryReader::readByte() { + if (m_End - m_Position < 1) { overflow(); return 0; } return *m_Position++; } -uint32_t BinaryReader::readUint32() -{ +uint32_t BinaryReader::readUint32() { uint32_t value; auto readBytes = decode_uint_32(m_Position, m_End, &value); - if (readBytes == 0) - { + if (readBytes == 0) { overflow(); return 0; }
diff --git a/src/core/field_types/core_bool_type.cpp b/src/core/field_types/core_bool_type.cpp index d738b74..8672715 100644 --- a/src/core/field_types/core_bool_type.cpp +++ b/src/core/field_types/core_bool_type.cpp
@@ -3,7 +3,6 @@ using namespace rive; -bool CoreBoolType::deserialize(BinaryReader& reader) -{ +bool CoreBoolType::deserialize(BinaryReader& reader) { return reader.readByte() == 1; } \ No newline at end of file
diff --git a/src/core/field_types/core_bytes_type.cpp b/src/core/field_types/core_bytes_type.cpp index 87837e4..68f7d8b 100644 --- a/src/core/field_types/core_bytes_type.cpp +++ b/src/core/field_types/core_bytes_type.cpp
@@ -3,7 +3,6 @@ using namespace rive; -std::vector<uint8_t> CoreBytesType::deserialize(BinaryReader& reader) -{ +std::vector<uint8_t> CoreBytesType::deserialize(BinaryReader& reader) { return reader.readBytes(); } \ No newline at end of file
diff --git a/src/core/field_types/core_color_type.cpp b/src/core/field_types/core_color_type.cpp index 2809d4f..b87ffbd 100644 --- a/src/core/field_types/core_color_type.cpp +++ b/src/core/field_types/core_color_type.cpp
@@ -3,7 +3,6 @@ using namespace rive; -int CoreColorType::deserialize(BinaryReader& reader) -{ +int CoreColorType::deserialize(BinaryReader& reader) { return reader.readUint32(); } \ No newline at end of file
diff --git a/src/core/field_types/core_double_type.cpp b/src/core/field_types/core_double_type.cpp index 2843ef7..73ab59d 100644 --- a/src/core/field_types/core_double_type.cpp +++ b/src/core/field_types/core_double_type.cpp
@@ -3,7 +3,6 @@ using namespace rive; -double CoreDoubleType::deserialize(BinaryReader& reader) -{ +double CoreDoubleType::deserialize(BinaryReader& reader) { return reader.readFloat32(); } \ No newline at end of file
diff --git a/src/core/field_types/core_string_type.cpp b/src/core/field_types/core_string_type.cpp index c9d7ed0..f16f74f 100644 --- a/src/core/field_types/core_string_type.cpp +++ b/src/core/field_types/core_string_type.cpp
@@ -3,7 +3,6 @@ using namespace rive; -std::string CoreStringType::deserialize(BinaryReader& reader) -{ +std::string CoreStringType::deserialize(BinaryReader& reader) { return reader.readString(); } \ No newline at end of file
diff --git a/src/core/field_types/core_uint_type.cpp b/src/core/field_types/core_uint_type.cpp index b9e6758..ce9eea7 100644 --- a/src/core/field_types/core_uint_type.cpp +++ b/src/core/field_types/core_uint_type.cpp
@@ -3,7 +3,6 @@ using namespace rive; -unsigned int CoreUintType::deserialize(BinaryReader& reader) -{ +unsigned int CoreUintType::deserialize(BinaryReader& reader) { return (int)reader.readVarUint64(); }
diff --git a/src/dependency_sorter.cpp b/src/dependency_sorter.cpp index 42b4e0a..711b3fe 100644 --- a/src/dependency_sorter.cpp +++ b/src/dependency_sorter.cpp
@@ -3,21 +3,17 @@ using namespace rive; -void DependencySorter::sort(Component* root, std::vector<Component*>& order) -{ +void DependencySorter::sort(Component* root, std::vector<Component*>& order) { order.clear(); visit(root, order); } bool DependencySorter::visit(Component* component, - std::vector<Component*>& order) -{ - if (m_Perm.find(component) != m_Perm.end()) - { + std::vector<Component*>& order) { + if (m_Perm.find(component) != m_Perm.end()) { return true; } - if (m_Temp.find(component) != m_Temp.end()) - { + if (m_Temp.find(component) != m_Temp.end()) { fprintf(stderr, "Dependency cycle!\n"); return false; } @@ -25,10 +21,8 @@ m_Temp.emplace(component); auto dependents = component->dependents(); - for (auto dependent : dependents) - { - if (!visit(dependent, order)) - { + for (auto dependent : dependents) { + if (!visit(dependent, order)) { return false; } }
diff --git a/src/draw_rules.cpp b/src/draw_rules.cpp index 5f4a1cb..b29a0eb 100644 --- a/src/draw_rules.cpp +++ b/src/draw_rules.cpp
@@ -5,36 +5,28 @@ using namespace rive; -StatusCode DrawRules::onAddedDirty(CoreContext* context) -{ +StatusCode DrawRules::onAddedDirty(CoreContext* context) { StatusCode result = Super::onAddedDirty(context); - if (result != StatusCode::Ok) - { + if (result != StatusCode::Ok) { return result; } auto coreObject = context->resolve(drawTargetId()); - if (coreObject != nullptr && coreObject->is<DrawTarget>()) - { + if (coreObject != nullptr && coreObject->is<DrawTarget>()) { m_ActiveTarget = reinterpret_cast<DrawTarget*>(coreObject); } return StatusCode::Ok; } -StatusCode DrawRules::onAddedClean(CoreContext* context) -{ +StatusCode DrawRules::onAddedClean(CoreContext* context) { return StatusCode::Ok; } -void DrawRules::drawTargetIdChanged() -{ +void DrawRules::drawTargetIdChanged() { auto coreObject = artboard()->resolve(drawTargetId()); - if (coreObject == nullptr || !coreObject->is<DrawTarget>()) - { + if (coreObject == nullptr || !coreObject->is<DrawTarget>()) { m_ActiveTarget = nullptr; - } - else - { + } else { m_ActiveTarget = reinterpret_cast<DrawTarget*>(coreObject); } artboard()->addDirt(ComponentDirt::DrawOrder);
diff --git a/src/draw_target.cpp b/src/draw_target.cpp index 5281993..948d85b 100644 --- a/src/draw_target.cpp +++ b/src/draw_target.cpp
@@ -5,28 +5,23 @@ using namespace rive; -StatusCode DrawTarget::onAddedDirty(CoreContext* context) -{ +StatusCode DrawTarget::onAddedDirty(CoreContext* context) { StatusCode code = Super::onAddedDirty(context); - if (code != StatusCode::Ok) - { + if (code != StatusCode::Ok) { return code; } auto coreObject = context->resolve(drawableId()); - if (coreObject == nullptr || !coreObject->is<Drawable>()) - { + if (coreObject == nullptr || !coreObject->is<Drawable>()) { return StatusCode::MissingObject; } m_Drawable = reinterpret_cast<Drawable*>(coreObject); return StatusCode::Ok; } -StatusCode DrawTarget::onAddedClean(CoreContext* context) -{ +StatusCode DrawTarget::onAddedClean(CoreContext* context) { return StatusCode::Ok; } -void DrawTarget::placementValueChanged() -{ +void DrawTarget::placementValueChanged() { artboard()->addDirt(ComponentDirt::DrawOrder); } \ No newline at end of file
diff --git a/src/drawable.cpp b/src/drawable.cpp index ae0e408..fbc930d 100644 --- a/src/drawable.cpp +++ b/src/drawable.cpp
@@ -6,24 +6,19 @@ using namespace rive; -void Drawable::addClippingShape(ClippingShape* shape) -{ +void Drawable::addClippingShape(ClippingShape* shape) { m_ClippingShapes.push_back(shape); } -bool Drawable::clip(Renderer* renderer) const -{ - if (m_ClippingShapes.size() == 0) - { +bool Drawable::clip(Renderer* renderer) const { + if (m_ClippingShapes.size() == 0) { return false; } renderer->save(); - for (auto clippingShape : m_ClippingShapes) - { - if (!clippingShape->isVisible()) - { + for (auto clippingShape : m_ClippingShapes) { + if (!clippingShape->isVisible()) { continue; }
diff --git a/src/file.cpp b/src/file.cpp index b861363..b5174fe 100644 --- a/src/file.cpp +++ b/src/file.cpp
@@ -49,21 +49,17 @@ // Import a single Rive runtime object. // Used by the file importer. static Core* readRuntimeObject(BinaryReader& reader, - const RuntimeHeader& header) -{ + const RuntimeHeader& header) { auto coreObjectKey = reader.readVarUint64(); auto object = CoreRegistry::makeCoreInstance((int)coreObjectKey); - while (true) - { + while (true) { auto propertyKey = reader.readVarUint64(); - if (propertyKey == 0) - { + if (propertyKey == 0) { // Terminator. https://media.giphy.com/media/7TtvTUMm9mp20/giphy.gif break; } - if (reader.didOverflow()) - { + if (reader.didOverflow()) { delete object; return nullptr; } @@ -72,14 +68,12 @@ // We have an unknown object or property, first see if core knows // the property type. int id = CoreRegistry::propertyFieldId((int)propertyKey); - if (id == -1) - { + if (id == -1) { // No, check if it's in toc. id = header.propertyFieldId((int)propertyKey); } - if (id == -1) - { + if (id == -1) { // Still couldn't find it, give up. fprintf(stderr, "Unknown property key " RIVE_FMT_U64 @@ -89,8 +83,7 @@ return nullptr; } - switch (id) - { + switch (id) { case CoreUintType::id: CoreUintType::deserialize(reader); break; @@ -106,8 +99,7 @@ } } } - if (object == nullptr) - { + if (object == nullptr) { // fprintf(stderr, // "File contains an unknown object with coreType " RIVE_FMT_U64 // ", which " "this runtime doesn't understand.\n", @@ -119,10 +111,8 @@ File::File(FileAssetResolver* assetResolver) : m_AssetResolver(assetResolver) {} -File::~File() -{ - for (auto artboard : m_Artboards) - { +File::~File() { + for (auto artboard : m_Artboards) { delete artboard; } delete m_Backboard; @@ -131,16 +121,13 @@ // Import a Rive file from a file handle ImportResult File::import(BinaryReader& reader, File** importedFile, - FileAssetResolver* assetResolver) -{ + FileAssetResolver* assetResolver) { RuntimeHeader header; - if (!RuntimeHeader::read(reader, header)) - { + if (!RuntimeHeader::read(reader, header)) { fprintf(stderr, "Bad header\n"); return ImportResult::malformed; } - if (header.majorVersion() != majorVersion) - { + if (header.majorVersion() != majorVersion) { fprintf(stderr, "Unsupported version %u.%u expected %u.%u.\n", header.majorVersion(), @@ -151,8 +138,7 @@ } auto file = new File(assetResolver); auto result = file->read(reader, header); - if (result != ImportResult::success) - { + if (result != ImportResult::success) { delete file; return result; } @@ -160,21 +146,16 @@ return result; } -ImportResult File::read(BinaryReader& reader, const RuntimeHeader& header) -{ +ImportResult File::read(BinaryReader& reader, const RuntimeHeader& header) { ImportStack importStack; - while (!reader.reachedEnd()) - { + while (!reader.reachedEnd()) { auto object = readRuntimeObject(reader, header); - if (object == nullptr) - { + if (object == nullptr) { importStack.readNullObject(); continue; } - if (object->import(importStack) == StatusCode::Ok) - { - switch (object->coreType()) - { + if (object->import(importStack) == StatusCode::Ok) { + switch (object->coreType()) { case Backboard::typeKey: m_Backboard = object->as<Backboard>(); break; @@ -182,9 +163,7 @@ m_Artboards.push_back(object->as<Artboard>()); break; } - } - else - { + } else { fprintf(stderr, "Failed to import object of type %d\n", object->coreType()); @@ -194,8 +173,7 @@ ImportStackObject* stackObject = nullptr; auto stackType = object->coreType(); - switch (stackType) - { + switch (stackType) { case Backboard::typeKey: stackObject = new BackboardImporter(object->as<Backboard>()); break; @@ -210,12 +188,10 @@ stackObject = new KeyedObjectImporter(object->as<KeyedObject>()); break; - case KeyedProperty::typeKey: - { + case KeyedProperty::typeKey: { auto importer = importStack.latest<LinearAnimationImporter>( LinearAnimation::typeKey); - if (importer == nullptr) - { + if (importer == nullptr) { return ImportResult::malformed; } stackObject = new KeyedPropertyImporter( @@ -226,12 +202,10 @@ stackObject = new StateMachineImporter(object->as<StateMachine>()); break; - case StateMachineLayer::typeKey: - { + case StateMachineLayer::typeKey: { auto artboardImporter = importStack.latest<ArtboardImporter>(ArtboardBase::typeKey); - if (artboardImporter == nullptr) - { + if (artboardImporter == nullptr) { return ImportResult::malformed; } @@ -262,8 +236,7 @@ stackType = FileAsset::typeKey; break; } - if (importStack.makeLatest(stackType, stackObject) != StatusCode::Ok) - { + if (importStack.makeLatest(stackType, stackObject) != StatusCode::Ok) { // Some previous stack item didn't resolve. return ImportResult::malformed; } @@ -275,31 +248,24 @@ Backboard* File::backboard() const { return m_Backboard; } -Artboard* File::artboard(std::string name) const -{ - for (auto artboard : m_Artboards) - { - if (artboard->name() == name) - { +Artboard* File::artboard(std::string name) const { + for (auto artboard : m_Artboards) { + if (artboard->name() == name) { return artboard; } } return nullptr; } -Artboard* File::artboard() const -{ - if (m_Artboards.empty()) - { +Artboard* File::artboard() const { + if (m_Artboards.empty()) { return nullptr; } return m_Artboards[0]; } -Artboard* File::artboard(size_t index) const -{ - if (index >= m_Artboards.size()) - { +Artboard* File::artboard(size_t index) const { + if (index >= m_Artboards.size()) { return nullptr; } return m_Artboards[index];
diff --git a/src/generated/animation/animation_base.cpp b/src/generated/animation/animation_base.cpp index e832aeb..81aef8c 100644 --- a/src/generated/animation/animation_base.cpp +++ b/src/generated/animation/animation_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* AnimationBase::clone() const -{ +Core* AnimationBase::clone() const { auto cloned = new Animation(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/animation_state_base.cpp b/src/generated/animation/animation_state_base.cpp index 922ea8e..299adb6 100644 --- a/src/generated/animation/animation_state_base.cpp +++ b/src/generated/animation/animation_state_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* AnimationStateBase::clone() const -{ +Core* AnimationStateBase::clone() const { auto cloned = new AnimationState(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/any_state_base.cpp b/src/generated/animation/any_state_base.cpp index 54b2a42..b590058 100644 --- a/src/generated/animation/any_state_base.cpp +++ b/src/generated/animation/any_state_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* AnyStateBase::clone() const -{ +Core* AnyStateBase::clone() const { auto cloned = new AnyState(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/blend_animation_1d_base.cpp b/src/generated/animation/blend_animation_1d_base.cpp index a04b71f..ee1a1c4 100644 --- a/src/generated/animation/blend_animation_1d_base.cpp +++ b/src/generated/animation/blend_animation_1d_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* BlendAnimation1DBase::clone() const -{ +Core* BlendAnimation1DBase::clone() const { auto cloned = new BlendAnimation1D(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/blend_animation_direct_base.cpp b/src/generated/animation/blend_animation_direct_base.cpp index 98bd50a..af0bec8 100644 --- a/src/generated/animation/blend_animation_direct_base.cpp +++ b/src/generated/animation/blend_animation_direct_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* BlendAnimationDirectBase::clone() const -{ +Core* BlendAnimationDirectBase::clone() const { auto cloned = new BlendAnimationDirect(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/blend_state_1d_base.cpp b/src/generated/animation/blend_state_1d_base.cpp index 3a287ec..b866eb4 100644 --- a/src/generated/animation/blend_state_1d_base.cpp +++ b/src/generated/animation/blend_state_1d_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* BlendState1DBase::clone() const -{ +Core* BlendState1DBase::clone() const { auto cloned = new BlendState1D(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/blend_state_direct_base.cpp b/src/generated/animation/blend_state_direct_base.cpp index a0349bc..1f2e64d 100644 --- a/src/generated/animation/blend_state_direct_base.cpp +++ b/src/generated/animation/blend_state_direct_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* BlendStateDirectBase::clone() const -{ +Core* BlendStateDirectBase::clone() const { auto cloned = new BlendStateDirect(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/blend_state_transition_base.cpp b/src/generated/animation/blend_state_transition_base.cpp index a4b74d4..6b361e1 100644 --- a/src/generated/animation/blend_state_transition_base.cpp +++ b/src/generated/animation/blend_state_transition_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* BlendStateTransitionBase::clone() const -{ +Core* BlendStateTransitionBase::clone() const { auto cloned = new BlendStateTransition(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/cubic_interpolator_base.cpp b/src/generated/animation/cubic_interpolator_base.cpp index 24eb158..75a2ceb 100644 --- a/src/generated/animation/cubic_interpolator_base.cpp +++ b/src/generated/animation/cubic_interpolator_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* CubicInterpolatorBase::clone() const -{ +Core* CubicInterpolatorBase::clone() const { auto cloned = new CubicInterpolator(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/entry_state_base.cpp b/src/generated/animation/entry_state_base.cpp index 68ec90e..126024c 100644 --- a/src/generated/animation/entry_state_base.cpp +++ b/src/generated/animation/entry_state_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* EntryStateBase::clone() const -{ +Core* EntryStateBase::clone() const { auto cloned = new EntryState(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/exit_state_base.cpp b/src/generated/animation/exit_state_base.cpp index 12f5ad5..3991967 100644 --- a/src/generated/animation/exit_state_base.cpp +++ b/src/generated/animation/exit_state_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* ExitStateBase::clone() const -{ +Core* ExitStateBase::clone() const { auto cloned = new ExitState(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/keyed_object_base.cpp b/src/generated/animation/keyed_object_base.cpp index 57cb7a2..f3c108c 100644 --- a/src/generated/animation/keyed_object_base.cpp +++ b/src/generated/animation/keyed_object_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* KeyedObjectBase::clone() const -{ +Core* KeyedObjectBase::clone() const { auto cloned = new KeyedObject(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/keyed_property_base.cpp b/src/generated/animation/keyed_property_base.cpp index fe175e5..b649f54 100644 --- a/src/generated/animation/keyed_property_base.cpp +++ b/src/generated/animation/keyed_property_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* KeyedPropertyBase::clone() const -{ +Core* KeyedPropertyBase::clone() const { auto cloned = new KeyedProperty(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/keyframe_bool_base.cpp b/src/generated/animation/keyframe_bool_base.cpp index 72b141d..441c542 100644 --- a/src/generated/animation/keyframe_bool_base.cpp +++ b/src/generated/animation/keyframe_bool_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* KeyFrameBoolBase::clone() const -{ +Core* KeyFrameBoolBase::clone() const { auto cloned = new KeyFrameBool(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/keyframe_color_base.cpp b/src/generated/animation/keyframe_color_base.cpp index 93d2a15..f601201 100644 --- a/src/generated/animation/keyframe_color_base.cpp +++ b/src/generated/animation/keyframe_color_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* KeyFrameColorBase::clone() const -{ +Core* KeyFrameColorBase::clone() const { auto cloned = new KeyFrameColor(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/keyframe_double_base.cpp b/src/generated/animation/keyframe_double_base.cpp index b991a0e..f252dc8 100644 --- a/src/generated/animation/keyframe_double_base.cpp +++ b/src/generated/animation/keyframe_double_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* KeyFrameDoubleBase::clone() const -{ +Core* KeyFrameDoubleBase::clone() const { auto cloned = new KeyFrameDouble(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/keyframe_id_base.cpp b/src/generated/animation/keyframe_id_base.cpp index a228b47..bd5a263 100644 --- a/src/generated/animation/keyframe_id_base.cpp +++ b/src/generated/animation/keyframe_id_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* KeyFrameIdBase::clone() const -{ +Core* KeyFrameIdBase::clone() const { auto cloned = new KeyFrameId(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/linear_animation_base.cpp b/src/generated/animation/linear_animation_base.cpp index b55beef..f1d084f 100644 --- a/src/generated/animation/linear_animation_base.cpp +++ b/src/generated/animation/linear_animation_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* LinearAnimationBase::clone() const -{ +Core* LinearAnimationBase::clone() const { auto cloned = new LinearAnimation(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/nested_remap_animation_base.cpp b/src/generated/animation/nested_remap_animation_base.cpp index ff0a6c6..be06ba9 100644 --- a/src/generated/animation/nested_remap_animation_base.cpp +++ b/src/generated/animation/nested_remap_animation_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* NestedRemapAnimationBase::clone() const -{ +Core* NestedRemapAnimationBase::clone() const { auto cloned = new NestedRemapAnimation(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/nested_simple_animation_base.cpp b/src/generated/animation/nested_simple_animation_base.cpp index 283d353..3d19b86 100644 --- a/src/generated/animation/nested_simple_animation_base.cpp +++ b/src/generated/animation/nested_simple_animation_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* NestedSimpleAnimationBase::clone() const -{ +Core* NestedSimpleAnimationBase::clone() const { auto cloned = new NestedSimpleAnimation(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/nested_state_machine_base.cpp b/src/generated/animation/nested_state_machine_base.cpp index ef221f1..460ad2b 100644 --- a/src/generated/animation/nested_state_machine_base.cpp +++ b/src/generated/animation/nested_state_machine_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* NestedStateMachineBase::clone() const -{ +Core* NestedStateMachineBase::clone() const { auto cloned = new NestedStateMachine(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/state_machine_base.cpp b/src/generated/animation/state_machine_base.cpp index 7d34670..48d4aa4 100644 --- a/src/generated/animation/state_machine_base.cpp +++ b/src/generated/animation/state_machine_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* StateMachineBase::clone() const -{ +Core* StateMachineBase::clone() const { auto cloned = new StateMachine(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/state_machine_bool_base.cpp b/src/generated/animation/state_machine_bool_base.cpp index 3db764d..1cb9316 100644 --- a/src/generated/animation/state_machine_bool_base.cpp +++ b/src/generated/animation/state_machine_bool_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* StateMachineBoolBase::clone() const -{ +Core* StateMachineBoolBase::clone() const { auto cloned = new StateMachineBool(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/state_machine_layer_base.cpp b/src/generated/animation/state_machine_layer_base.cpp index acafe6e..cc60f49 100644 --- a/src/generated/animation/state_machine_layer_base.cpp +++ b/src/generated/animation/state_machine_layer_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* StateMachineLayerBase::clone() const -{ +Core* StateMachineLayerBase::clone() const { auto cloned = new StateMachineLayer(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/state_machine_number_base.cpp b/src/generated/animation/state_machine_number_base.cpp index b821aa4..3d8e26b 100644 --- a/src/generated/animation/state_machine_number_base.cpp +++ b/src/generated/animation/state_machine_number_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* StateMachineNumberBase::clone() const -{ +Core* StateMachineNumberBase::clone() const { auto cloned = new StateMachineNumber(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/state_machine_trigger_base.cpp b/src/generated/animation/state_machine_trigger_base.cpp index d7890be..6363092 100644 --- a/src/generated/animation/state_machine_trigger_base.cpp +++ b/src/generated/animation/state_machine_trigger_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* StateMachineTriggerBase::clone() const -{ +Core* StateMachineTriggerBase::clone() const { auto cloned = new StateMachineTrigger(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/state_transition_base.cpp b/src/generated/animation/state_transition_base.cpp index f535fbd..4267482 100644 --- a/src/generated/animation/state_transition_base.cpp +++ b/src/generated/animation/state_transition_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* StateTransitionBase::clone() const -{ +Core* StateTransitionBase::clone() const { auto cloned = new StateTransition(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/transition_bool_condition_base.cpp b/src/generated/animation/transition_bool_condition_base.cpp index 3b92f3d..a55fa3f 100644 --- a/src/generated/animation/transition_bool_condition_base.cpp +++ b/src/generated/animation/transition_bool_condition_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* TransitionBoolConditionBase::clone() const -{ +Core* TransitionBoolConditionBase::clone() const { auto cloned = new TransitionBoolCondition(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/transition_number_condition_base.cpp b/src/generated/animation/transition_number_condition_base.cpp index 537addf..6861e7f 100644 --- a/src/generated/animation/transition_number_condition_base.cpp +++ b/src/generated/animation/transition_number_condition_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* TransitionNumberConditionBase::clone() const -{ +Core* TransitionNumberConditionBase::clone() const { auto cloned = new TransitionNumberCondition(); cloned->copy(*this); return cloned;
diff --git a/src/generated/animation/transition_trigger_condition_base.cpp b/src/generated/animation/transition_trigger_condition_base.cpp index 31dadd3..c8544be 100644 --- a/src/generated/animation/transition_trigger_condition_base.cpp +++ b/src/generated/animation/transition_trigger_condition_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* TransitionTriggerConditionBase::clone() const -{ +Core* TransitionTriggerConditionBase::clone() const { auto cloned = new TransitionTriggerCondition(); cloned->copy(*this); return cloned;
diff --git a/src/generated/artboard_base.cpp b/src/generated/artboard_base.cpp index 612c270..682be5e 100644 --- a/src/generated/artboard_base.cpp +++ b/src/generated/artboard_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* ArtboardBase::clone() const -{ +Core* ArtboardBase::clone() const { auto cloned = new Artboard(); cloned->copy(*this); return cloned;
diff --git a/src/generated/assets/file_asset_contents_base.cpp b/src/generated/assets/file_asset_contents_base.cpp index 8d0e376..dd9d526 100644 --- a/src/generated/assets/file_asset_contents_base.cpp +++ b/src/generated/assets/file_asset_contents_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* FileAssetContentsBase::clone() const -{ +Core* FileAssetContentsBase::clone() const { auto cloned = new FileAssetContents(); cloned->copy(*this); return cloned;
diff --git a/src/generated/assets/folder_base.cpp b/src/generated/assets/folder_base.cpp index ba27d04..109aa68 100644 --- a/src/generated/assets/folder_base.cpp +++ b/src/generated/assets/folder_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* FolderBase::clone() const -{ +Core* FolderBase::clone() const { auto cloned = new Folder(); cloned->copy(*this); return cloned;
diff --git a/src/generated/assets/image_asset_base.cpp b/src/generated/assets/image_asset_base.cpp index 6b32b1d..87da493 100644 --- a/src/generated/assets/image_asset_base.cpp +++ b/src/generated/assets/image_asset_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* ImageAssetBase::clone() const -{ +Core* ImageAssetBase::clone() const { auto cloned = new ImageAsset(); cloned->copy(*this); return cloned;
diff --git a/src/generated/backboard_base.cpp b/src/generated/backboard_base.cpp index c5dfd7a..64ff18c 100644 --- a/src/generated/backboard_base.cpp +++ b/src/generated/backboard_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* BackboardBase::clone() const -{ +Core* BackboardBase::clone() const { auto cloned = new Backboard(); cloned->copy(*this); return cloned;
diff --git a/src/generated/bones/bone_base.cpp b/src/generated/bones/bone_base.cpp index 0ad594f..2ecaf1d 100644 --- a/src/generated/bones/bone_base.cpp +++ b/src/generated/bones/bone_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* BoneBase::clone() const -{ +Core* BoneBase::clone() const { auto cloned = new Bone(); cloned->copy(*this); return cloned;
diff --git a/src/generated/bones/cubic_weight_base.cpp b/src/generated/bones/cubic_weight_base.cpp index 4192b74..c3e4300 100644 --- a/src/generated/bones/cubic_weight_base.cpp +++ b/src/generated/bones/cubic_weight_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* CubicWeightBase::clone() const -{ +Core* CubicWeightBase::clone() const { auto cloned = new CubicWeight(); cloned->copy(*this); return cloned;
diff --git a/src/generated/bones/root_bone_base.cpp b/src/generated/bones/root_bone_base.cpp index faf1c91..c4e3a1f 100644 --- a/src/generated/bones/root_bone_base.cpp +++ b/src/generated/bones/root_bone_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* RootBoneBase::clone() const -{ +Core* RootBoneBase::clone() const { auto cloned = new RootBone(); cloned->copy(*this); return cloned;
diff --git a/src/generated/bones/skin_base.cpp b/src/generated/bones/skin_base.cpp index 401c65f..20741ea 100644 --- a/src/generated/bones/skin_base.cpp +++ b/src/generated/bones/skin_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* SkinBase::clone() const -{ +Core* SkinBase::clone() const { auto cloned = new Skin(); cloned->copy(*this); return cloned;
diff --git a/src/generated/bones/tendon_base.cpp b/src/generated/bones/tendon_base.cpp index 866209b..5bee774 100644 --- a/src/generated/bones/tendon_base.cpp +++ b/src/generated/bones/tendon_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* TendonBase::clone() const -{ +Core* TendonBase::clone() const { auto cloned = new Tendon(); cloned->copy(*this); return cloned;
diff --git a/src/generated/bones/weight_base.cpp b/src/generated/bones/weight_base.cpp index f62cb02..038e3ec 100644 --- a/src/generated/bones/weight_base.cpp +++ b/src/generated/bones/weight_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* WeightBase::clone() const -{ +Core* WeightBase::clone() const { auto cloned = new Weight(); cloned->copy(*this); return cloned;
diff --git a/src/generated/constraints/distance_constraint_base.cpp b/src/generated/constraints/distance_constraint_base.cpp index 457fe8c..00161b5 100644 --- a/src/generated/constraints/distance_constraint_base.cpp +++ b/src/generated/constraints/distance_constraint_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* DistanceConstraintBase::clone() const -{ +Core* DistanceConstraintBase::clone() const { auto cloned = new DistanceConstraint(); cloned->copy(*this); return cloned;
diff --git a/src/generated/constraints/ik_constraint_base.cpp b/src/generated/constraints/ik_constraint_base.cpp index 8a16dac..71df2b2 100644 --- a/src/generated/constraints/ik_constraint_base.cpp +++ b/src/generated/constraints/ik_constraint_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* IKConstraintBase::clone() const -{ +Core* IKConstraintBase::clone() const { auto cloned = new IKConstraint(); cloned->copy(*this); return cloned;
diff --git a/src/generated/constraints/rotation_constraint_base.cpp b/src/generated/constraints/rotation_constraint_base.cpp index 870570f..8ca5893 100644 --- a/src/generated/constraints/rotation_constraint_base.cpp +++ b/src/generated/constraints/rotation_constraint_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* RotationConstraintBase::clone() const -{ +Core* RotationConstraintBase::clone() const { auto cloned = new RotationConstraint(); cloned->copy(*this); return cloned;
diff --git a/src/generated/constraints/scale_constraint_base.cpp b/src/generated/constraints/scale_constraint_base.cpp index 612fcd4..7fe8a87 100644 --- a/src/generated/constraints/scale_constraint_base.cpp +++ b/src/generated/constraints/scale_constraint_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* ScaleConstraintBase::clone() const -{ +Core* ScaleConstraintBase::clone() const { auto cloned = new ScaleConstraint(); cloned->copy(*this); return cloned;
diff --git a/src/generated/constraints/transform_constraint_base.cpp b/src/generated/constraints/transform_constraint_base.cpp index 0c594f0..fbf2b48 100644 --- a/src/generated/constraints/transform_constraint_base.cpp +++ b/src/generated/constraints/transform_constraint_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* TransformConstraintBase::clone() const -{ +Core* TransformConstraintBase::clone() const { auto cloned = new TransformConstraint(); cloned->copy(*this); return cloned;
diff --git a/src/generated/constraints/translation_constraint_base.cpp b/src/generated/constraints/translation_constraint_base.cpp index 3de3c2a..0fe62c8 100644 --- a/src/generated/constraints/translation_constraint_base.cpp +++ b/src/generated/constraints/translation_constraint_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* TranslationConstraintBase::clone() const -{ +Core* TranslationConstraintBase::clone() const { auto cloned = new TranslationConstraint(); cloned->copy(*this); return cloned;
diff --git a/src/generated/draw_rules_base.cpp b/src/generated/draw_rules_base.cpp index 67b9c81..3e9f51c 100644 --- a/src/generated/draw_rules_base.cpp +++ b/src/generated/draw_rules_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* DrawRulesBase::clone() const -{ +Core* DrawRulesBase::clone() const { auto cloned = new DrawRules(); cloned->copy(*this); return cloned;
diff --git a/src/generated/draw_target_base.cpp b/src/generated/draw_target_base.cpp index 0578be9..1de0a4d 100644 --- a/src/generated/draw_target_base.cpp +++ b/src/generated/draw_target_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* DrawTargetBase::clone() const -{ +Core* DrawTargetBase::clone() const { auto cloned = new DrawTarget(); cloned->copy(*this); return cloned;
diff --git a/src/generated/nested_artboard_base.cpp b/src/generated/nested_artboard_base.cpp index 46a277e..4daa8c3 100644 --- a/src/generated/nested_artboard_base.cpp +++ b/src/generated/nested_artboard_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* NestedArtboardBase::clone() const -{ +Core* NestedArtboardBase::clone() const { auto cloned = new NestedArtboard(); cloned->copy(*this); return cloned;
diff --git a/src/generated/node_base.cpp b/src/generated/node_base.cpp index 7f144d5..160a2f8 100644 --- a/src/generated/node_base.cpp +++ b/src/generated/node_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* NodeBase::clone() const -{ +Core* NodeBase::clone() const { auto cloned = new Node(); cloned->copy(*this); return cloned;
diff --git a/src/generated/shapes/clipping_shape_base.cpp b/src/generated/shapes/clipping_shape_base.cpp index 2c28b3a..fbd7cb9 100644 --- a/src/generated/shapes/clipping_shape_base.cpp +++ b/src/generated/shapes/clipping_shape_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* ClippingShapeBase::clone() const -{ +Core* ClippingShapeBase::clone() const { auto cloned = new ClippingShape(); cloned->copy(*this); return cloned;
diff --git a/src/generated/shapes/cubic_asymmetric_vertex_base.cpp b/src/generated/shapes/cubic_asymmetric_vertex_base.cpp index 62b665a..15ade38 100644 --- a/src/generated/shapes/cubic_asymmetric_vertex_base.cpp +++ b/src/generated/shapes/cubic_asymmetric_vertex_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* CubicAsymmetricVertexBase::clone() const -{ +Core* CubicAsymmetricVertexBase::clone() const { auto cloned = new CubicAsymmetricVertex(); cloned->copy(*this); return cloned;
diff --git a/src/generated/shapes/cubic_detached_vertex_base.cpp b/src/generated/shapes/cubic_detached_vertex_base.cpp index 22f88ba..87c799f 100644 --- a/src/generated/shapes/cubic_detached_vertex_base.cpp +++ b/src/generated/shapes/cubic_detached_vertex_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* CubicDetachedVertexBase::clone() const -{ +Core* CubicDetachedVertexBase::clone() const { auto cloned = new CubicDetachedVertex(); cloned->copy(*this); return cloned;
diff --git a/src/generated/shapes/cubic_mirrored_vertex_base.cpp b/src/generated/shapes/cubic_mirrored_vertex_base.cpp index fb1731b..df88cf4 100644 --- a/src/generated/shapes/cubic_mirrored_vertex_base.cpp +++ b/src/generated/shapes/cubic_mirrored_vertex_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* CubicMirroredVertexBase::clone() const -{ +Core* CubicMirroredVertexBase::clone() const { auto cloned = new CubicMirroredVertex(); cloned->copy(*this); return cloned;
diff --git a/src/generated/shapes/ellipse_base.cpp b/src/generated/shapes/ellipse_base.cpp index df160bb..7546e22 100644 --- a/src/generated/shapes/ellipse_base.cpp +++ b/src/generated/shapes/ellipse_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* EllipseBase::clone() const -{ +Core* EllipseBase::clone() const { auto cloned = new Ellipse(); cloned->copy(*this); return cloned;
diff --git a/src/generated/shapes/image_base.cpp b/src/generated/shapes/image_base.cpp index 60bb78e..ae3ed39 100644 --- a/src/generated/shapes/image_base.cpp +++ b/src/generated/shapes/image_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* ImageBase::clone() const -{ +Core* ImageBase::clone() const { auto cloned = new Image(); cloned->copy(*this); return cloned;
diff --git a/src/generated/shapes/paint/fill_base.cpp b/src/generated/shapes/paint/fill_base.cpp index 1b2dbbc..481495d 100644 --- a/src/generated/shapes/paint/fill_base.cpp +++ b/src/generated/shapes/paint/fill_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* FillBase::clone() const -{ +Core* FillBase::clone() const { auto cloned = new Fill(); cloned->copy(*this); return cloned;
diff --git a/src/generated/shapes/paint/gradient_stop_base.cpp b/src/generated/shapes/paint/gradient_stop_base.cpp index 0ff71eb..d9e3a95 100644 --- a/src/generated/shapes/paint/gradient_stop_base.cpp +++ b/src/generated/shapes/paint/gradient_stop_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* GradientStopBase::clone() const -{ +Core* GradientStopBase::clone() const { auto cloned = new GradientStop(); cloned->copy(*this); return cloned;
diff --git a/src/generated/shapes/paint/linear_gradient_base.cpp b/src/generated/shapes/paint/linear_gradient_base.cpp index ad261e7..f446ddf 100644 --- a/src/generated/shapes/paint/linear_gradient_base.cpp +++ b/src/generated/shapes/paint/linear_gradient_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* LinearGradientBase::clone() const -{ +Core* LinearGradientBase::clone() const { auto cloned = new LinearGradient(); cloned->copy(*this); return cloned;
diff --git a/src/generated/shapes/paint/radial_gradient_base.cpp b/src/generated/shapes/paint/radial_gradient_base.cpp index 79b00d6..42a0820 100644 --- a/src/generated/shapes/paint/radial_gradient_base.cpp +++ b/src/generated/shapes/paint/radial_gradient_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* RadialGradientBase::clone() const -{ +Core* RadialGradientBase::clone() const { auto cloned = new RadialGradient(); cloned->copy(*this); return cloned;
diff --git a/src/generated/shapes/paint/solid_color_base.cpp b/src/generated/shapes/paint/solid_color_base.cpp index df57f7f..37e350f 100644 --- a/src/generated/shapes/paint/solid_color_base.cpp +++ b/src/generated/shapes/paint/solid_color_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* SolidColorBase::clone() const -{ +Core* SolidColorBase::clone() const { auto cloned = new SolidColor(); cloned->copy(*this); return cloned;
diff --git a/src/generated/shapes/paint/stroke_base.cpp b/src/generated/shapes/paint/stroke_base.cpp index 0c3acba..b260e98 100644 --- a/src/generated/shapes/paint/stroke_base.cpp +++ b/src/generated/shapes/paint/stroke_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* StrokeBase::clone() const -{ +Core* StrokeBase::clone() const { auto cloned = new Stroke(); cloned->copy(*this); return cloned;
diff --git a/src/generated/shapes/paint/trim_path_base.cpp b/src/generated/shapes/paint/trim_path_base.cpp index fb319ca..9a145b7 100644 --- a/src/generated/shapes/paint/trim_path_base.cpp +++ b/src/generated/shapes/paint/trim_path_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* TrimPathBase::clone() const -{ +Core* TrimPathBase::clone() const { auto cloned = new TrimPath(); cloned->copy(*this); return cloned;
diff --git a/src/generated/shapes/points_path_base.cpp b/src/generated/shapes/points_path_base.cpp index 27169a8..4e87789 100644 --- a/src/generated/shapes/points_path_base.cpp +++ b/src/generated/shapes/points_path_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* PointsPathBase::clone() const -{ +Core* PointsPathBase::clone() const { auto cloned = new PointsPath(); cloned->copy(*this); return cloned;
diff --git a/src/generated/shapes/polygon_base.cpp b/src/generated/shapes/polygon_base.cpp index 96214c5..4dfa011 100644 --- a/src/generated/shapes/polygon_base.cpp +++ b/src/generated/shapes/polygon_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* PolygonBase::clone() const -{ +Core* PolygonBase::clone() const { auto cloned = new Polygon(); cloned->copy(*this); return cloned;
diff --git a/src/generated/shapes/rectangle_base.cpp b/src/generated/shapes/rectangle_base.cpp index 47a83fe..db0d78f 100644 --- a/src/generated/shapes/rectangle_base.cpp +++ b/src/generated/shapes/rectangle_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* RectangleBase::clone() const -{ +Core* RectangleBase::clone() const { auto cloned = new Rectangle(); cloned->copy(*this); return cloned;
diff --git a/src/generated/shapes/shape_base.cpp b/src/generated/shapes/shape_base.cpp index 595afa6..7595b31 100644 --- a/src/generated/shapes/shape_base.cpp +++ b/src/generated/shapes/shape_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* ShapeBase::clone() const -{ +Core* ShapeBase::clone() const { auto cloned = new Shape(); cloned->copy(*this); return cloned;
diff --git a/src/generated/shapes/star_base.cpp b/src/generated/shapes/star_base.cpp index 3b753c2..1df8368 100644 --- a/src/generated/shapes/star_base.cpp +++ b/src/generated/shapes/star_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* StarBase::clone() const -{ +Core* StarBase::clone() const { auto cloned = new Star(); cloned->copy(*this); return cloned;
diff --git a/src/generated/shapes/straight_vertex_base.cpp b/src/generated/shapes/straight_vertex_base.cpp index a7c99c1..19ff88c 100644 --- a/src/generated/shapes/straight_vertex_base.cpp +++ b/src/generated/shapes/straight_vertex_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* StraightVertexBase::clone() const -{ +Core* StraightVertexBase::clone() const { auto cloned = new StraightVertex(); cloned->copy(*this); return cloned;
diff --git a/src/generated/shapes/triangle_base.cpp b/src/generated/shapes/triangle_base.cpp index c4f7e95..e7debc1 100644 --- a/src/generated/shapes/triangle_base.cpp +++ b/src/generated/shapes/triangle_base.cpp
@@ -3,8 +3,7 @@ using namespace rive; -Core* TriangleBase::clone() const -{ +Core* TriangleBase::clone() const { auto cloned = new Triangle(); cloned->copy(*this); return cloned;
diff --git a/src/importers/artboard_importer.cpp b/src/importers/artboard_importer.cpp index 32f7df2..34959fe 100644 --- a/src/importers/artboard_importer.cpp +++ b/src/importers/artboard_importer.cpp
@@ -8,25 +8,21 @@ ArtboardImporter::ArtboardImporter(Artboard* artboard) : m_Artboard(artboard) {} -void ArtboardImporter::addComponent(Core* object) -{ +void ArtboardImporter::addComponent(Core* object) { m_Artboard->addObject(object); } -void ArtboardImporter::addAnimation(LinearAnimation* animation) -{ +void ArtboardImporter::addAnimation(LinearAnimation* animation) { m_Artboard->addAnimation(animation); } -void ArtboardImporter::addStateMachine(StateMachine* stateMachine) -{ +void ArtboardImporter::addStateMachine(StateMachine* stateMachine) { m_Artboard->addStateMachine(stateMachine); } StatusCode ArtboardImporter::resolve() { return m_Artboard->initialize(); } -bool ArtboardImporter::readNullObject() -{ +bool ArtboardImporter::readNullObject() { addComponent(nullptr); return true; } \ No newline at end of file
diff --git a/src/importers/backboard_importer.cpp b/src/importers/backboard_importer.cpp index 64619d4..306d56c 100644 --- a/src/importers/backboard_importer.cpp +++ b/src/importers/backboard_importer.cpp
@@ -6,48 +6,38 @@ using namespace rive; BackboardImporter::BackboardImporter(Backboard* backboard) : - m_Backboard(backboard), m_NextArtboardId(0) -{ -} -void BackboardImporter::addNestedArtboard(NestedArtboard* artboard) -{ + m_Backboard(backboard), m_NextArtboardId(0) {} +void BackboardImporter::addNestedArtboard(NestedArtboard* artboard) { m_NestedArtboards.push_back(artboard); } -void BackboardImporter::addFileAsset(FileAsset* asset) -{ +void BackboardImporter::addFileAsset(FileAsset* asset) { m_FileAssets.push_back(asset); } -void BackboardImporter::addFileAssetReferencer(FileAssetReferencer* referencer) -{ +void BackboardImporter::addFileAssetReferencer( + FileAssetReferencer* referencer) { m_FileAssetReferencers.push_back(referencer); } -void BackboardImporter::addArtboard(Artboard* artboard) -{ +void BackboardImporter::addArtboard(Artboard* artboard) { m_ArtboardLookup[m_NextArtboardId++] = artboard; } void BackboardImporter::addMissingArtboard() { m_NextArtboardId++; } -StatusCode BackboardImporter::resolve() -{ - for (auto nestedArtboard : m_NestedArtboards) - { +StatusCode BackboardImporter::resolve() { + for (auto nestedArtboard : m_NestedArtboards) { auto itr = m_ArtboardLookup.find(nestedArtboard->artboardId()); - if (itr != m_ArtboardLookup.end()) - { + if (itr != m_ArtboardLookup.end()) { auto artboard = itr->second; - if (artboard != nullptr) - { + if (artboard != nullptr) { nestedArtboard->nest(artboard); } } } - for (auto referencer : m_FileAssetReferencers) - { + for (auto referencer : m_FileAssetReferencers) { referencer->assets(m_FileAssets); } return StatusCode::Ok;
diff --git a/src/importers/file_asset_importer.cpp b/src/importers/file_asset_importer.cpp index d589ef3..a60dd29 100644 --- a/src/importers/file_asset_importer.cpp +++ b/src/importers/file_asset_importer.cpp
@@ -7,23 +7,17 @@ FileAssetImporter::FileAssetImporter(FileAsset* fileAsset, FileAssetResolver* assetResolver) : - m_FileAsset(fileAsset), m_FileAssetResolver(assetResolver) -{ -} + m_FileAsset(fileAsset), m_FileAssetResolver(assetResolver) {} -void FileAssetImporter::loadContents(const FileAssetContents& contents) -{ +void FileAssetImporter::loadContents(const FileAssetContents& contents) { const std::vector<uint8_t>& data = contents.bytes(); - if (m_FileAsset->decode(&data[0], data.size())) - { + if (m_FileAsset->decode(&data[0], data.size())) { m_LoadedContents = true; } } -StatusCode FileAssetImporter::resolve() -{ - if (!m_LoadedContents && m_FileAssetResolver != nullptr) - { +StatusCode FileAssetImporter::resolve() { + if (!m_LoadedContents && m_FileAssetResolver != nullptr) { // Contents weren't available in-band, or they couldn't be decoded. Try // to find them out of band. m_FileAssetResolver->loadContents(*m_FileAsset);
diff --git a/src/importers/keyed_object_importer.cpp b/src/importers/keyed_object_importer.cpp index 74a5270..6d570e1 100644 --- a/src/importers/keyed_object_importer.cpp +++ b/src/importers/keyed_object_importer.cpp
@@ -6,11 +6,8 @@ using namespace rive; KeyedObjectImporter::KeyedObjectImporter(KeyedObject* keyedObject) : - m_KeyedObject(keyedObject) -{ -} + m_KeyedObject(keyedObject) {} -void KeyedObjectImporter::addKeyedProperty(KeyedProperty* property) -{ +void KeyedObjectImporter::addKeyedProperty(KeyedProperty* property) { m_KeyedObject->addKeyedProperty(property); } \ No newline at end of file
diff --git a/src/importers/keyed_property_importer.cpp b/src/importers/keyed_property_importer.cpp index 674f5eb..a664e1a 100644 --- a/src/importers/keyed_property_importer.cpp +++ b/src/importers/keyed_property_importer.cpp
@@ -7,18 +7,14 @@ KeyedPropertyImporter::KeyedPropertyImporter(LinearAnimation* animation, KeyedProperty* keyedProperty) : - m_Animation(animation), m_KeyedProperty(keyedProperty) -{ -} + m_Animation(animation), m_KeyedProperty(keyedProperty) {} -void KeyedPropertyImporter::addKeyFrame(KeyFrame* keyFrame) -{ +void KeyedPropertyImporter::addKeyFrame(KeyFrame* keyFrame) { keyFrame->computeSeconds(m_Animation->fps()); m_KeyedProperty->addKeyFrame(keyFrame); } -bool KeyedPropertyImporter::readNullObject() -{ +bool KeyedPropertyImporter::readNullObject() { // We don't need to add the null keyframe as nothing references them, but we // do need to not allow the null to propagate up. return true;
diff --git a/src/importers/layer_state_importer.cpp b/src/importers/layer_state_importer.cpp index 2786be4..a1cc71d 100644 --- a/src/importers/layer_state_importer.cpp +++ b/src/importers/layer_state_importer.cpp
@@ -7,15 +7,12 @@ using namespace rive; LayerStateImporter::LayerStateImporter(LayerState* state) : m_State(state) {} -void LayerStateImporter::addTransition(StateTransition* transition) -{ +void LayerStateImporter::addTransition(StateTransition* transition) { m_State->addTransition(transition); } -bool LayerStateImporter::addBlendAnimation(BlendAnimation* animation) -{ - if (!m_State->is<BlendState>()) - { +bool LayerStateImporter::addBlendAnimation(BlendAnimation* animation) { + if (!m_State->is<BlendState>()) { return false; } auto blendState = m_State->as<BlendState>(); @@ -24,22 +21,17 @@ return true; } -StatusCode LayerStateImporter::resolve() -{ - if (m_State->is<BlendState>()) - { +StatusCode LayerStateImporter::resolve() { + if (m_State->is<BlendState>()) { auto blendState = m_State->as<BlendState>(); - for (auto transition : blendState->m_Transitions) - { - if (!transition->is<BlendStateTransition>()) - { + for (auto transition : blendState->m_Transitions) { + if (!transition->is<BlendStateTransition>()) { continue; } auto blendStateTransition = transition->as<BlendStateTransition>(); auto exitId = blendStateTransition->exitBlendAnimationId(); - if (exitId >= 0 && exitId < blendState->m_Animations.size()) - { + if (exitId >= 0 && exitId < blendState->m_Animations.size()) { blendStateTransition->m_ExitBlendAnimation = blendState->m_Animations[exitId]; }
diff --git a/src/importers/linear_animation_importer.cpp b/src/importers/linear_animation_importer.cpp index 00f7560..c038eeb 100644 --- a/src/importers/linear_animation_importer.cpp +++ b/src/importers/linear_animation_importer.cpp
@@ -6,11 +6,8 @@ using namespace rive; LinearAnimationImporter::LinearAnimationImporter(LinearAnimation* animation) : - m_Animation(animation) -{ -} + m_Animation(animation) {} -void LinearAnimationImporter::addKeyedObject(KeyedObject* object) -{ +void LinearAnimationImporter::addKeyedObject(KeyedObject* object) { m_Animation->addKeyedObject(object); } \ No newline at end of file
diff --git a/src/importers/state_machine_importer.cpp b/src/importers/state_machine_importer.cpp index c1db466..a5b54b3 100644 --- a/src/importers/state_machine_importer.cpp +++ b/src/importers/state_machine_importer.cpp
@@ -4,22 +4,17 @@ using namespace rive; StateMachineImporter::StateMachineImporter(StateMachine* machine) : - m_StateMachine(machine) -{ -} + m_StateMachine(machine) {} -void StateMachineImporter::addLayer(StateMachineLayer* layer) -{ +void StateMachineImporter::addLayer(StateMachineLayer* layer) { m_StateMachine->addLayer(layer); } -void StateMachineImporter::addInput(StateMachineInput* input) -{ +void StateMachineImporter::addInput(StateMachineInput* input) { m_StateMachine->addInput(input); } -bool StateMachineImporter::readNullObject() -{ +bool StateMachineImporter::readNullObject() { // Hard assumption that we won't add new layer types... m_StateMachine->addInput(nullptr); return true;
diff --git a/src/importers/state_machine_layer_importer.cpp b/src/importers/state_machine_layer_importer.cpp index dd1c08c..9a7da10 100644 --- a/src/importers/state_machine_layer_importer.cpp +++ b/src/importers/state_machine_layer_importer.cpp
@@ -8,35 +8,26 @@ using namespace rive; StateMachineLayerImporter::StateMachineLayerImporter(StateMachineLayer* layer, const Artboard* artboard) : - m_Layer(layer), m_Artboard(artboard) -{ -} -void StateMachineLayerImporter::addState(LayerState* state) -{ + m_Layer(layer), m_Artboard(artboard) {} +void StateMachineLayerImporter::addState(LayerState* state) { m_Layer->addState(state); } -StatusCode StateMachineLayerImporter::resolve() -{ +StatusCode StateMachineLayerImporter::resolve() { - for (auto state : m_Layer->m_States) - { - if (state->is<AnimationState>()) - { + for (auto state : m_Layer->m_States) { + if (state->is<AnimationState>()) { auto animationState = state->as<AnimationState>(); - if (animationState->animationId() != -1) - { + if (animationState->animationId() != -1) { animationState->m_Animation = m_Artboard->animation(animationState->animationId()); - if (animationState->m_Animation == nullptr) - { + if (animationState->m_Animation == nullptr) { return StatusCode::MissingObject; } } } - for (auto transition : state->m_Transitions) - { + for (auto transition : state->m_Transitions) { if (transition->stateToId() < 0 || transition->stateToId() > m_Layer->m_States.size()) { @@ -48,8 +39,7 @@ return StatusCode::Ok; } -bool StateMachineLayerImporter::readNullObject() -{ +bool StateMachineLayerImporter::readNullObject() { // Add an 'empty' generic state that can be transitioned to/from but doesn't // effectively do anything. This allows us to deal with unexpected new state // types the runtime won't be able to understand. It'll still be able to
diff --git a/src/importers/state_transition_importer.cpp b/src/importers/state_transition_importer.cpp index 5f2890b..d340460 100644 --- a/src/importers/state_transition_importer.cpp +++ b/src/importers/state_transition_importer.cpp
@@ -5,11 +5,8 @@ using namespace rive; StateTransitionImporter::StateTransitionImporter(StateTransition* transition) : - m_Transition(transition) -{ -} -void StateTransitionImporter::addCondition(TransitionCondition* condition) -{ + m_Transition(transition) {} +void StateTransitionImporter::addCondition(TransitionCondition* condition) { m_Transition->addCondition(condition); }
diff --git a/src/math/aabb.cpp b/src/math/aabb.cpp index 7b0590d..ce363a2 100644 --- a/src/math/aabb.cpp +++ b/src/math/aabb.cpp
@@ -5,8 +5,7 @@ AABB::AABB() : buffer{0} {} -AABB::AABB(const AABB& copy) -{ +AABB::AABB(const AABB& copy) { buffer[0] = copy.buffer[0]; buffer[1] = copy.buffer[1]; buffer[2] = copy.buffer[2]; @@ -14,66 +13,55 @@ } AABB::AABB(float minX, float minY, float maxX, float maxY) : - buffer{minX, minY, maxX, maxY} -{ -} + buffer{minX, minY, maxX, maxY} {} -void AABB::center(Vec2D& out, const AABB& a) -{ +void AABB::center(Vec2D& out, const AABB& a) { out[0] = (a[0] + a[2]) * 0.5f; out[1] = (a[1] + a[3]) * 0.5f; } -void AABB::size(Vec2D& out, const AABB& a) -{ +void AABB::size(Vec2D& out, const AABB& a) { out[0] = a[2] - a[0]; out[1] = a[3] - a[1]; } -void AABB::extents(Vec2D& out, const AABB& a) -{ +void AABB::extents(Vec2D& out, const AABB& a) { out[0] = (a[2] - a[0]) * 0.5; out[1] = (a[3] - a[1]) * 0.5; } void AABB::combine(AABB& out, const AABB& a, const AABB& b) {} -bool AABB::contains(const AABB& a, const AABB& b) -{ +bool AABB::contains(const AABB& a, const AABB& b) { return a[0] <= b[0] && a[1] <= b[1] && b[2] <= a[2] && b[3] <= a[3]; } -bool AABB::isValid(const AABB& a) -{ +bool AABB::isValid(const AABB& a) { float dx = a[2] - a[0]; float dy = a[3] - a[1]; return dx >= 0.0f && dy >= 0.0f && std::isfinite(a[0]) && std::isfinite(a[1]) && std::isfinite(a[2]) && std::isfinite(a[3]); } -bool AABB::testOverlap(const AABB& a, const AABB& b) -{ +bool AABB::testOverlap(const AABB& a, const AABB& b) { float d1x = b[0] - a[2]; float d1y = b[1] - a[3]; float d2x = a[0] - b[2]; float d2y = a[1] - b[3]; - if (d1x > 0.0 || d1y > 0.0) - { + if (d1x > 0.0 || d1y > 0.0) { return false; } - if (d2x > 0.0 || d2y > 0.0) - { + if (d2x > 0.0 || d2y > 0.0) { return false; } return true; } -bool AABB::areIdentical(const AABB& a, const AABB& b) -{ +bool AABB::areIdentical(const AABB& a, const AABB& b) { return a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3]; } @@ -81,15 +69,13 @@ float AABB::height() const { return buffer[3] - buffer[1]; } -float AABB::perimeter() const -{ +float AABB::perimeter() const { float wx = buffer[2] - buffer[0]; float wy = buffer[3] - buffer[1]; return 2.0 * (wx + wy); } -void AABB::transform(AABB& out, const AABB& a, const Mat2D& matrix) -{ +void AABB::transform(AABB& out, const AABB& a, const Mat2D& matrix) { Vec2D p1(a[0], a[1]); Vec2D p2(a[2], a[1]); Vec2D p3(a[2], a[3]);
diff --git a/src/math/mat2d.cpp b/src/math/mat2d.cpp index fecb69e..8e46cad 100644 --- a/src/math/mat2d.cpp +++ b/src/math/mat2d.cpp
@@ -8,17 +8,12 @@ Mat2D::Mat2D() : m_Buffer{1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f} {} Mat2D::Mat2D(const Mat2D& copy) : - m_Buffer{copy[0], copy[1], copy[2], copy[3], copy[4], copy[5]} -{ -} + m_Buffer{copy[0], copy[1], copy[2], copy[3], copy[4], copy[5]} {} Mat2D::Mat2D(float x1, float y1, float x2, float y2, float tx, float ty) : - m_Buffer{x1, y1, x2, y2, tx, ty} -{ -} + m_Buffer{x1, y1, x2, y2, tx, ty} {} -void Mat2D::fromRotation(Mat2D& result, float rad) -{ +void Mat2D::fromRotation(Mat2D& result, float rad) { float s = sin(rad); float c = cos(rad); result[0] = c; @@ -29,8 +24,7 @@ result[5] = 0; } -void Mat2D::scale(Mat2D& result, const Mat2D& mat, const Vec2D& vec) -{ +void Mat2D::scale(Mat2D& result, const Mat2D& mat, const Vec2D& vec) { float v0 = vec[0], v1 = vec[1]; result[0] = mat[0] * v0; result[1] = mat[1] * v0; @@ -40,8 +34,7 @@ result[5] = mat[5]; } -void Mat2D::multiply(Mat2D& result, const Mat2D& a, const Mat2D& b) -{ +void Mat2D::multiply(Mat2D& result, const Mat2D& a, const Mat2D& b) { float a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5], b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5]; result[0] = a0 * b0 + a2 * b1; @@ -52,13 +45,11 @@ result[5] = a1 * b4 + a3 * b5 + a5; } -bool Mat2D::invert(Mat2D& result, const Mat2D& a) -{ +bool Mat2D::invert(Mat2D& result, const Mat2D& a) { float aa = a[0], ab = a[1], ac = a[2], ad = a[3], atx = a[4], aty = a[5]; float det = aa * ad - ab * ac; - if (det == 0.0f) - { + if (det == 0.0f) { return false; } det = 1.0f / det; @@ -72,8 +63,7 @@ return true; } -void Mat2D::copy(Mat2D& result, const Mat2D& a) -{ +void Mat2D::copy(Mat2D& result, const Mat2D& a) { result[0] = a[0]; result[1] = a[1]; result[2] = a[2]; @@ -82,8 +72,7 @@ result[5] = a[5]; } -void Mat2D::decompose(TransformComponents& result, const Mat2D& m) -{ +void Mat2D::decompose(TransformComponents& result, const Mat2D& m) { float m0 = m[0], m1 = m[1], m2 = m[2], m3 = m[3]; float rotation = (float)std::atan2(m1, m0); @@ -100,16 +89,12 @@ result.skew(skewX); } -void Mat2D::compose(Mat2D& result, const TransformComponents& components) -{ +void Mat2D::compose(Mat2D& result, const TransformComponents& components) { float r = components.rotation(); - if (r != 0.0f) - { + if (r != 0.0f) { Mat2D::fromRotation(result, r); - } - else - { + } else { Mat2D::identity(result); } result[4] = components.x(); @@ -119,15 +104,13 @@ Mat2D::scale(result, result, scale); float sk = components.skew(); - if (sk != 0.0f) - { + if (sk != 0.0f) { result[2] = result[0] * sk + result[2]; result[3] = result[1] * sk + result[3]; } } -void Mat2D::scaleByValues(Mat2D& result, float sx, float sy) -{ +void Mat2D::scaleByValues(Mat2D& result, float sx, float sy) { result[0] *= sx; result[1] *= sx; result[2] *= sy;
diff --git a/src/math/vec2d.cpp b/src/math/vec2d.cpp index 5921536..f74eff8 100644 --- a/src/math/vec2d.cpp +++ b/src/math/vec2d.cpp
@@ -8,105 +8,89 @@ Vec2D::Vec2D(float x, float y) : m_Buffer{x, y} {} -Vec2D::Vec2D(const Vec2D& copy) : m_Buffer{copy.m_Buffer[0], copy.m_Buffer[1]} -{ -} +Vec2D::Vec2D(const Vec2D& copy) : + m_Buffer{copy.m_Buffer[0], copy.m_Buffer[1]} {} -void Vec2D::transform(Vec2D& result, const Vec2D& a, const Mat2D& m) -{ +void Vec2D::transform(Vec2D& result, const Vec2D& a, const Mat2D& m) { float x = a[0]; float y = a[1]; result[0] = m[0] * x + m[2] * y + m[4]; result[1] = m[1] * x + m[3] * y + m[5]; } -void Vec2D::transformDir(Vec2D& result, const Vec2D& a, const Mat2D& m) -{ +void Vec2D::transformDir(Vec2D& result, const Vec2D& a, const Mat2D& m) { float x = a[0]; float y = a[1]; result[0] = m[0] * x + m[2] * y; result[1] = m[1] * x + m[3] * y; } -void Vec2D::add(Vec2D& result, const Vec2D& a, const Vec2D& b) -{ +void Vec2D::add(Vec2D& result, const Vec2D& a, const Vec2D& b) { result[0] = a[0] + b[0]; result[1] = a[1] + b[1]; } -void Vec2D::subtract(Vec2D& result, const Vec2D& a, const Vec2D& b) -{ +void Vec2D::subtract(Vec2D& result, const Vec2D& a, const Vec2D& b) { result[0] = a[0] - b[0]; result[1] = a[1] - b[1]; } float Vec2D::length(const Vec2D& a) { return std::sqrt(lengthSquared(a)); } -float Vec2D::lengthSquared(const Vec2D& a) -{ +float Vec2D::lengthSquared(const Vec2D& a) { float x = a[0]; float y = a[1]; return x * x + y * y; } -float Vec2D::distance(const Vec2D& a, const Vec2D& b) -{ +float Vec2D::distance(const Vec2D& a, const Vec2D& b) { return std::sqrt(distanceSquared(a, b)); } -float Vec2D::distanceSquared(const Vec2D& a, const Vec2D& b) -{ +float Vec2D::distanceSquared(const Vec2D& a, const Vec2D& b) { float x = b[0] - a[0]; float y = b[1] - a[1]; return x * x + y * y; } -void Vec2D::copy(Vec2D& result, const Vec2D& a) -{ +void Vec2D::copy(Vec2D& result, const Vec2D& a) { result[0] = a[0]; result[1] = a[1]; } -void Vec2D::normalize(Vec2D& result, const Vec2D& a) -{ +void Vec2D::normalize(Vec2D& result, const Vec2D& a) { float x = a[0]; float y = a[1]; float len = x * x + y * y; - if (len > 0.0f) - { + if (len > 0.0f) { len = 1.0f / std::sqrt(len); result[0] = a[0] * len; result[1] = a[1] * len; } } -float Vec2D::dot(const Vec2D& a, const Vec2D& b) -{ +float Vec2D::dot(const Vec2D& a, const Vec2D& b) { return a[0] * b[0] + a[1] * b[1]; } -void Vec2D::lerp(Vec2D& o, const Vec2D& a, const Vec2D& b, float f) -{ +void Vec2D::lerp(Vec2D& o, const Vec2D& a, const Vec2D& b, float f) { float ax = a[0]; float ay = a[1]; o[0] = ax + f * (b[0] - ax); o[1] = ay + f * (b[1] - ay); } -void Vec2D::scale(Vec2D& o, const Vec2D& a, float scale) -{ +void Vec2D::scale(Vec2D& o, const Vec2D& a, float scale) { o[0] = a[0] * scale; o[1] = a[1] * scale; } -void Vec2D::scaleAndAdd(Vec2D& o, const Vec2D& a, const Vec2D& b, float scale) -{ +void Vec2D::scaleAndAdd(Vec2D& o, const Vec2D& a, const Vec2D& b, float scale) { o[0] = a[0] + b[0] * scale; o[1] = a[1] + b[1] * scale; } -void Vec2D::negate(Vec2D& o, const Vec2D& a) -{ +void Vec2D::negate(Vec2D& o, const Vec2D& a) { o[0] = -a[0]; o[1] = -a[1]; } \ No newline at end of file
diff --git a/src/nested_artboard.cpp b/src/nested_artboard.cpp index 363db65..e42eb14 100644 --- a/src/nested_artboard.cpp +++ b/src/nested_artboard.cpp
@@ -7,36 +7,29 @@ using namespace rive; -NestedArtboard::~NestedArtboard() -{ - if (m_NestedInstance->isInstance()) - { +NestedArtboard::~NestedArtboard() { + if (m_NestedInstance->isInstance()) { delete m_NestedInstance; } } -Core* NestedArtboard::clone() const -{ +Core* NestedArtboard::clone() const { NestedArtboard* nestedArtboard = static_cast<NestedArtboard*>(NestedArtboardBase::clone()); - if (m_NestedInstance == nullptr) - { + if (m_NestedInstance == nullptr) { return nestedArtboard; } nestedArtboard->nest(m_NestedInstance->instance()); return nestedArtboard; } -void NestedArtboard::nest(Artboard* artboard) -{ +void NestedArtboard::nest(Artboard* artboard) { assert(artboard != nullptr); m_NestedInstance = artboard; m_NestedInstance->advance(0.0f); } -void NestedArtboard::draw(Renderer* renderer) -{ - if (m_NestedInstance == nullptr) - { +void NestedArtboard::draw(Renderer* renderer) { + if (m_NestedInstance == nullptr) { return; } renderer->save(); @@ -49,12 +42,10 @@ renderer->restore(); } -StatusCode NestedArtboard::import(ImportStack& importStack) -{ +StatusCode NestedArtboard::import(ImportStack& importStack) { auto backboardImporter = importStack.latest<BackboardImporter>(Backboard::typeKey); - if (backboardImporter == nullptr) - { + if (backboardImporter == nullptr) { return StatusCode::MissingObject; } backboardImporter->addNestedArtboard(this); @@ -62,44 +53,36 @@ return Super::import(importStack); } -void NestedArtboard::addNestedAnimation(NestedAnimation* nestedAnimation) -{ +void NestedArtboard::addNestedAnimation(NestedAnimation* nestedAnimation) { m_NestedAnimations.push_back(nestedAnimation); } -StatusCode NestedArtboard::onAddedClean(CoreContext* context) -{ +StatusCode NestedArtboard::onAddedClean(CoreContext* context) { // N.B. The nested instance will be null here for the source artboards. // Instances will have a nestedInstance available. This is a good thing as // it ensures that we only instance animations in artboard instances. It // does require that we always use an artboard instance (not just the source // artboard) when working with nested artboards, but in general this is good // practice for any loaded Rive file. - if (m_NestedInstance != nullptr) - { - for (auto animation : m_NestedAnimations) - { + if (m_NestedInstance != nullptr) { + for (auto animation : m_NestedAnimations) { animation->initializeAnimation(m_NestedInstance); } } return Super::onAddedClean(context); } -bool NestedArtboard::advance(float elapsedSeconds) -{ - if (m_NestedInstance == nullptr) - { +bool NestedArtboard::advance(float elapsedSeconds) { + if (m_NestedInstance == nullptr) { return false; } - for (auto animation : m_NestedAnimations) - { + for (auto animation : m_NestedAnimations) { animation->advance(elapsedSeconds, m_NestedInstance); } return m_NestedInstance->advance(elapsedSeconds); } -void NestedArtboard::update(ComponentDirt value) -{ +void NestedArtboard::update(ComponentDirt value) { Super::update(value); if (hasDirt(value, ComponentDirt::WorldTransform) && m_NestedInstance != nullptr)
diff --git a/src/shapes/clipping_shape.cpp b/src/shapes/clipping_shape.cpp index 200a783..3ba12b9 100644 --- a/src/shapes/clipping_shape.cpp +++ b/src/shapes/clipping_shape.cpp
@@ -8,27 +8,22 @@ using namespace rive; -StatusCode ClippingShape::onAddedClean(CoreContext* context) -{ +StatusCode ClippingShape::onAddedClean(CoreContext* context) { auto clippingHolder = parent(); auto artboard = static_cast<Artboard*>(context); - for (auto core : artboard->objects()) - { - if (core == nullptr) - { + for (auto core : artboard->objects()) { + if (core == nullptr) { continue; } // Iterate artboard to find drawables that are parented to this clipping // shape, they need to know they'll be clipped by this shape. - if (core->is<Drawable>()) - { + if (core->is<Drawable>()) { auto drawable = core->as<Drawable>(); for (ContainerComponent* component = drawable; component != nullptr; component = component->parent()) { - if (component == clippingHolder) - { + if (component == clippingHolder) { drawable->addClippingShape(this); break; } @@ -38,13 +33,10 @@ // Iterate artboard to find shapes that are parented to the source, // their paths will need to be RenderPaths in order to be used for // clipping operations. - if (core->is<Shape>() && core != clippingHolder) - { + if (core->is<Shape>() && core != clippingHolder) { auto component = core->as<ContainerComponent>(); - while (component != nullptr) - { - if (component == m_Source) - { + while (component != nullptr) { + if (component == m_Source) { auto shape = core->as<Shape>(); shape->addDefaultPathSpace(PathSpace::World | PathSpace::Clipping); @@ -61,16 +53,13 @@ return StatusCode::Ok; } -StatusCode ClippingShape::onAddedDirty(CoreContext* context) -{ +StatusCode ClippingShape::onAddedDirty(CoreContext* context) { StatusCode code = Super::onAddedDirty(context); - if (code != StatusCode::Ok) - { + if (code != StatusCode::Ok) { return code; } auto coreObject = context->resolve(sourceId()); - if (coreObject == nullptr || !coreObject->is<Node>()) - { + if (coreObject == nullptr || !coreObject->is<Node>()) { return StatusCode::MissingObject; } @@ -79,26 +68,20 @@ return StatusCode::Ok; } -void ClippingShape::buildDependencies() -{ - for (auto shape : m_Shapes) - { +void ClippingShape::buildDependencies() { + for (auto shape : m_Shapes) { shape->pathComposer()->addDependent(this); } } static Mat2D identity; -void ClippingShape::update(ComponentDirt value) -{ - if (hasDirt(value, ComponentDirt::Path | ComponentDirt::WorldTransform)) - { +void ClippingShape::update(ComponentDirt value) { + if (hasDirt(value, ComponentDirt::Path | ComponentDirt::WorldTransform)) { m_RenderPath->reset(); m_RenderPath->fillRule((FillRule)fillRule()); - for (auto shape : m_Shapes) - { - if (!shape->isHidden()) - { + for (auto shape : m_Shapes) { + if (!shape->isHidden()) { m_RenderPath->addPath(shape->pathComposer()->worldPath(), identity); }
diff --git a/src/shapes/cubic_asymmetric_vertex.cpp b/src/shapes/cubic_asymmetric_vertex.cpp index 8e077ae..3e7c5ee 100644 --- a/src/shapes/cubic_asymmetric_vertex.cpp +++ b/src/shapes/cubic_asymmetric_vertex.cpp
@@ -4,35 +4,30 @@ using namespace rive; -void CubicAsymmetricVertex::computeIn() -{ +void CubicAsymmetricVertex::computeIn() { Vec2D::add(m_InPoint, Vec2D(x(), y()), Vec2D(cos(rotation()) * -inDistance(), sin(rotation()) * -inDistance())); } -void CubicAsymmetricVertex::computeOut() -{ +void CubicAsymmetricVertex::computeOut() { Vec2D::add(m_OutPoint, Vec2D(x(), y()), Vec2D(cos(rotation()) * outDistance(), sin(rotation()) * outDistance())); } -void CubicAsymmetricVertex::rotationChanged() -{ +void CubicAsymmetricVertex::rotationChanged() { m_InValid = false; m_OutValid = false; markPathDirty(); } -void CubicAsymmetricVertex::inDistanceChanged() -{ +void CubicAsymmetricVertex::inDistanceChanged() { m_InValid = false; markPathDirty(); } -void CubicAsymmetricVertex::outDistanceChanged() -{ +void CubicAsymmetricVertex::outDistanceChanged() { m_OutValid = false; markPathDirty(); } \ No newline at end of file
diff --git a/src/shapes/cubic_detached_vertex.cpp b/src/shapes/cubic_detached_vertex.cpp index 3ed4137..83960c1 100644 --- a/src/shapes/cubic_detached_vertex.cpp +++ b/src/shapes/cubic_detached_vertex.cpp
@@ -4,39 +4,33 @@ using namespace rive; -void CubicDetachedVertex::computeIn() -{ +void CubicDetachedVertex::computeIn() { Vec2D::add(m_InPoint, Vec2D(x(), y()), Vec2D(cos(inRotation()) * inDistance(), sin(inRotation()) * inDistance())); } -void CubicDetachedVertex::computeOut() -{ +void CubicDetachedVertex::computeOut() { Vec2D::add(m_OutPoint, Vec2D(x(), y()), Vec2D(cos(outRotation()) * outDistance(), sin(outRotation()) * outDistance())); } -void CubicDetachedVertex::inRotationChanged() -{ +void CubicDetachedVertex::inRotationChanged() { m_InValid = false; markPathDirty(); } -void CubicDetachedVertex::inDistanceChanged() -{ +void CubicDetachedVertex::inDistanceChanged() { m_InValid = false; markPathDirty(); } -void CubicDetachedVertex::outRotationChanged() -{ +void CubicDetachedVertex::outRotationChanged() { m_OutValid = false; markPathDirty(); } -void CubicDetachedVertex::outDistanceChanged() -{ +void CubicDetachedVertex::outDistanceChanged() { m_OutValid = false; markPathDirty(); } \ No newline at end of file
diff --git a/src/shapes/cubic_mirrored_vertex.cpp b/src/shapes/cubic_mirrored_vertex.cpp index 7791050..340934f 100644 --- a/src/shapes/cubic_mirrored_vertex.cpp +++ b/src/shapes/cubic_mirrored_vertex.cpp
@@ -4,29 +4,25 @@ using namespace rive; -void CubicMirroredVertex::computeIn() -{ +void CubicMirroredVertex::computeIn() { Vec2D::add( m_InPoint, Vec2D(x(), y()), Vec2D(cos(rotation()) * -distance(), sin(rotation()) * -distance())); } -void CubicMirroredVertex::computeOut() -{ +void CubicMirroredVertex::computeOut() { Vec2D::add( m_OutPoint, Vec2D(x(), y()), Vec2D(cos(rotation()) * distance(), sin(rotation()) * distance())); } -void CubicMirroredVertex::rotationChanged() -{ +void CubicMirroredVertex::rotationChanged() { m_InValid = m_OutValid = false; markPathDirty(); } -void CubicMirroredVertex::distanceChanged() -{ +void CubicMirroredVertex::distanceChanged() { m_InValid = m_OutValid = false; markPathDirty(); } \ No newline at end of file
diff --git a/src/shapes/cubic_vertex.cpp b/src/shapes/cubic_vertex.cpp index de9ae5e..bd06c68 100644 --- a/src/shapes/cubic_vertex.cpp +++ b/src/shapes/cubic_vertex.cpp
@@ -2,75 +2,58 @@ #include "rive/bones/cubic_weight.hpp" using namespace rive; -const Vec2D& CubicVertex::renderIn() -{ - if (hasWeight()) - { +const Vec2D& CubicVertex::renderIn() { + if (hasWeight()) { return weight<CubicWeight>()->inTranslation(); - } - else - { + } else { return inPoint(); } } -const Vec2D& CubicVertex::renderOut() -{ - if (hasWeight()) - { +const Vec2D& CubicVertex::renderOut() { + if (hasWeight()) { return weight<CubicWeight>()->outTranslation(); - } - else - { + } else { return outPoint(); } } -const Vec2D& CubicVertex::inPoint() -{ - if (!m_InValid) - { +const Vec2D& CubicVertex::inPoint() { + if (!m_InValid) { computeIn(); m_InValid = true; } return m_InPoint; } -const Vec2D& CubicVertex::outPoint() -{ - if (!m_OutValid) - { +const Vec2D& CubicVertex::outPoint() { + if (!m_OutValid) { computeOut(); m_OutValid = true; } return m_OutPoint; } -void CubicVertex::outPoint(const Vec2D& value) -{ +void CubicVertex::outPoint(const Vec2D& value) { Vec2D::copy(m_OutPoint, value); m_OutValid = true; } -void CubicVertex::inPoint(const Vec2D& value) -{ +void CubicVertex::inPoint(const Vec2D& value) { Vec2D::copy(m_InPoint, value); m_InValid = true; } -void CubicVertex::xChanged() -{ +void CubicVertex::xChanged() { Super::xChanged(); m_InValid = m_OutValid = false; } -void CubicVertex::yChanged() -{ +void CubicVertex::yChanged() { Super::yChanged(); m_InValid = m_OutValid = false; } -void CubicVertex::deform(Mat2D& worldTransform, float* boneTransforms) -{ +void CubicVertex::deform(Mat2D& worldTransform, float* boneTransforms) { Super::deform(worldTransform, boneTransforms); auto cubicWeight = weight<CubicWeight>();
diff --git a/src/shapes/ellipse.cpp b/src/shapes/ellipse.cpp index 06489e6..474068a 100644 --- a/src/shapes/ellipse.cpp +++ b/src/shapes/ellipse.cpp
@@ -4,18 +4,15 @@ using namespace rive; -Ellipse::Ellipse() -{ +Ellipse::Ellipse() { addVertex(&m_Vertex1); addVertex(&m_Vertex2); addVertex(&m_Vertex3); addVertex(&m_Vertex4); } -void Ellipse::update(ComponentDirt value) -{ - if (hasDirt(value, ComponentDirt::Path)) - { +void Ellipse::update(ComponentDirt value) { + if (hasDirt(value, ComponentDirt::Path)) { auto radiusX = width() / 2.0f; auto radiusY = height() / 2.0f;
diff --git a/src/shapes/image.cpp b/src/shapes/image.cpp index d4ed0d9..4bc4b6a 100644 --- a/src/shapes/image.cpp +++ b/src/shapes/image.cpp
@@ -6,15 +6,12 @@ using namespace rive; -void Image::draw(Renderer* renderer) -{ - if (m_ImageAsset == nullptr || renderOpacity() == 0.0f) - { +void Image::draw(Renderer* renderer) { + if (m_ImageAsset == nullptr || renderOpacity() == 0.0f) { return; } - if (!clip(renderer)) - { + if (!clip(renderer)) { // We didn't clip, so make sure to save as we'll be doing some // transformations. renderer->save(); @@ -36,12 +33,10 @@ renderer->restore(); } -StatusCode Image::import(ImportStack& importStack) -{ +StatusCode Image::import(ImportStack& importStack) { auto backboardImporter = importStack.latest<BackboardImporter>(Backboard::typeKey); - if (backboardImporter == nullptr) - { + if (backboardImporter == nullptr) { return StatusCode::MissingObject; } backboardImporter->addFileAssetReferencer(this); @@ -49,21 +44,17 @@ return Super::import(importStack); } -void Image::assets(const std::vector<FileAsset*>& assets) -{ - if (assetId() < 0 || assetId() >= assets.size()) - { +void Image::assets(const std::vector<FileAsset*>& assets) { + if (assetId() < 0 || assetId() >= assets.size()) { return; } auto asset = assets[assetId()]; - if (asset->is<ImageAsset>()) - { + if (asset->is<ImageAsset>()) { m_ImageAsset = asset->as<ImageAsset>(); } } -Core* Image::clone() const -{ +Core* Image::clone() const { Image* twin = ImageBase::clone()->as<Image>(); twin->m_ImageAsset = m_ImageAsset; return twin;
diff --git a/src/shapes/metrics_path.cpp b/src/shapes/metrics_path.cpp index 3b3017b..e4c1800 100644 --- a/src/shapes/metrics_path.cpp +++ b/src/shapes/metrics_path.cpp
@@ -4,21 +4,16 @@ using namespace rive; -float clamp(float v, float lo, float hi) -{ - if (v < lo) - { +float clamp(float v, float lo, float hi) { + if (v < lo) { return lo; - } - else if (v > hi) - { + } else if (v > hi) { return hi; } return v; } -void MetricsPath::reset() -{ +void MetricsPath::reset() { m_ComputedLength = 0.0f; m_CubicSegments.clear(); m_Points.clear(); @@ -27,28 +22,24 @@ m_Paths.clear(); } -void MetricsPath::addPath(CommandPath* path, const Mat2D& transform) -{ +void MetricsPath::addPath(CommandPath* path, const Mat2D& transform) { MetricsPath* metricsPath = reinterpret_cast<MetricsPath*>(path); m_ComputedLength += metricsPath->computeLength(transform); m_Paths.emplace_back(metricsPath); } -void MetricsPath::moveTo(float x, float y) -{ +void MetricsPath::moveTo(float x, float y) { assert(m_Points.size() == 0); m_Points.emplace_back(Vec2D(x, y)); } -void MetricsPath::lineTo(float x, float y) -{ +void MetricsPath::lineTo(float x, float y) { m_Parts.push_back(PathPart(0, m_Points.size())); m_Points.emplace_back(Vec2D(x, y)); } void MetricsPath::cubicTo( - float ox, float oy, float ix, float iy, float x, float y) -{ + float ox, float oy, float ix, float iy, float x, float y) { m_Parts.push_back(PathPart(1, m_Points.size())); m_Points.emplace_back(Vec2D(ox, oy)); m_Points.emplace_back(Vec2D(ix, iy)); @@ -62,8 +53,7 @@ const Vec2D& toIn, const Vec2D& to, float t, - Vec2D* hull) -{ + Vec2D* hull) { Vec2D::lerp(hull[0], from, fromOut, t); Vec2D::lerp(hull[1], fromOut, toIn, t); Vec2D::lerp(hull[2], toIn, to, t); @@ -77,16 +67,14 @@ static const float minSegmentLength = 0.05f; static const float distTooFar = 1.0f; -static bool tooFar(const Vec2D& a, const Vec2D& b) -{ +static bool tooFar(const Vec2D& a, const Vec2D& b) { return std::max(std::abs(a[0] - b[0]), std::abs(a[1] - b[1])) > distTooFar; } static bool shouldSplitCubic(const Vec2D& from, const Vec2D& fromOut, const Vec2D& toIn, - const Vec2D& to) -{ + const Vec2D& to) { Vec2D oneThird, twoThird; Vec2D::lerp(oneThird, from, to, 1.0f / 3.0f); Vec2D::lerp(twoThird, from, to, 2.0f / 3.0f); @@ -100,11 +88,9 @@ float runningLength, float t1, float t2, - std::vector<CubicSegment>& segments) -{ + std::vector<CubicSegment>& segments) { - if (shouldSplitCubic(from, fromOut, toIn, to)) - { + if (shouldSplitCubic(from, fromOut, toIn, to)) { float halfT = (t1 + t2) / 2.0f; Vec2D hull[6]; @@ -120,25 +106,20 @@ segments); runningLength = segmentCubic( hull[5], hull[4], hull[2], to, runningLength, halfT, t2, segments); - } - else - { + } else { float length = Vec2D::distance(from, to); runningLength += length; - if (length > minSegmentLength) - { + if (length > minSegmentLength) { segments.emplace_back(CubicSegment(t2, runningLength)); } } return runningLength; } -float MetricsPath::computeLength(const Mat2D& transform) -{ +float MetricsPath::computeLength(const Mat2D& transform) { // If the pre-computed length is still valid (transformed with the same // transform) just return that. - if (!m_Lengths.empty() && transform == m_ComputedLengthTransform) - { + if (!m_Lengths.empty() && transform == m_ComputedLengthTransform) { return m_ComputedLength; } m_ComputedLengthTransform = transform; @@ -149,8 +130,7 @@ // transform is changing (path may not have been reset but got added with // another transform). m_TransformedPoints.resize(m_Points.size()); - for (size_t i = 0, l = m_Points.size(); i < l; i++) - { + for (size_t i = 0, l = m_Points.size(); i < l; i++) { Vec2D::transform(m_TransformedPoints[i], m_Points[i], transform); } @@ -161,12 +141,9 @@ int idx = 1; float length = 0.0f; - for (PathPart& part : m_Parts) - { - switch (part.type) - { - case PathPart::line: - { + for (PathPart& part : m_Parts) { + switch (part.type) { + case PathPart::line: { const Vec2D& point = m_TransformedPoints[idx++]; float partLength = Vec2D::distance(*pen, point); @@ -176,8 +153,7 @@ break; } // Anything above 0 is the number of cubic parts... - default: - { + default: { // Subdivide as necessary... // push in the parts @@ -208,16 +184,13 @@ void MetricsPath::trim(float startLength, float endLength, bool moveTo, - RenderPath* result) -{ + RenderPath* result) { assert(endLength >= startLength); - if (!m_Paths.empty()) - { + if (!m_Paths.empty()) { m_Paths.front()->trim(startLength, endLength, moveTo, result); return; } - if (startLength == endLength) - { + if (startLength == endLength) { // nothing to trim. return; } @@ -228,29 +201,24 @@ int firstPartIndex = -1, lastPartIndex = partCount - 1; float startT = 0.0f, endT = 1.0f; // Find first part. - for (int i = 0; i < partCount; i++) - { + for (int i = 0; i < partCount; i++) { float partLength = m_Lengths[i]; - if (length + partLength > startLength) - { + if (length + partLength > startLength) { firstPartIndex = i; startT = (startLength - length) / partLength; break; } length += partLength; } - if (firstPartIndex == -1) - { + if (firstPartIndex == -1) { // Couldn't find it. return; } // Find last part. - for (int i = firstPartIndex; i < partCount; i++) - { + for (int i = firstPartIndex; i < partCount; i++) { float partLength = m_Lengths[i]; - if (length + partLength >= endLength) - { + if (length + partLength >= endLength) { lastPartIndex = i; endT = (endLength - length) / partLength; break; @@ -262,27 +230,20 @@ startT = clamp(startT, 0.0f, 1.0f); endT = clamp(endT, 0.0f, 1.0f); - if (firstPartIndex == lastPartIndex) - { + if (firstPartIndex == lastPartIndex) { extractSubPart(firstPartIndex, startT, endT, moveTo, result); - } - else - { + } else { extractSubPart(firstPartIndex, startT, 1.0f, moveTo, result); - for (int i = firstPartIndex + 1; i < lastPartIndex; i++) - { + for (int i = firstPartIndex + 1; i < lastPartIndex; i++) { // add entire part... const PathPart& part = m_Parts[i]; - switch (part.type) - { - case PathPart::line: - { + switch (part.type) { + case PathPart::line: { const Vec2D& point = m_TransformedPoints[part.offset]; result->lineTo(point[0], point[1]); break; } - default: - { + default: { const Vec2D& point1 = m_TransformedPoints[part.offset]; const Vec2D& point2 = m_TransformedPoints[part.offset + 1]; const Vec2D& point3 = m_TransformedPoints[part.offset + 2]; @@ -303,20 +264,16 @@ float lerp(float from, float to, float f) { return from + f * (to - from); } void MetricsPath::extractSubPart( - int index, float startT, float endT, bool moveTo, RenderPath* result) -{ + int index, float startT, float endT, bool moveTo, RenderPath* result) { assert(startT >= 0.0f && startT <= 1.0f && endT >= 0.0f && endT <= 1.0f); const PathPart& part = m_Parts[index]; - switch (part.type) - { - case PathPart::line: - { + switch (part.type) { + case PathPart::line: { const Vec2D& from = m_TransformedPoints[part.offset - 1]; const Vec2D& to = m_TransformedPoints[part.offset]; Vec2D dir; Vec2D::subtract(dir, to, from); - if (moveTo) - { + if (moveTo) { Vec2D point; Vec2D::scaleAndAdd(point, from, dir, startT); result->moveTo(point[0], point[1]); @@ -326,29 +283,22 @@ break; } - default: - { + default: { auto startingSegmentIndex = part.type - 1; auto startEndSegmentIndex = startingSegmentIndex; auto endingSegmentIndex = startingSegmentIndex + part.numSegments; // Find cubicStartT and cubicEndT float length = m_Lengths[index]; - if (startT != 0.0f) - { + if (startT != 0.0f) { float startLength = startT * length; for (int si = startingSegmentIndex; si < endingSegmentIndex; - si++) - { + si++) { const CubicSegment& segment = m_CubicSegments[si]; - if (segment.length >= startLength) - { - if (si == startingSegmentIndex) - { + if (segment.length >= startLength) { + if (si == startingSegmentIndex) { startT = segment.t * (startLength / segment.length); - } - else - { + } else { float previousLength = m_CubicSegments[si - 1].length; @@ -366,21 +316,15 @@ } } - if (endT != 1.0f) - { + if (endT != 1.0f) { float endLength = endT * length; for (int si = startEndSegmentIndex; si < endingSegmentIndex; - si++) - { + si++) { const CubicSegment& segment = m_CubicSegments[si]; - if (segment.length >= endLength) - { - if (si == startingSegmentIndex) - { + if (segment.length >= endLength) { + if (si == startingSegmentIndex) { endT = segment.t * (endLength / segment.length); - } - else - { + } else { float previousLength = m_CubicSegments[si - 1].length; @@ -401,12 +345,10 @@ const Vec2D& toIn = m_TransformedPoints[part.offset + 1]; const Vec2D& to = m_TransformedPoints[part.offset + 2]; - if (startT == 0.0f) - { + if (startT == 0.0f) { // Start is 0, so split at end and keep the left side. computeHull(from, fromOut, toIn, to, endT, hull); - if (moveTo) - { + if (moveTo) { result->moveTo(from[0], from[1]); } result->cubicTo(hull[0][0], @@ -415,18 +357,14 @@ hull[3][1], hull[5][0], hull[5][1]); - } - else - { + } else { // Split at start since it's non 0. computeHull(from, fromOut, toIn, to, startT, hull); - if (moveTo) - { + if (moveTo) { // Move to first point on the right side. result->moveTo(hull[5][0], hull[5][1]); } - if (endT == 1.0f) - { + if (endT == 1.0f) { // End is 1, so no further split is necessary just cubicTo // the remaining right side. result->cubicTo(hull[4][0], @@ -435,9 +373,7 @@ hull[2][1], to[0], to[1]); - } - else - { + } else { // End is not 1, so split again and cubic to the left side // of the split and remap endT to the new curve range computeHull(hull[5], @@ -463,44 +399,37 @@ RenderMetricsPath::RenderMetricsPath() : m_RenderPath(makeRenderPath()) {} RenderMetricsPath::~RenderMetricsPath() { delete m_RenderPath; } -void RenderMetricsPath::addPath(CommandPath* path, const Mat2D& transform) -{ +void RenderMetricsPath::addPath(CommandPath* path, const Mat2D& transform) { MetricsPath::addPath(path, transform); m_RenderPath->addPath(path->renderPath(), transform); } -void RenderMetricsPath::reset() -{ +void RenderMetricsPath::reset() { MetricsPath::reset(); m_RenderPath->reset(); } -void RenderMetricsPath::moveTo(float x, float y) -{ +void RenderMetricsPath::moveTo(float x, float y) { MetricsPath::moveTo(x, y); m_RenderPath->moveTo(x, y); } -void RenderMetricsPath::lineTo(float x, float y) -{ +void RenderMetricsPath::lineTo(float x, float y) { MetricsPath::lineTo(x, y); m_RenderPath->lineTo(x, y); } void RenderMetricsPath::cubicTo( - float ox, float oy, float ix, float iy, float x, float y) -{ + float ox, float oy, float ix, float iy, float x, float y) { MetricsPath::cubicTo(ox, oy, ix, iy, x, y); m_RenderPath->cubicTo(ox, oy, ix, iy, x, y); } -void RenderMetricsPath::close() -{ +void RenderMetricsPath::close() { MetricsPath::close(); m_RenderPath->close(); } -void RenderMetricsPath::fillRule(FillRule value) -{ +void RenderMetricsPath::fillRule(FillRule value) { m_RenderPath->fillRule(value); }
diff --git a/src/shapes/paint/color.cpp b/src/shapes/paint/color.cpp index 06fbd52..0112ed4 100644 --- a/src/shapes/paint/color.cpp +++ b/src/shapes/paint/color.cpp
@@ -1,64 +1,48 @@ #include "rive/shapes/paint/color.hpp" #include <stdio.h> -namespace rive -{ - unsigned int colorARGB(int a, int r, int g, int b) - { +namespace rive { + unsigned int colorARGB(int a, int r, int g, int b) { return (((a & 0xff) << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | ((b & 0xff) << 0)) & 0xFFFFFFFF; } - unsigned int colorRed(ColorInt value) - { - return (0x00ff0000 & value) >> 16; - } + unsigned int colorRed(ColorInt value) { return (0x00ff0000 & value) >> 16; } - unsigned int colorGreen(ColorInt value) - { + unsigned int colorGreen(ColorInt value) { return (0x0000ff00 & value) >> 8; } - unsigned int colorBlue(ColorInt value) - { - return (0x000000ff & value) >> 0; - } + unsigned int colorBlue(ColorInt value) { return (0x000000ff & value) >> 0; } - unsigned int colorAlpha(ColorInt value) - { + unsigned int colorAlpha(ColorInt value) { return (0xff000000 & value) >> 24; } - float colorOpacity(ColorInt value) - { + float colorOpacity(ColorInt value) { return (float)colorAlpha(value) / 0xFF; } - ColorInt colorWithAlpha(ColorInt value, unsigned int a) - { + ColorInt colorWithAlpha(ColorInt value, unsigned int a) { return colorARGB( a, colorRed(value), colorGreen(value), colorBlue(value)); } - ColorInt colorWithOpacity(ColorInt value, float opacity) - { + ColorInt colorWithOpacity(ColorInt value, float opacity) { return colorWithAlpha(value, std::round(255.0 * opacity)); } - ColorInt colorModulateOpacity(ColorInt value, float opacity) - { + ColorInt colorModulateOpacity(ColorInt value, float opacity) { return colorWithAlpha( value, std::round(255.0f * colorOpacity(value) * opacity)); } - static unsigned int lerp(unsigned int a, unsigned int b, float mix) - { + static unsigned int lerp(unsigned int a, unsigned int b, float mix) { return a * (1.0f - mix) + b * mix; } - ColorInt colorLerp(ColorInt from, ColorInt to, float mix) - { + ColorInt colorLerp(ColorInt from, ColorInt to, float mix) { return colorARGB(lerp(colorAlpha(from), colorAlpha(to), mix), lerp(colorRed(from), colorRed(to), mix), lerp(colorGreen(from), colorGreen(to), mix),
diff --git a/src/shapes/paint/fill.cpp b/src/shapes/paint/fill.cpp index b7b99eb..e39fb78 100644 --- a/src/shapes/paint/fill.cpp +++ b/src/shapes/paint/fill.cpp
@@ -4,17 +4,14 @@ PathSpace Fill::pathSpace() const { return PathSpace::Local; } -RenderPaint* Fill::initRenderPaint(ShapePaintMutator* mutator) -{ +RenderPaint* Fill::initRenderPaint(ShapePaintMutator* mutator) { auto renderPaint = Super::initRenderPaint(mutator); renderPaint->style(RenderPaintStyle::fill); return renderPaint; } -void Fill::draw(Renderer* renderer, CommandPath* path) -{ - if (!isVisible()) - { +void Fill::draw(Renderer* renderer, CommandPath* path) { + if (!isVisible()) { return; } auto renderPath = path->renderPath();
diff --git a/src/shapes/paint/gradient_stop.cpp b/src/shapes/paint/gradient_stop.cpp index 098eea2..d8c1d8a 100644 --- a/src/shapes/paint/gradient_stop.cpp +++ b/src/shapes/paint/gradient_stop.cpp
@@ -3,27 +3,22 @@ using namespace rive; -StatusCode GradientStop::onAddedDirty(CoreContext* context) -{ +StatusCode GradientStop::onAddedDirty(CoreContext* context) { StatusCode code = Super::onAddedDirty(context); - if (code != StatusCode::Ok) - { + if (code != StatusCode::Ok) { return code; } - if (!parent()->is<LinearGradient>()) - { + if (!parent()->is<LinearGradient>()) { return StatusCode::MissingObject; } parent()->as<LinearGradient>()->addStop(this); return StatusCode::Ok; } -void GradientStop::colorValueChanged() -{ +void GradientStop::colorValueChanged() { parent()->as<LinearGradient>()->markGradientDirty(); } -void GradientStop::positionChanged() -{ +void GradientStop::positionChanged() { parent()->as<LinearGradient>()->markStopsDirty(); } \ No newline at end of file
diff --git a/src/shapes/paint/linear_gradient.cpp b/src/shapes/paint/linear_gradient.cpp index 77ae49d..273a39e 100644 --- a/src/shapes/paint/linear_gradient.cpp +++ b/src/shapes/paint/linear_gradient.cpp
@@ -10,26 +10,21 @@ using namespace rive; -StatusCode LinearGradient::onAddedDirty(CoreContext* context) -{ +StatusCode LinearGradient::onAddedDirty(CoreContext* context) { StatusCode code = Super::onAddedDirty(context); - if (code != StatusCode::Ok) - { + if (code != StatusCode::Ok) { return code; } - if (!initPaintMutator(this)) - { + if (!initPaintMutator(this)) { return StatusCode::MissingObject; } return StatusCode::Ok; } -void LinearGradient::buildDependencies() -{ +void LinearGradient::buildDependencies() { auto p = parent(); - if (p != nullptr && p->parent() != nullptr) - { + if (p != nullptr && p->parent() != nullptr) { auto parentsParent = p->parent(); // Parent's parent must be a shape paint container. assert(ShapePaintContainer::from(parentsParent) != nullptr); @@ -46,17 +41,14 @@ void LinearGradient::addStop(GradientStop* stop) { m_Stops.push_back(stop); } -static bool stopsComparer(GradientStop* a, GradientStop* b) -{ +static bool stopsComparer(GradientStop* a, GradientStop* b) { return a->position() < b->position(); } -void LinearGradient::update(ComponentDirt value) -{ +void LinearGradient::update(ComponentDirt value) { // Do the stops need to be re-ordered? bool stopsChanged = hasDirt(value, ComponentDirt::Stops); - if (stopsChanged) - { + if (stopsChanged) { std::sort(m_Stops.begin(), m_Stops.end(), stopsComparer); } @@ -72,16 +64,14 @@ ComponentDirt::Paint | ComponentDirt::RenderOpacity | ComponentDirt::Transform) || (paintsInWorldSpace && worldTransformed); - if (rebuildGradient) - { + if (rebuildGradient) { auto paint = renderPaint(); Vec2D start(startX(), startY()); Vec2D end(endX(), endY()); // Check if we need to update the world space gradient (if there's no // shape container, presumably it's the artboard and we're already in // world). - if (paintsInWorldSpace && m_ShapePaintContainer != nullptr) - { + if (paintsInWorldSpace && m_ShapePaintContainer != nullptr) { // Get the start and end of the gradient in world coordinates (world // transform of the shape). const Mat2D& world = m_ShapePaintContainer->worldTransform(); @@ -91,15 +81,12 @@ Vec2D worldEnd; Vec2D::transform(worldEnd, end, world); makeGradient(worldStart, worldEnd); - } - else - { + } else { makeGradient(start, end); } // build up the color and positions lists double ro = opacity() * renderOpacity(); - for (auto stop : m_Stops) - { + for (auto stop : m_Stops) { paint->addStop( colorModulateOpacity((unsigned int)stop->colorValue(), ro), stop->position()); @@ -108,14 +95,12 @@ } } -void LinearGradient::makeGradient(const Vec2D& start, const Vec2D& end) -{ +void LinearGradient::makeGradient(const Vec2D& start, const Vec2D& end) { renderPaint()->linearGradient(start[0], start[1], end[0], end[1]); } void LinearGradient::markGradientDirty() { addDirt(ComponentDirt::Paint); } -void LinearGradient::markStopsDirty() -{ +void LinearGradient::markStopsDirty() { addDirt(ComponentDirt::Paint | ComponentDirt::Stops); } @@ -136,5 +121,5 @@ return true; } } - return false; // all of our stops are opaque + return false; // all of our stops are opaque }
diff --git a/src/shapes/paint/radial_gradient.cpp b/src/shapes/paint/radial_gradient.cpp index e85e9d9..9598ff2 100644 --- a/src/shapes/paint/radial_gradient.cpp +++ b/src/shapes/paint/radial_gradient.cpp
@@ -3,7 +3,6 @@ using namespace rive; -void RadialGradient::makeGradient(const Vec2D& start, const Vec2D& end) -{ +void RadialGradient::makeGradient(const Vec2D& start, const Vec2D& end) { renderPaint()->radialGradient(start[0], start[1], end[0], end[1]); } \ No newline at end of file
diff --git a/src/shapes/paint/shape_paint.cpp b/src/shapes/paint/shape_paint.cpp index ecada79..174d82a 100644 --- a/src/shapes/paint/shape_paint.cpp +++ b/src/shapes/paint/shape_paint.cpp
@@ -7,26 +7,22 @@ ShapePaint::~ShapePaint() { delete m_RenderPaint; } -StatusCode ShapePaint::onAddedClean(CoreContext* context) -{ +StatusCode ShapePaint::onAddedClean(CoreContext* context) { auto container = ShapePaintContainer::from(parent()); - if (container == nullptr) - { + if (container == nullptr) { return StatusCode::MissingObject; } container->addPaint(this); return StatusCode::Ok; } -RenderPaint* ShapePaint::initRenderPaint(ShapePaintMutator* mutator) -{ +RenderPaint* ShapePaint::initRenderPaint(ShapePaintMutator* mutator) { assert(m_RenderPaint == nullptr); m_PaintMutator = mutator; return m_RenderPaint = makeRenderPaint(); } -void ShapePaint::blendMode(BlendMode value) -{ +void ShapePaint::blendMode(BlendMode value) { assert(m_RenderPaint != nullptr); m_RenderPaint->blendMode(value); } \ No newline at end of file
diff --git a/src/shapes/paint/shape_paint_mutator.cpp b/src/shapes/paint/shape_paint_mutator.cpp index 093e71b..534f744 100644 --- a/src/shapes/paint/shape_paint_mutator.cpp +++ b/src/shapes/paint/shape_paint_mutator.cpp
@@ -4,12 +4,10 @@ using namespace rive; -bool ShapePaintMutator::initPaintMutator(Component* component) -{ +bool ShapePaintMutator::initPaintMutator(Component* component) { auto parent = component->parent(); m_Component = component; - if (parent->is<ShapePaint>()) - { + if (parent->is<ShapePaint>()) { // Set this object as the mutator for the shape paint and get a // reference to the paint we'll be mutating. m_RenderPaint = parent->as<ShapePaint>()->initRenderPaint(this); @@ -18,10 +16,8 @@ return false; } -void ShapePaintMutator::renderOpacity(float value) -{ - if (m_RenderOpacity == value) - { +void ShapePaintMutator::renderOpacity(float value) { + if (m_RenderOpacity == value) { return; } m_RenderOpacity = value;
diff --git a/src/shapes/paint/solid_color.cpp b/src/shapes/paint/solid_color.cpp index 377888e..8c5078a 100644 --- a/src/shapes/paint/solid_color.cpp +++ b/src/shapes/paint/solid_color.cpp
@@ -5,29 +5,23 @@ using namespace rive; -StatusCode SolidColor::onAddedDirty(CoreContext* context) -{ +StatusCode SolidColor::onAddedDirty(CoreContext* context) { StatusCode code = Super::onAddedDirty(context); - if (code != StatusCode::Ok) - { + if (code != StatusCode::Ok) { return code; } - if (!initPaintMutator(this)) - { + if (!initPaintMutator(this)) { return StatusCode::MissingObject; } renderOpacityChanged(); return StatusCode::Ok; } -void SolidColor::renderOpacityChanged() -{ - if (renderPaint() == nullptr) - { +void SolidColor::renderOpacityChanged() { + if (renderPaint() == nullptr) { return; } - renderPaint()->color( - colorModulateOpacity(colorValue(), renderOpacity())); + renderPaint()->color(colorModulateOpacity(colorValue(), renderOpacity())); } void SolidColor::colorValueChanged() { renderOpacityChanged(); }
diff --git a/src/shapes/paint/stroke.cpp b/src/shapes/paint/stroke.cpp index 1127771..9891b28 100644 --- a/src/shapes/paint/stroke.cpp +++ b/src/shapes/paint/stroke.cpp
@@ -5,13 +5,11 @@ using namespace rive; -PathSpace Stroke::pathSpace() const -{ +PathSpace Stroke::pathSpace() const { return transformAffectsStroke() ? PathSpace::Local : PathSpace::World; } -RenderPaint* Stroke::initRenderPaint(ShapePaintMutator* mutator) -{ +RenderPaint* Stroke::initRenderPaint(ShapePaintMutator* mutator) { auto renderPaint = Super::initRenderPaint(mutator); renderPaint->style(RenderPaintStyle::stroke); renderPaint->thickness(thickness()); @@ -20,20 +18,16 @@ return renderPaint; } -bool Stroke::isVisible() const -{ +bool Stroke::isVisible() const { return Super::isVisible() && thickness() > 0.0f; } -void Stroke::draw(Renderer* renderer, CommandPath* path) -{ - if (!isVisible()) - { +void Stroke::draw(Renderer* renderer, CommandPath* path) { + if (!isVisible()) { return; } - if (m_Effect != nullptr) - { + if (m_Effect != nullptr) { /// We're guaranteed to get a metrics path here if we have an effect. path = m_Effect->effectPath(reinterpret_cast<MetricsPath*>(path)); } @@ -41,30 +35,25 @@ renderer->drawPath(path->renderPath(), m_RenderPaint); } -void Stroke::thicknessChanged() -{ +void Stroke::thicknessChanged() { assert(m_RenderPaint != nullptr); m_RenderPaint->thickness(thickness()); } -void Stroke::capChanged() -{ +void Stroke::capChanged() { assert(m_RenderPaint != nullptr); m_RenderPaint->cap((StrokeCap)cap()); } -void Stroke::joinChanged() -{ +void Stroke::joinChanged() { assert(m_RenderPaint != nullptr); m_RenderPaint->join((StrokeJoin)join()); } void Stroke::addStrokeEffect(StrokeEffect* effect) { m_Effect = effect; } -void Stroke::invalidateEffects() -{ - if (m_Effect != nullptr) - { +void Stroke::invalidateEffects() { + if (m_Effect != nullptr) { m_Effect->invalidateEffect(); } } \ No newline at end of file
diff --git a/src/shapes/paint/trim_path.cpp b/src/shapes/paint/trim_path.cpp index d9d9039..3d2e8d8 100644 --- a/src/shapes/paint/trim_path.cpp +++ b/src/shapes/paint/trim_path.cpp
@@ -7,10 +7,8 @@ TrimPath::TrimPath() : m_TrimmedPath(makeRenderPath()) {} TrimPath::~TrimPath() { delete m_TrimmedPath; } -StatusCode TrimPath::onAddedClean(CoreContext* context) -{ - if (!parent()->is<Stroke>()) - { +StatusCode TrimPath::onAddedClean(CoreContext* context) { + if (!parent()->is<Stroke>()) { return StatusCode::InvalidObject; } @@ -19,10 +17,8 @@ return StatusCode::Ok; } -RenderPath* TrimPath::effectPath(MetricsPath* source) -{ - if (m_RenderPath != nullptr) - { +RenderPath* TrimPath::effectPath(MetricsPath* source) { + if (m_RenderPath != nullptr) { return m_RenderPath; } @@ -31,86 +27,70 @@ m_TrimmedPath->reset(); auto renderOffset = std::fmod(std::fmod(offset(), 1.0f) + 1.0f, 1.0f); - switch (modeValue()) - { - case 1: - { + switch (modeValue()) { + case 1: { float totalLength = source->length(); auto startLength = totalLength * (start() + renderOffset); auto endLength = totalLength * (end() + renderOffset); - if (endLength < startLength) - { + if (endLength < startLength) { float swap = startLength; startLength = endLength; endLength = swap; } - if (startLength > totalLength) - { + if (startLength > totalLength) { startLength -= totalLength; endLength -= totalLength; } int i = 0, subPathCount = (int)subPaths.size(); - while (endLength > 0) - { + while (endLength > 0) { auto path = subPaths[i % subPathCount]; auto pathLength = path->length(); - if (startLength < pathLength) - { + if (startLength < pathLength) { path->trim(startLength, endLength, true, m_TrimmedPath); endLength -= pathLength; startLength = 0; - } - else - { + } else { startLength -= pathLength; endLength -= pathLength; } i++; } - } - break; + } break; - case 2: - { - for (auto path : subPaths) - { + case 2: { + for (auto path : subPaths) { auto pathLength = path->length(); auto startLength = pathLength * (start() + renderOffset); auto endLength = pathLength * (end() + renderOffset); - if (endLength < startLength) - { + if (endLength < startLength) { auto length = startLength; startLength = endLength; endLength = length; } - if (startLength > pathLength) - { + if (startLength > pathLength) { startLength -= pathLength; endLength -= pathLength; } path->trim(startLength, endLength, true, m_TrimmedPath); - while (endLength > pathLength) - { + while (endLength > pathLength) { startLength = 0; endLength -= pathLength; path->trim(startLength, endLength, true, m_TrimmedPath); } } - } - break; + } break; } m_RenderPath = m_TrimmedPath; return m_RenderPath; } -void TrimPath::invalidateEffect() -{ +void TrimPath::invalidateEffect() { m_RenderPath = nullptr; parent()->as<Stroke>()->parent()->addDirt(ComponentDirt::Paint); }
diff --git a/src/shapes/path.cpp b/src/shapes/path.cpp index a0bfdab..2b503ea 100644 --- a/src/shapes/path.cpp +++ b/src/shapes/path.cpp
@@ -12,21 +12,17 @@ Path::~Path() { delete m_CommandPath; } -StatusCode Path::onAddedDirty(CoreContext* context) -{ +StatusCode Path::onAddedDirty(CoreContext* context) { StatusCode code = Super::onAddedDirty(context); - if (code != StatusCode::Ok) - { + if (code != StatusCode::Ok) { return code; } return StatusCode::Ok; } -StatusCode Path::onAddedClean(CoreContext* context) -{ +StatusCode Path::onAddedClean(CoreContext* context) { StatusCode code = Super::onAddedClean(context); - if (code != StatusCode::Ok) - { + if (code != StatusCode::Ok) { return code; } @@ -34,8 +30,7 @@ for (auto currentParent = parent(); currentParent != nullptr; currentParent = currentParent->parent()) { - if (currentParent->is<Shape>()) - { + if (currentParent->is<Shape>()) { m_Shape = currentParent->as<Shape>(); m_Shape->addPath(this); return StatusCode::Ok; @@ -45,8 +40,7 @@ return StatusCode::MissingObject; } -void Path::buildDependencies() -{ +void Path::buildDependencies() { Super::buildDependencies(); // Make sure this is called once the shape has all of the paints added // (paints get added during the added cycle so buildDependencies is a good @@ -60,13 +54,11 @@ static void buildPath(CommandPath& commandPath, bool isClosed, - const std::vector<PathVertex*>& vertices) -{ + const std::vector<PathVertex*>& vertices) { commandPath.reset(); auto length = vertices.size(); - if (length < 2) - { + if (length < 2) { return; } auto firstPoint = vertices[0]; @@ -79,8 +71,7 @@ float startInX, startInY; bool startIsCubic; - if (firstPoint->is<CubicVertex>()) - { + if (firstPoint->is<CubicVertex>()) { auto cubic = firstPoint->as<CubicVertex>(); startIsCubic = prevIsCubic = true; auto inPoint = cubic->renderIn(); @@ -91,14 +82,11 @@ outY = outPoint[1]; auto translation = cubic->renderTranslation(); commandPath.moveTo(startX = translation[0], startY = translation[1]); - } - else - { + } else { startIsCubic = prevIsCubic = false; auto point = *firstPoint->as<StraightVertex>(); - if (auto radius = point.radius(); radius > 0.0f) - { + if (auto radius = point.radius(); radius > 0.0f) { auto prev = vertices[length - 1]; Vec2D pos = point.renderTranslation(); @@ -149,21 +137,17 @@ outX = posNext[0], outY = posNext[1]); prevIsCubic = false; - } - else - { + } else { auto translation = point.renderTranslation(); commandPath.moveTo(startInX = startX = outX = translation[0], startInY = startY = outY = translation[1]); } } - for (size_t i = 1; i < length; i++) - { + for (size_t i = 1; i < length; i++) { auto vertex = vertices[i]; - if (vertex->is<CubicVertex>()) - { + if (vertex->is<CubicVertex>()) { auto cubic = vertex->as<CubicVertex>(); auto inPoint = cubic->renderIn(); auto translation = cubic->renderTranslation(); @@ -179,14 +163,11 @@ auto outPoint = cubic->renderOut(); outX = outPoint[0]; outY = outPoint[1]; - } - else - { + } else { auto point = *vertex->as<StraightVertex>(); Vec2D pos = point.renderTranslation(); - if (auto radius = point.radius(); radius > 0.0f) - { + if (auto radius = point.radius(); radius > 0.0f) { Vec2D toPrev; Vec2D::subtract(toPrev, Vec2D(outX, outY), pos); auto toPrevLength = Vec2D::length(toPrev); @@ -210,17 +191,14 @@ Vec2D translation; Vec2D::scaleAndAdd(translation, pos, toPrev, renderRadius); - if (prevIsCubic) - { + if (prevIsCubic) { commandPath.cubicTo(outX, outY, translation[0], translation[1], translation[0], translation[1]); - } - else - { + } else { commandPath.lineTo(translation[0], translation[1]); } @@ -241,9 +219,7 @@ outX = posNext[0], outY = posNext[1]); prevIsCubic = false; - } - else if (prevIsCubic) - { + } else if (prevIsCubic) { float x = pos[0]; float y = pos[1]; commandPath.cubicTo(outX, outY, x, y, x, y); @@ -251,51 +227,39 @@ prevIsCubic = false; outX = x; outY = y; - } - else - { + } else { commandPath.lineTo(outX = pos[0], outY = pos[1]); } } } - if (isClosed) - { - if (prevIsCubic || startIsCubic) - { + if (isClosed) { + if (prevIsCubic || startIsCubic) { commandPath.cubicTo(outX, outY, startInX, startInY, startX, startY); - } - else - { + } else { commandPath.lineTo(startX, startY); } commandPath.close(); } } -void Path::markPathDirty() -{ +void Path::markPathDirty() { addDirt(ComponentDirt::Path); - if (m_Shape != nullptr) - { + if (m_Shape != nullptr) { m_Shape->pathChanged(); } } -void Path::onDirty(ComponentDirt value) -{ - if (hasDirt(value, ComponentDirt::WorldTransform) && m_Shape != nullptr) - { +void Path::onDirty(ComponentDirt value) { + if (hasDirt(value, ComponentDirt::WorldTransform) && m_Shape != nullptr) { m_Shape->pathChanged(); } } -void Path::update(ComponentDirt value) -{ +void Path::update(ComponentDirt value) { Super::update(value); assert(m_CommandPath != nullptr); - if (hasDirt(value, ComponentDirt::Path)) - { + if (hasDirt(value, ComponentDirt::Path)) { buildPath(*m_CommandPath, isPathClosed(), m_Vertices); } // if (hasDirt(value, ComponentDirt::WorldTransform) && m_Shape != nullptr) @@ -309,8 +273,7 @@ #ifdef ENABLE_QUERY_FLAT_VERTICES -class DisplayCubicVertex : public CubicVertex -{ +class DisplayCubicVertex : public CubicVertex { public: DisplayCubicVertex(const Vec2D& in, const Vec2D& out, @@ -329,23 +292,19 @@ void computeOut() override {} }; -FlattenedPath* Path::makeFlat(bool transformToParent) -{ - if (m_Vertices.empty()) - { +FlattenedPath* Path::makeFlat(bool transformToParent) { + if (m_Vertices.empty()) { return nullptr; } // Path transform always puts the path into world space. auto transform = pathTransform(); - if (transformToParent && parent()->is<TransformComponent>()) - { + if (transformToParent && parent()->is<TransformComponent>()) { // Put the transform in parent space. auto world = parent()->as<TransformComponent>()->worldTransform(); Mat2D inverseWorld; - if (!Mat2D::invert(inverseWorld, world)) - { + if (!Mat2D::invert(inverseWorld, world)) { Mat2D::identity(inverseWorld); } Mat2D::multiply(transform, inverseWorld, transform); @@ -355,18 +314,14 @@ auto length = m_Vertices.size(); PathVertex* previous = isPathClosed() ? m_Vertices[length - 1] : nullptr; bool deletePrevious = false; - for (size_t i = 0; i < length; i++) - { + for (size_t i = 0; i < length; i++) { auto vertex = m_Vertices[i]; - switch (vertex->coreType()) - { - case StraightVertex::typeKey: - { + switch (vertex->coreType()) { + case StraightVertex::typeKey: { auto point = *vertex->as<StraightVertex>(); if (point.radius() > 0.0f && - (isPathClosed() || (i != 0 && i != length - 1))) - { + (isPathClosed() || (i != 0 && i != length - 1))) { auto next = m_Vertices[(i + 1) % length]; Vec2D prevPoint = @@ -415,8 +370,7 @@ new DisplayCubicVertex(in, translation, translation); flat->addVertex(v2, transform); - if (deletePrevious) - { + if (deletePrevious) { delete previous; } previous = v2; @@ -425,8 +379,7 @@ } } default: - if (deletePrevious) - { + if (deletePrevious) { delete previous; } previous = vertex; @@ -435,19 +388,16 @@ break; } } - if (deletePrevious) - { + if (deletePrevious) { delete previous; } return flat; } -void FlattenedPath::addVertex(PathVertex* vertex, const Mat2D& transform) -{ +void FlattenedPath::addVertex(PathVertex* vertex, const Mat2D& transform) { // To make this easy and relatively clean we just transform the vertices. // Requires the vertex to be passed in as a clone. - if (vertex->is<CubicVertex>()) - { + if (vertex->is<CubicVertex>()) { auto cubic = vertex->as<CubicVertex>(); // Cubics need to be transformed so we create a Display version which @@ -459,9 +409,7 @@ auto displayCubic = new DisplayCubicVertex(in, out, translation); m_Vertices.push_back(displayCubic); - } - else - { + } else { auto point = new PathVertex(); Vec2D translation; Vec2D::transform(translation, vertex->renderTranslation(), transform); @@ -471,10 +419,8 @@ } } -FlattenedPath::~FlattenedPath() -{ - for (auto vertex : m_Vertices) - { +FlattenedPath::~FlattenedPath() { + for (auto vertex : m_Vertices) { delete vertex; } }
diff --git a/src/shapes/path_composer.cpp b/src/shapes/path_composer.cpp index 91e47b1..a6483c5 100644 --- a/src/shapes/path_composer.cpp +++ b/src/shapes/path_composer.cpp
@@ -9,64 +9,48 @@ static Mat2D identity; PathComposer::PathComposer(Shape* shape) : m_Shape(shape) {} -PathComposer::~PathComposer() -{ +PathComposer::~PathComposer() { delete m_LocalPath; delete m_WorldPath; } -void PathComposer::buildDependencies() -{ +void PathComposer::buildDependencies() { assert(m_Shape != nullptr); m_Shape->addDependent(this); - for (auto path : m_Shape->paths()) - { + for (auto path : m_Shape->paths()) { path->addDependent(this); } } -void PathComposer::update(ComponentDirt value) -{ - if (hasDirt(value, ComponentDirt::Path)) - { +void PathComposer::update(ComponentDirt value) { + if (hasDirt(value, ComponentDirt::Path)) { auto space = m_Shape->pathSpace(); - if ((space & PathSpace::Local) == PathSpace::Local) - { - if (m_LocalPath == nullptr) - { + if ((space & PathSpace::Local) == PathSpace::Local) { + if (m_LocalPath == nullptr) { m_LocalPath = m_Shape->makeCommandPath(PathSpace::Local); - } - else - { + } else { m_LocalPath->reset(); } auto world = m_Shape->worldTransform(); Mat2D inverseWorld; - if (!Mat2D::invert(inverseWorld, world)) - { + if (!Mat2D::invert(inverseWorld, world)) { Mat2D::identity(inverseWorld); } // Get all the paths into local shape space. - for (auto path : m_Shape->paths()) - { + for (auto path : m_Shape->paths()) { Mat2D localTransform; const Mat2D& transform = path->pathTransform(); Mat2D::multiply(localTransform, inverseWorld, transform); m_LocalPath->addPath(path->commandPath(), localTransform); } } - if ((space & PathSpace::World) == PathSpace::World) - { - if (m_WorldPath == nullptr) - { + if ((space & PathSpace::World) == PathSpace::World) { + if (m_WorldPath == nullptr) { m_WorldPath = m_Shape->makeCommandPath(PathSpace::World); - } - else - { + } else { m_WorldPath->reset(); } - for (auto path : m_Shape->paths()) - { + for (auto path : m_Shape->paths()) { const Mat2D& transform = path->pathTransform(); m_WorldPath->addPath(path->commandPath(), transform); }
diff --git a/src/shapes/path_vertex.cpp b/src/shapes/path_vertex.cpp index 0359ac5..220a68f 100644 --- a/src/shapes/path_vertex.cpp +++ b/src/shapes/path_vertex.cpp
@@ -3,34 +3,27 @@ using namespace rive; -Vec2D PathVertex::renderTranslation() -{ - if (hasWeight()) - { +Vec2D PathVertex::renderTranslation() { + if (hasWeight()) { return m_Weight->translation(); } return Vec2D(x(), y()); } -StatusCode PathVertex::onAddedDirty(CoreContext* context) -{ +StatusCode PathVertex::onAddedDirty(CoreContext* context) { StatusCode code = Super::onAddedDirty(context); - if (code != StatusCode::Ok) - { + if (code != StatusCode::Ok) { return code; } - if (!parent()->is<Path>()) - { + if (!parent()->is<Path>()) { return StatusCode::MissingObject; } parent()->as<Path>()->addVertex(this); return StatusCode::Ok; } -void PathVertex::markPathDirty() -{ - if (parent() == nullptr) - { +void PathVertex::markPathDirty() { + if (parent() == nullptr) { // This is an acceptable condition as the parametric paths create points // that are not part of the core context. return; @@ -41,8 +34,7 @@ void PathVertex::xChanged() { markPathDirty(); } void PathVertex::yChanged() { markPathDirty(); } -void PathVertex::deform(Mat2D& worldTransform, float* boneTransforms) -{ +void PathVertex::deform(Mat2D& worldTransform, float* boneTransforms) { Weight::deform(x(), y(), m_Weight->indices(),
diff --git a/src/shapes/points_path.cpp b/src/shapes/points_path.cpp index ce5da10..346d611 100644 --- a/src/shapes/points_path.cpp +++ b/src/shapes/points_path.cpp
@@ -4,37 +4,29 @@ using namespace rive; Mat2D identity; -void PointsPath::buildDependencies() -{ +void PointsPath::buildDependencies() { Super::buildDependencies(); - if (skin() != nullptr) - { + if (skin() != nullptr) { skin()->addDependent(this); } } -const Mat2D& PointsPath::pathTransform() const -{ - if (skin() != nullptr) - { +const Mat2D& PointsPath::pathTransform() const { + if (skin() != nullptr) { return identity; } return worldTransform(); } -void PointsPath::update(ComponentDirt value) -{ - if (hasDirt(value, ComponentDirt::Path) && skin() != nullptr) - { +void PointsPath::update(ComponentDirt value) { + if (hasDirt(value, ComponentDirt::Path) && skin() != nullptr) { skin()->deform(m_Vertices); } Super::update(value); } -void PointsPath::markPathDirty() -{ - if (skin() != nullptr) - { +void PointsPath::markPathDirty() { + if (skin() != nullptr) { skin()->addDirt(ComponentDirt::Path); } Super::markPathDirty();
diff --git a/src/shapes/polygon.cpp b/src/shapes/polygon.cpp index bbac031..f5704e6 100644 --- a/src/shapes/polygon.cpp +++ b/src/shapes/polygon.cpp
@@ -15,8 +15,7 @@ std::size_t Polygon::vertexCount() { return points(); } -void Polygon::buildPolygon() -{ +void Polygon::buildPolygon() { auto halfWidth = width() / 2; auto halfHeight = height() / 2; @@ -26,8 +25,7 @@ auto angle = -M_PI / 2; auto inc = 2 * M_PI / points(); - for (StraightVertex& vertex : m_PolygonVertices) - { + for (StraightVertex& vertex : m_PolygonVertices) { vertex.x(ox + cos(angle) * halfWidth); vertex.y(oy + sin(angle) * halfHeight); vertex.radius(cornerRadius()); @@ -35,16 +33,12 @@ } } -void Polygon::update(ComponentDirt value) -{ - if (hasDirt(value, ComponentDirt::Path)) - { - if (m_PolygonVertices.size() != vertexCount()) - { +void Polygon::update(ComponentDirt value) { + if (hasDirt(value, ComponentDirt::Path)) { + if (m_PolygonVertices.size() != vertexCount()) { m_PolygonVertices.resize(vertexCount()); m_Vertices.clear(); - for (StraightVertex& vertex : m_PolygonVertices) - { + for (StraightVertex& vertex : m_PolygonVertices) { m_Vertices.push_back(&vertex); } }
diff --git a/src/shapes/rectangle.cpp b/src/shapes/rectangle.cpp index e70cb0e..84eed38 100644 --- a/src/shapes/rectangle.cpp +++ b/src/shapes/rectangle.cpp
@@ -2,8 +2,7 @@ using namespace rive; -Rectangle::Rectangle() -{ +Rectangle::Rectangle() { addVertex(&m_Vertex1); addVertex(&m_Vertex2); addVertex(&m_Vertex3); @@ -15,10 +14,8 @@ void Rectangle::cornerRadiusBLChanged() { markPathDirty(); } void Rectangle::cornerRadiusBRChanged() { markPathDirty(); } -void Rectangle::update(ComponentDirt value) -{ - if (hasDirt(value, ComponentDirt::Path)) - { +void Rectangle::update(ComponentDirt value) { + if (hasDirt(value, ComponentDirt::Path)) { auto radius = cornerRadiusTL(); auto link = linkCornerRadius();
diff --git a/src/shapes/shape.cpp b/src/shapes/shape.cpp index e063f25..2ffe390 100644 --- a/src/shapes/shape.cpp +++ b/src/shapes/shape.cpp
@@ -9,51 +9,41 @@ Shape::Shape() : m_PathComposer(this) {} -void Shape::addPath(Path* path) -{ +void Shape::addPath(Path* path) { // Make sure the path is not already in the shape. assert(std::find(m_Paths.begin(), m_Paths.end(), path) == m_Paths.end()); m_Paths.push_back(path); } -void Shape::update(ComponentDirt value) -{ +void Shape::update(ComponentDirt value) { Super::update(value); - if (hasDirt(value, ComponentDirt::RenderOpacity)) - { - for (auto shapePaint : m_ShapePaints) - { + if (hasDirt(value, ComponentDirt::RenderOpacity)) { + for (auto shapePaint : m_ShapePaints) { shapePaint->renderOpacity(renderOpacity()); } } } -void Shape::pathChanged() -{ +void Shape::pathChanged() { m_PathComposer.addDirt(ComponentDirt::Path, true); invalidateStrokeEffects(); } -void Shape::draw(Renderer* renderer) -{ - if (renderOpacity() == 0.0f) - { +void Shape::draw(Renderer* renderer) { + if (renderOpacity() == 0.0f) { return; } auto shouldRestore = clip(renderer); - for (auto shapePaint : m_ShapePaints) - { - if (!shapePaint->isVisible()) - { + for (auto shapePaint : m_ShapePaints) { + if (!shapePaint->isVisible()) { continue; } renderer->save(); bool paintsInLocal = (shapePaint->pathSpace() & PathSpace::Local) == PathSpace::Local; - if (paintsInLocal) - { + if (paintsInLocal) { const Mat2D& transform = worldTransform(); renderer->transform(transform); } @@ -63,14 +53,12 @@ renderer->restore(); } - if (shouldRestore) - { + if (shouldRestore) { renderer->restore(); } } -void Shape::buildDependencies() -{ +void Shape::buildDependencies() { // Make sure to propagate the call to PathComposer as it's no longer part of // Core and owned only by the Shape. m_PathComposer.buildDependencies(); @@ -80,22 +68,18 @@ // Set the blend mode on all the shape paints. If we ever animate this // property, we'll need to update it in the update cycle/mark dirty when the // blend mode changes. - for (auto paint : m_ShapePaints) - { + for (auto paint : m_ShapePaints) { paint->blendMode(blendMode()); } } -void Shape::addDefaultPathSpace(PathSpace space) -{ +void Shape::addDefaultPathSpace(PathSpace space) { m_DefaultPathSpace |= space; } -StatusCode Shape::onAddedDirty(CoreContext* context) -{ +StatusCode Shape::onAddedDirty(CoreContext* context) { auto code = Super::onAddedDirty(context); - if (code != StatusCode::Ok) - { + if (code != StatusCode::Ok) { return code; } // This ensures context propagates to path composer too.
diff --git a/src/shapes/shape_paint_container.cpp b/src/shapes/shape_paint_container.cpp index 007a1f4..d90f059 100644 --- a/src/shapes/shape_paint_container.cpp +++ b/src/shapes/shape_paint_container.cpp
@@ -8,10 +8,8 @@ #include "rive/shapes/shape.hpp" using namespace rive; -ShapePaintContainer* ShapePaintContainer::from(Component* component) -{ - switch (component->coreType()) - { +ShapePaintContainer* ShapePaintContainer::from(Component* component) { + switch (component->coreType()) { case Artboard::typeKey: return component->as<Artboard>(); break; @@ -22,34 +20,27 @@ return nullptr; } -void ShapePaintContainer::addPaint(ShapePaint* paint) -{ +void ShapePaintContainer::addPaint(ShapePaint* paint) { m_ShapePaints.push_back(paint); } -PathSpace ShapePaintContainer::pathSpace() const -{ +PathSpace ShapePaintContainer::pathSpace() const { PathSpace space = m_DefaultPathSpace; - for (auto paint : m_ShapePaints) - { + for (auto paint : m_ShapePaints) { space |= paint->pathSpace(); } return space; } -void ShapePaintContainer::invalidateStrokeEffects() -{ - for (auto paint : m_ShapePaints) - { - if (paint->is<Stroke>()) - { +void ShapePaintContainer::invalidateStrokeEffects() { + for (auto paint : m_ShapePaints) { + if (paint->is<Stroke>()) { paint->as<Stroke>()->invalidateEffects(); } } } -CommandPath* ShapePaintContainer::makeCommandPath(PathSpace space) -{ +CommandPath* ShapePaintContainer::makeCommandPath(PathSpace space) { // Force a render path if we specifically request to use it for clipping or // this shape is used for clipping. bool needForRender = ((space | m_DefaultPathSpace) & PathSpace::Clipping) == @@ -57,34 +48,24 @@ bool needForEffects = false; - for (auto paint : m_ShapePaints) - { + for (auto paint : m_ShapePaints) { if (space != PathSpace::Neither && - (space & paint->pathSpace()) != space) - { + (space & paint->pathSpace()) != space) { continue; } - if (paint->is<Stroke>() && paint->as<Stroke>()->hasStrokeEffect()) - { + if (paint->is<Stroke>() && paint->as<Stroke>()->hasStrokeEffect()) { needForEffects = true; - } - else - { + } else { needForRender = true; } } - if (needForEffects && needForRender) - { + if (needForEffects && needForRender) { return new RenderMetricsPath(); - } - else if (needForEffects) - { + } else if (needForEffects) { return new OnlyMetricsPath(); - } - else - { + } else { return rive::makeRenderPath(); } } \ No newline at end of file
diff --git a/src/shapes/star.cpp b/src/shapes/star.cpp index 1aa29ff..52e4df7 100644 --- a/src/shapes/star.cpp +++ b/src/shapes/star.cpp
@@ -11,8 +11,7 @@ std::size_t Star::vertexCount() { return points() * 2; } -void Star::buildPolygon() -{ +void Star::buildPolygon() { auto halfWidth = width() / 2; auto halfHeight = height() / 2; auto innerHalfWidth = width() * innerRadius() / 2; @@ -24,8 +23,7 @@ auto angle = -M_PI / 2; auto inc = 2 * M_PI / length; - for (int i = 0; i < length; i += 2) - { + for (int i = 0; i < length; i += 2) { { StraightVertex& vertex = m_PolygonVertices[i]; vertex.x(ox + cos(angle) * halfWidth);
diff --git a/src/shapes/triangle.cpp b/src/shapes/triangle.cpp index 6b9ca51..5c9553d 100644 --- a/src/shapes/triangle.cpp +++ b/src/shapes/triangle.cpp
@@ -4,17 +4,14 @@ using namespace rive; -Triangle::Triangle() -{ +Triangle::Triangle() { addVertex(&m_Vertex1); addVertex(&m_Vertex2); addVertex(&m_Vertex3); } -void Triangle::update(ComponentDirt value) -{ - if (hasDirt(value, ComponentDirt::Path)) - { +void Triangle::update(ComponentDirt value) { + if (hasDirt(value, ComponentDirt::Path)) { auto ox = -originX() * width(); auto oy = -originY() * height();
diff --git a/src/transform_component.cpp b/src/transform_component.cpp index 9afb1e3..aa7b296 100644 --- a/src/transform_component.cpp +++ b/src/transform_component.cpp
@@ -6,8 +6,7 @@ using namespace rive; -StatusCode TransformComponent::onAddedClean(CoreContext* context) -{ +StatusCode TransformComponent::onAddedClean(CoreContext* context) { m_ParentTransformComponent = parent() != nullptr && parent()->is<WorldTransformComponent>() ? parent()->as<WorldTransformComponent>() @@ -15,31 +14,23 @@ return StatusCode::Ok; } -void TransformComponent::buildDependencies() -{ - if (parent() != nullptr) - { +void TransformComponent::buildDependencies() { + if (parent() != nullptr) { parent()->addDependent(this); } } -void TransformComponent::markTransformDirty() -{ - if (!addDirt(ComponentDirt::Transform)) - { +void TransformComponent::markTransformDirty() { + if (!addDirt(ComponentDirt::Transform)) { return; } markWorldTransformDirty(); } -void TransformComponent::updateTransform() -{ - if (rotation() != 0) - { +void TransformComponent::updateTransform() { + if (rotation() != 0) { Mat2D::fromRotation(m_Transform, rotation()); - } - else - { + } else { Mat2D::identity(m_Transform); } m_Transform[4] = x(); @@ -47,40 +38,30 @@ Mat2D::scaleByValues(m_Transform, scaleX(), scaleY()); } -void TransformComponent::updateWorldTransform() -{ - if (m_ParentTransformComponent != nullptr) - { +void TransformComponent::updateWorldTransform() { + if (m_ParentTransformComponent != nullptr) { Mat2D::multiply(m_WorldTransform, m_ParentTransformComponent->m_WorldTransform, m_Transform); - } - else - { + } else { Mat2D::copy(m_WorldTransform, m_Transform); } - for (auto constraint : m_Constraints) - { + for (auto constraint : m_Constraints) { constraint->constrain(this); } } -void TransformComponent::update(ComponentDirt value) -{ - if (hasDirt(value, ComponentDirt::Transform)) - { +void TransformComponent::update(ComponentDirt value) { + if (hasDirt(value, ComponentDirt::Transform)) { updateTransform(); } - if (hasDirt(value, ComponentDirt::WorldTransform)) - { + if (hasDirt(value, ComponentDirt::WorldTransform)) { updateWorldTransform(); } - if (hasDirt(value, ComponentDirt::RenderOpacity)) - { + if (hasDirt(value, ComponentDirt::RenderOpacity)) { m_RenderOpacity = opacity(); - if (m_ParentTransformComponent != nullptr) - { + if (m_ParentTransformComponent != nullptr) { m_RenderOpacity *= m_ParentTransformComponent->childOpacity(); } } @@ -94,7 +75,6 @@ void TransformComponent::scaleXChanged() { markTransformDirty(); } void TransformComponent::scaleYChanged() { markTransformDirty(); } -void TransformComponent::addConstraint(Constraint* constraint) -{ +void TransformComponent::addConstraint(Constraint* constraint) { m_Constraints.push_back(constraint); } \ No newline at end of file
diff --git a/src/world_transform_component.cpp b/src/world_transform_component.cpp index 571d853..ea3d931 100644 --- a/src/world_transform_component.cpp +++ b/src/world_transform_component.cpp
@@ -7,28 +7,23 @@ float WorldTransformComponent::childOpacity() { return opacity(); } -void WorldTransformComponent::markWorldTransformDirty() -{ +void WorldTransformComponent::markWorldTransformDirty() { addDirt(ComponentDirt::WorldTransform, true); } -const Mat2D& WorldTransformComponent::worldTransform() const -{ +const Mat2D& WorldTransformComponent::worldTransform() const { return m_WorldTransform; } -Mat2D& WorldTransformComponent::mutableWorldTransform() -{ +Mat2D& WorldTransformComponent::mutableWorldTransform() { return m_WorldTransform; } -void WorldTransformComponent::opacityChanged() -{ +void WorldTransformComponent::opacityChanged() { addDirt(ComponentDirt::RenderOpacity, true); } -void WorldTransformComponent::worldTranslation(Vec2D& result) const -{ +void WorldTransformComponent::worldTranslation(Vec2D& result) const { result[0] = m_WorldTransform[4]; result[1] = m_WorldTransform[5]; }
diff --git a/test/bound_bones_test.cpp b/test/bound_bones_test.cpp index 7ba5eb8..3aa01e1 100644 --- a/test/bound_bones_test.cpp +++ b/test/bound_bones_test.cpp
@@ -12,8 +12,7 @@ #include <catch.hpp> #include <cstdio> -TEST_CASE("bound bones load correctly", "[bones]") -{ +TEST_CASE("bound bones load correctly", "[bones]") { FILE* fp = fopen("../../test/assets/off_road_car.riv", "r"); REQUIRE(fp != nullptr); @@ -44,8 +43,7 @@ REQUIRE(pointsPath->skin()->tendons()[0]->bone() != nullptr); REQUIRE(pointsPath->skin()->tendons()[1]->bone() != nullptr); - for (auto vertex : path->vertices()) - { + for (auto vertex : path->vertices()) { REQUIRE(vertex->weight() != nullptr); }
diff --git a/test/clip_test.cpp b/test/clip_test.cpp index 4cb6444..1b60766 100644 --- a/test/clip_test.cpp +++ b/test/clip_test.cpp
@@ -8,8 +8,7 @@ #include <catch.hpp> #include <cstdio> -TEST_CASE("clipping loads correctly", "[clipping]") -{ +TEST_CASE("clipping loads correctly", "[clipping]") { FILE* fp = fopen("../../test/assets/circle_clips.riv", "r"); REQUIRE(fp != nullptr);
diff --git a/test/distance_constraint_test.cpp b/test/distance_constraint_test.cpp index ea65b3d..8b031ef 100644 --- a/test/distance_constraint_test.cpp +++ b/test/distance_constraint_test.cpp
@@ -7,8 +7,7 @@ #include "rive_testing.hpp" #include <cstdio> -TEST_CASE("distance constraints moves items as expected", "[file]") -{ +TEST_CASE("distance constraints moves items as expected", "[file]") { FILE* fp = fopen("../../test/assets/distance_constraint.riv", "r"); REQUIRE(fp != nullptr);
diff --git a/test/draw_order_test.cpp b/test/draw_order_test.cpp index 32ac1a7..1544e38 100644 --- a/test/draw_order_test.cpp +++ b/test/draw_order_test.cpp
@@ -8,8 +8,7 @@ #include <catch.hpp> #include <cstdio> -TEST_CASE("draw rules load and sort correctly", "[draw rules]") -{ +TEST_CASE("draw rules load and sort correctly", "[draw rules]") { FILE* fp = fopen("../../test/assets/draw_rule_cycle.riv", "r"); REQUIRE(fp != nullptr);
diff --git a/test/file_test.cpp b/test/file_test.cpp index ded420c..7744e2a 100644 --- a/test/file_test.cpp +++ b/test/file_test.cpp
@@ -7,8 +7,7 @@ #include <catch.hpp> #include <cstdio> -TEST_CASE("file can be read", "[file]") -{ +TEST_CASE("file can be read", "[file]") { FILE* fp = fopen("../../test/assets/two_artboards.riv", "r"); REQUIRE(fp != nullptr); @@ -35,8 +34,7 @@ delete[] bytes; } -TEST_CASE("file with animation can be read", "[file]") -{ +TEST_CASE("file with animation can be read", "[file]") { FILE* fp = fopen("../../test/assets/juice.riv", "r"); REQUIRE(fp != nullptr); @@ -77,8 +75,7 @@ delete[] bytes; } -TEST_CASE("artboards can be counted and accessed via index or name", "[file]") -{ +TEST_CASE("artboards can be counted and accessed via index or name", "[file]") { FILE* fp = fopen("../../test/assets/dependency_test.riv", "r"); REQUIRE(fp != nullptr); @@ -110,8 +107,7 @@ delete[] bytes; } -TEST_CASE("dependencies are as expected", "[file]") -{ +TEST_CASE("dependencies are as expected", "[file]") { // ┌────┐ // │Blue│ // └────┘
diff --git a/test/ik_constraint_test.cpp b/test/ik_constraint_test.cpp index 7fc38d7..c4beb4b 100644 --- a/test/ik_constraint_test.cpp +++ b/test/ik_constraint_test.cpp
@@ -9,8 +9,7 @@ #include "rive_testing.hpp" #include <cstdio> -TEST_CASE("ik with skinned bones orders correctly", "[file]") -{ +TEST_CASE("ik with skinned bones orders correctly", "[file]") { FILE* fp = fopen("../../test/assets/complex_ik_dependency.riv", "r"); REQUIRE(fp != nullptr); @@ -35,10 +34,8 @@ REQUIRE(artboard->find<rive::Bone>("Two") != nullptr); auto two = artboard->find<rive::Bone>("Two"); rive::Skin* skin = nullptr; - for (auto object : artboard->objects()) - { - if (object->is<rive::Skin>()) - { + for (auto object : artboard->objects()) { + if (object->is<rive::Skin>()) { skin = object->as<rive::Skin>(); break; }
diff --git a/test/ik_test.cpp b/test/ik_test.cpp index 1a10c99..2db9ada 100644 --- a/test/ik_test.cpp +++ b/test/ik_test.cpp
@@ -7,8 +7,7 @@ #include "rive_testing.hpp" #include <cstdio> -TEST_CASE("two bone ik places bones correctly", "[file]") -{ +TEST_CASE("two bone ik places bones correctly", "[file]") { FILE* fp = fopen("../../test/assets/two_bone_ik.riv", "r"); REQUIRE(fp != nullptr);
diff --git a/test/image_asset_test.cpp b/test/image_asset_test.cpp index 4ac1566..8d1f979 100644 --- a/test/image_asset_test.cpp +++ b/test/image_asset_test.cpp
@@ -10,8 +10,7 @@ #include <catch.hpp> #include <cstdio> -TEST_CASE("image assets loads correctly", "[assets]") -{ +TEST_CASE("image assets loads correctly", "[assets]") { FILE* fp = fopen("../../test/assets/walle.riv", "r"); REQUIRE(fp != nullptr); @@ -59,8 +58,7 @@ delete[] bytes; } -TEST_CASE("out of band image assets loads correctly", "[assets]") -{ +TEST_CASE("out of band image assets loads correctly", "[assets]") { std::string filename = "../../test/assets/out_of_band/walle.riv"; rive::RelativeLocalAssetResolver resolver(filename);
diff --git a/test/instancing_test.cpp b/test/instancing_test.cpp index 143a61b..4aaf13f 100644 --- a/test/instancing_test.cpp +++ b/test/instancing_test.cpp
@@ -8,8 +8,7 @@ #include <catch.hpp> #include <cstdio> -TEST_CASE("cloning an ellipse works", "[instancing]") -{ +TEST_CASE("cloning an ellipse works", "[instancing]") { FILE* fp = fopen("../../test/assets/circle_clips.riv", "r"); REQUIRE(fp != nullptr); @@ -39,8 +38,7 @@ delete[] bytes; } -TEST_CASE("instancing artboard clones clipped properties", "[instancing]") -{ +TEST_CASE("instancing artboard clones clipped properties", "[instancing]") { FILE* fp = fopen("../../test/assets/circle_clips.riv", "r"); REQUIRE(fp != nullptr); @@ -82,8 +80,7 @@ delete[] bytes; } -TEST_CASE("instancing artboard doesn't clone animations", "[instancing]") -{ +TEST_CASE("instancing artboard doesn't clone animations", "[instancing]") { FILE* fp = fopen("../../test/assets/juice.riv", "r"); REQUIRE(fp != nullptr);
diff --git a/test/linear_animation_instance_test.cpp b/test/linear_animation_instance_test.cpp index 416293a..11becbd 100644 --- a/test/linear_animation_instance_test.cpp +++ b/test/linear_animation_instance_test.cpp
@@ -4,8 +4,7 @@ #include <catch.hpp> #include <cstdio> -TEST_CASE("LinearAnimationInstance oneShot", "[animation]") -{ +TEST_CASE("LinearAnimationInstance oneShot", "[animation]") { rive::LinearAnimation* linearAnimation = new rive::LinearAnimation(); // duration in seconds is 5 linearAnimation->duration(10); @@ -33,8 +32,7 @@ delete linearAnimation; } -TEST_CASE("LinearAnimationInstance oneShot <-", "[animation]") -{ +TEST_CASE("LinearAnimationInstance oneShot <-", "[animation]") { rive::LinearAnimation* linearAnimation = new rive::LinearAnimation(); // duration in seconds is 5 linearAnimation->duration(10); @@ -78,8 +76,7 @@ delete linearAnimation; } -TEST_CASE("LinearAnimationInstance loop ->", "[animation]") -{ +TEST_CASE("LinearAnimationInstance loop ->", "[animation]") { rive::LinearAnimation* linearAnimation = new rive::LinearAnimation(); // duration in seconds is 5 linearAnimation->duration(10); @@ -107,8 +104,7 @@ delete linearAnimation; } -TEST_CASE("LinearAnimationInstance loop <-", "[animation]") -{ +TEST_CASE("LinearAnimationInstance loop <-", "[animation]") { rive::LinearAnimation* linearAnimation = new rive::LinearAnimation(); // duration in seconds is 5 linearAnimation->duration(10); @@ -146,8 +142,7 @@ delete linearAnimation; } -TEST_CASE("LinearAnimationInstance loop <- work area", "[animation]") -{ +TEST_CASE("LinearAnimationInstance loop <- work area", "[animation]") { rive::LinearAnimation* linearAnimation = new rive::LinearAnimation(); // duration in seconds is 50 linearAnimation->workStart(4); @@ -198,8 +193,7 @@ delete linearAnimation; } -TEST_CASE("LinearAnimationInstance pingpong ->", "[animation]") -{ +TEST_CASE("LinearAnimationInstance pingpong ->", "[animation]") { rive::LinearAnimation* linearAnimation = new rive::LinearAnimation(); // duration in seconds is 5 linearAnimation->duration(10); @@ -228,8 +222,7 @@ delete linearAnimation; } -TEST_CASE("LinearAnimationInstance pingpong <-", "[animation]") -{ +TEST_CASE("LinearAnimationInstance pingpong <-", "[animation]") { rive::LinearAnimation* linearAnimation = new rive::LinearAnimation(); // duration in seconds is 5 linearAnimation->duration(10); @@ -270,8 +263,7 @@ delete linearAnimation; } -TEST_CASE("LinearAnimationInstance override loop", "[animation]") -{ +TEST_CASE("LinearAnimationInstance override loop", "[animation]") { rive::LinearAnimation* linearAnimation = new rive::LinearAnimation(); // duration in seconds is 5 linearAnimation->duration(10);
diff --git a/test/metrics_path_test.cpp b/test/metrics_path_test.cpp index 44efab7..6e6bf4b 100644 --- a/test/metrics_path_test.cpp +++ b/test/metrics_path_test.cpp
@@ -1,8 +1,7 @@ #include <catch.hpp> #include <rive/shapes/metrics_path.hpp> -TEST_CASE("path metrics compute correctly", "[bezier]") -{ +TEST_CASE("path metrics compute correctly", "[bezier]") { // TODO: fix these based on new logic // Make a square with sides length 10. // rive::OnlyMetricsPath path;
diff --git a/test/no_op_renderer.cpp b/test/no_op_renderer.cpp index 6dee31a..5d8b131 100644 --- a/test/no_op_renderer.cpp +++ b/test/no_op_renderer.cpp
@@ -1,8 +1,7 @@ #include "no_op_renderer.hpp" #include <rive/renderer.hpp> -namespace rive -{ +namespace rive { RenderPaint* makeRenderPaint() { return new NoOpRenderPaint(); } RenderPath* makeRenderPath() { return new NoOpRenderPath(); } RenderImage* makeRenderImage() { return new NoOpRenderImage(); }
diff --git a/test/no_op_renderer.hpp b/test/no_op_renderer.hpp index 23253e8..3856319 100644 --- a/test/no_op_renderer.hpp +++ b/test/no_op_renderer.hpp
@@ -3,19 +3,15 @@ #include <rive/renderer.hpp> #include <vector> -namespace rive -{ - class NoOpRenderImage : public RenderImage - { +namespace rive { + class NoOpRenderImage : public RenderImage { public: - bool decode(const uint8_t* bytes, std::size_t size) override - { + bool decode(const uint8_t* bytes, std::size_t size) override { return true; } }; - class NoOpRenderPaint : public RenderPaint - { + class NoOpRenderPaint : public RenderPaint { public: void color(unsigned int value) override {} void style(RenderPaintStyle value) override {} @@ -30,17 +26,9 @@ void completeGradient() override {} }; - enum class NoOpPathCommandType - { - MoveTo, - LineTo, - CubicTo, - Reset, - Close - }; + enum class NoOpPathCommandType { MoveTo, LineTo, CubicTo, Reset, Close }; - struct NoOpPathCommand - { + struct NoOpPathCommand { NoOpPathCommandType command; float x; float y; @@ -50,12 +38,10 @@ float outY; }; - class NoOpRenderPath : public RenderPath - { + class NoOpRenderPath : public RenderPath { public: std::vector<NoOpPathCommand> commands; - void reset() override - { + void reset() override { commands.emplace_back((NoOpPathCommand){NoOpPathCommandType::Reset, 0.0f, 0.0f, @@ -69,24 +55,20 @@ void addPath(CommandPath* path, const Mat2D& transform) override {} void addRenderPath(RenderPath* path, const Mat2D& transform) override {} - void moveTo(float x, float y) override - { + void moveTo(float x, float y) override { commands.emplace_back((NoOpPathCommand){ NoOpPathCommandType::MoveTo, x, y, 0.0f, 0.0f, 0.0f, 0.0f}); } - void lineTo(float x, float y) override - { + void lineTo(float x, float y) override { commands.emplace_back((NoOpPathCommand){ NoOpPathCommandType::LineTo, x, y, 0.0f, 0.0f, 0.0f, 0.0f}); } void cubicTo( - float ox, float oy, float ix, float iy, float x, float y) override - { + float ox, float oy, float ix, float iy, float x, float y) override { commands.emplace_back((NoOpPathCommand){ NoOpPathCommandType::CubicTo, x, y, ix, iy, ox, oy}); } - void close() override - { + void close() override { commands.emplace_back((NoOpPathCommand){NoOpPathCommandType::Close, 0.0f, 0.0f, @@ -97,17 +79,15 @@ } }; - class NoOpRenderer : public Renderer - { + class NoOpRenderer : public Renderer { void save() override {} void restore() override {} void transform(const Mat2D& transform) override {} void drawPath(RenderPath* path, RenderPaint* paint) override {} void clipPath(RenderPath* path) override {} - void - drawImage(RenderImage* image, BlendMode value, float opacity) override - { - } + void drawImage(RenderImage* image, + BlendMode value, + float opacity) override {} }; } // namespace rive
diff --git a/test/node_test.cpp b/test/node_test.cpp index 0fecbad..36f371d 100644 --- a/test/node_test.cpp +++ b/test/node_test.cpp
@@ -3,8 +3,7 @@ TEST_CASE("Node instances", "[core]") { REQUIRE(rive::Node().x() == 0.0f); } -TEST_CASE("nodeX function return x value", "[node]") -{ +TEST_CASE("nodeX function return x value", "[node]") { rive::Node* node = new rive::Node(); REQUIRE(node->x() == 0.0f); node->x(2.0f);
diff --git a/test/path_test.cpp b/test/path_test.cpp index 4dbdb4a..86ffef5 100644 --- a/test/path_test.cpp +++ b/test/path_test.cpp
@@ -11,8 +11,7 @@ #include <catch.hpp> #include <cstdio> -TEST_CASE("rectangle path builds expected commands", "[path]") -{ +TEST_CASE("rectangle path builds expected commands", "[path]") { rive::Artboard* artboard = new rive::Artboard(); rive::Shape* shape = new rive::Shape(); rive::Rectangle* rectangle = new rive::Rectangle(); @@ -49,8 +48,7 @@ delete artboard; } -TEST_CASE("rounded rectangle path builds expected commands", "[path]") -{ +TEST_CASE("rounded rectangle path builds expected commands", "[path]") { rive::Artboard* artboard = new rive::Artboard(); rive::Shape* shape = new rive::Shape(); rive::Rectangle* rectangle = new rive::Rectangle(); @@ -114,8 +112,7 @@ delete artboard; } -TEST_CASE("ellipse path builds expected commands", "[path]") -{ +TEST_CASE("ellipse path builds expected commands", "[path]") { rive::Artboard* artboard = new rive::Artboard(); rive::Ellipse* ellipse = new rive::Ellipse(); rive::Shape* shape = new rive::Shape();
diff --git a/test/reader_test.cpp b/test/reader_test.cpp index 7a05e39..6de4489 100644 --- a/test/reader_test.cpp +++ b/test/reader_test.cpp
@@ -1,8 +1,7 @@ #include <catch.hpp> #include <rive/core/reader.h> -TEST_CASE("uint leb decoder", "[reader]") -{ +TEST_CASE("uint leb decoder", "[reader]") { uint64_t result; uint8_t encoded1[] = {0x01}; @@ -18,8 +17,7 @@ REQUIRE(result == 624485); } -TEST_CASE("string decoder", "[reader]") -{ +TEST_CASE("string decoder", "[reader]") { char* str = strdup("New Artboard"); uint8_t str_bytes[] = { 0x4E, 0x65, 0x77, 0x20, 0x41, 0x72, 0x74, 0x62, 0x6F, 0x61, 0x72, 0x64}; @@ -36,8 +34,7 @@ delete decoded_str; } -TEST_CASE("double decoder", "[reader]") -{ +TEST_CASE("double decoder", "[reader]") { double decoded_num; uint64_t bytes_read; @@ -63,8 +60,7 @@ REQUIRE(bytes_read == 0); } -TEST_CASE("float decoder", "[reader]") -{ +TEST_CASE("float decoder", "[reader]") { float decoded_num; uint64_t bytes_read; @@ -89,8 +85,7 @@ REQUIRE(bytes_read == 0); } -TEST_CASE("byte decoder", "[reader") -{ +TEST_CASE("byte decoder", "[reader") { uint8_t decoded_byte; // luigi: commented this out as it was giving a warning (I added -Wall to // the compiler flags). Warning was:
diff --git a/test/rive_testing.cpp b/test/rive_testing.cpp index aa7691e..ac27630 100644 --- a/test/rive_testing.cpp +++ b/test/rive_testing.cpp
@@ -1,12 +1,9 @@ #include "rive_testing.hpp" -bool aboutEqual(const rive::Mat2D& a, const rive::Mat2D& b) -{ +bool aboutEqual(const rive::Mat2D& a, const rive::Mat2D& b) { const float epsilon = 0.0001f; - for (int i = 0; i < 6; i++) - { - if (std::fabs(a[i] - b[i]) > epsilon) - { + for (int i = 0; i < 6; i++) { + if (std::fabs(a[i] - b[i]) > epsilon) { return false; } }
diff --git a/test/rive_testing.hpp b/test/rive_testing.hpp index cf7482a..0f49def 100644 --- a/test/rive_testing.hpp +++ b/test/rive_testing.hpp
@@ -7,12 +7,9 @@ bool aboutEqual(const rive::Mat2D& a, const rive::Mat2D& b); -namespace Catch -{ - template <> struct StringMaker<rive::Mat2D> - { - static std::string convert(rive::Mat2D const& value) - { +namespace Catch { + template <> struct StringMaker<rive::Mat2D> { + static std::string convert(rive::Mat2D const& value) { std::ostringstream os; os << value[0] << ", " << value[1] << ", " << value[2] << ", " << value[3] << ", " << value[4] << ", " << value[5];
diff --git a/test/rotation_constraint_test.cpp b/test/rotation_constraint_test.cpp index 0f75d44..7398795 100644 --- a/test/rotation_constraint_test.cpp +++ b/test/rotation_constraint_test.cpp
@@ -8,8 +8,7 @@ #include "rive_testing.hpp" #include <cstdio> -TEST_CASE("rotation constraint updates world transform", "[file]") -{ +TEST_CASE("rotation constraint updates world transform", "[file]") { FILE* fp = fopen("../../test/assets/rotation_constraint.riv", "r"); REQUIRE(fp != nullptr);
diff --git a/test/scale_constraint_test.cpp b/test/scale_constraint_test.cpp index c2722e3..c6e724a 100644 --- a/test/scale_constraint_test.cpp +++ b/test/scale_constraint_test.cpp
@@ -8,8 +8,7 @@ #include "rive_testing.hpp" #include <cstdio> -TEST_CASE("scale constraint updates world transform", "[file]") -{ +TEST_CASE("scale constraint updates world transform", "[file]") { FILE* fp = fopen("../../test/assets/scale_constraint.riv", "r"); REQUIRE(fp != nullptr);
diff --git a/test/state_machine_test.cpp b/test/state_machine_test.cpp index b2e1414..6bab974 100644 --- a/test/state_machine_test.cpp +++ b/test/state_machine_test.cpp
@@ -14,8 +14,7 @@ #include "catch.hpp" #include <cstdio> -TEST_CASE("file with state machine be read", "[file]") -{ +TEST_CASE("file with state machine be read", "[file]") { FILE* fp = fopen("../../test/assets/rocket.riv", "r"); REQUIRE(fp != nullptr); @@ -57,11 +56,9 @@ REQUIRE(layer->exitState() != nullptr); int foundAnimationStates = 0; - for (int i = 0; i < layer->stateCount(); i++) - { + for (int i = 0; i < layer->stateCount(); i++) { auto state = layer->state(i); - if (state->is<rive::AnimationState>()) - { + if (state->is<rive::AnimationState>()) { foundAnimationStates++; REQUIRE(state->as<rive::AnimationState>()->animation() != nullptr); } @@ -78,8 +75,7 @@ auto idleState = stateTo->as<rive::AnimationState>(); REQUIRE(idleState->transitionCount() == 2); - for (int i = 0; i < idleState->transitionCount(); i++) - { + for (int i = 0; i < idleState->transitionCount(); i++) { auto transition = idleState->transition(i); if (transition->stateTo() ->as<rive::AnimationState>() @@ -103,8 +99,7 @@ delete[] bytes; } -TEST_CASE("file with blend states loads correctly", "[file]") -{ +TEST_CASE("file with blend states loads correctly", "[file]") { FILE* fp = fopen("../../test/assets/blend_test.riv", "r"); REQUIRE(fp != nullptr); @@ -175,8 +170,7 @@ delete[] bytes; } -TEST_CASE("animation state with no animation doesn't crash", "[file]") -{ +TEST_CASE("animation state with no animation doesn't crash", "[file]") { FILE* fp = fopen("../../test/assets/multiple_state_machines.riv", "r"); REQUIRE(fp != nullptr);
diff --git a/test/stroke_test.cpp b/test/stroke_test.cpp index 84f059b..751a261 100644 --- a/test/stroke_test.cpp +++ b/test/stroke_test.cpp
@@ -10,8 +10,7 @@ #include <catch.hpp> #include <cstdio> -TEST_CASE("stroke can be looked up at runtime", "[file]") -{ +TEST_CASE("stroke can be looked up at runtime", "[file]") { FILE* fp = fopen("../../test/assets/stroke_name_test.riv", "r"); REQUIRE(fp != nullptr);
diff --git a/test/transform_constraint_test.cpp b/test/transform_constraint_test.cpp index 331ef49..b47c278 100644 --- a/test/transform_constraint_test.cpp +++ b/test/transform_constraint_test.cpp
@@ -7,8 +7,7 @@ #include "rive_testing.hpp" #include <cstdio> -TEST_CASE("transform constraint updates world transform", "[file]") -{ +TEST_CASE("transform constraint updates world transform", "[file]") { FILE* fp = fopen("../../test/assets/transform_constraint.riv", "r"); REQUIRE(fp != nullptr);
diff --git a/test/translation_constraint_test.cpp b/test/translation_constraint_test.cpp index 49da2e4..feb4bf7 100644 --- a/test/translation_constraint_test.cpp +++ b/test/translation_constraint_test.cpp
@@ -8,8 +8,7 @@ #include "rive_testing.hpp" #include <cstdio> -TEST_CASE("translation constraint updates world transform", "[file]") -{ +TEST_CASE("translation constraint updates world transform", "[file]") { FILE* fp = fopen("../../test/assets/translation_constraint.riv", "r"); REQUIRE(fp != nullptr);