diff --git a/Common/Cpp/MoveOnlyFunction.h b/Common/Cpp/MoveOnlyFunction.h new file mode 100644 index 0000000000..9cc71f3422 --- /dev/null +++ b/Common/Cpp/MoveOnlyFunction.h @@ -0,0 +1,118 @@ +/* Move-Only Function + * + * From: https://github.com/PokemonAutomation/ + * + * A callable wrapper that can be moved but not copied. + * + * Prefer this over std::function for a callback that has one owner. + * Copying a std::function copies its callable, so a stateful lambda + * silently splits into two independent states. And std::function cannot + * hold a lambda that captures a move-only object (e.g. std::unique_ptr). + * + * This is std::move_only_function (C++23) where the standard library has + * it. Apple's libc++ (Xcode 26 / Apple Clang 21) does not, so this header + * has a minimal fallback for the plain "R(Args...)" signature. Delete the + * fallback once every supported compiler defines + * __cpp_lib_move_only_function. + * + */ + +#ifndef PokemonAutomation_MoveOnlyFunction_H +#define PokemonAutomation_MoveOnlyFunction_H + +#include +#include + +#ifndef __cpp_lib_move_only_function +#include +#include +#include +#include +#endif + +namespace PokemonAutomation{ + + + +#ifdef __cpp_lib_move_only_function + +template +using MoveOnlyFunction = std::move_only_function; + +#else + +template +class MoveOnlyFunction; + +template +class MoveOnlyFunction{ +public: + MoveOnlyFunction() noexcept = default; + MoveOnlyFunction(std::nullptr_t) noexcept {} + + template + requires ( + !std::is_same_v, MoveOnlyFunction> && + std::is_invocable_r_v&, Args...> + ) + MoveOnlyFunction(Function&& function){ + using Stored = std::decay_t; + // Like std::move_only_function, a null function pointer makes an + // empty wrapper. + if constexpr (std::is_pointer_v || std::is_member_pointer_v){ + if (function == nullptr){ + return; + } + } + m_callable = std::make_unique>(std::forward(function)); + } + + MoveOnlyFunction(MoveOnlyFunction&&) noexcept = default; + MoveOnlyFunction& operator=(MoveOnlyFunction&&) noexcept = default; + MoveOnlyFunction(const MoveOnlyFunction&) = delete; + MoveOnlyFunction& operator=(const MoveOnlyFunction&) = delete; + + explicit operator bool() const noexcept{ + return m_callable != nullptr; + } + friend bool operator==(const MoveOnlyFunction& function, std::nullptr_t) noexcept{ + return !function; + } + + // Calling an empty wrapper is undefined, as for std::move_only_function. + R operator()(Args... args){ + return m_callable->call(std::forward(args)...); + } + + +private: + class Callable{ + public: + virtual ~Callable() = default; + virtual R call(Args&&... args) = 0; + }; + + template + class Holder final : public Callable{ + public: + template + explicit Holder(Source&& source) + : m_stored(std::forward(source)) + {} + virtual R call(Args&&... args) override{ + return std::invoke_r(m_stored, std::forward(args)...); + } + + private: + Stored m_stored; + }; + + std::unique_ptr m_callable; +}; + +#endif + + + +} +#endif diff --git a/Common/Cpp/MoveOnlyFunction_Tests.cpp b/Common/Cpp/MoveOnlyFunction_Tests.cpp new file mode 100644 index 0000000000..72ed5998ae --- /dev/null +++ b/Common/Cpp/MoveOnlyFunction_Tests.cpp @@ -0,0 +1,190 @@ +/* Move-Only Function Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "TestRunners/UnitTestDatabase.h" +#include "MoveOnlyFunction.h" +#include "MoveOnlyFunction_Tests.h" + +namespace PokemonAutomation{ +namespace{ + + + +// Copying would fork a stateful callable, so it must not compile. +static_assert(!std::is_copy_constructible_v>); +static_assert(!std::is_copy_assignable_v>); +static_assert(std::is_nothrow_move_constructible_v>); + + + +std::string expected_int(const char* what, int expected, int actual){ + return std::string(what) + ": expected " + std::to_string(expected) + + ", got " + std::to_string(actual); +} + + + +class Test_MoveOnlyFunction_MoveOnlyCapture : public UnitTest{ +public: + Test_MoveOnlyFunction_MoveOnlyCapture() + : UnitTest("Common::MoveOnlyFunction - Move-only capture") + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + auto value = std::make_unique(42); + MoveOnlyFunction function = [value = std::move(value)](int add){ + return *value + add; + }; + int actual = function(1); + if (actual != 43){ + return UnitTestResult(expected_int("call with a unique_ptr capture", 43, actual)); + } + + MoveOnlyFunction moved = std::move(function); + actual = moved(2); + if (actual != 44){ + return UnitTestResult(expected_int("call after a move", 44, actual)); + } + return true; + } +}; + + + +class Test_MoveOnlyFunction_StateNotForked : public UnitTest{ +public: + Test_MoveOnlyFunction_StateNotForked() + : UnitTest("Common::MoveOnlyFunction - Moving keeps one state") + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + MoveOnlyFunction counter = [count = 0]() mutable{ + return ++count; + }; + int actual = counter(); + if (actual != 1){ + return UnitTestResult(expected_int("first call", 1, actual)); + } + + // The moved-to wrapper continues the same count. + MoveOnlyFunction constructed = std::move(counter); + actual = constructed(); + if (actual != 2){ + return UnitTestResult(expected_int("call after a move construction", 2, actual)); + } + + MoveOnlyFunction assigned; + assigned = std::move(constructed); + actual = assigned(); + if (actual != 3){ + return UnitTestResult(expected_int("call after a move assignment", 3, actual)); + } + return true; + } +}; + + + +int return_seven(){ + return 7; +} + +class Test_MoveOnlyFunction_Empty : public UnitTest{ +public: + Test_MoveOnlyFunction_Empty() + : UnitTest("Common::MoveOnlyFunction - Empty is false") + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + MoveOnlyFunction defaulted; + if (defaulted){ + return UnitTestResult("default constructed: expected empty, got non-empty"); + } + MoveOnlyFunction from_nullptr = nullptr; + if (from_nullptr){ + return UnitTestResult("constructed from nullptr: expected empty, got non-empty"); + } + int (*null_pointer)() = nullptr; + MoveOnlyFunction from_null_pointer = null_pointer; + if (from_null_pointer){ + return UnitTestResult("constructed from a null function pointer: expected empty, got non-empty"); + } + + MoveOnlyFunction from_pointer = &return_seven; + if (!from_pointer){ + return UnitTestResult("constructed from a function pointer: expected non-empty, got empty"); + } + int actual = from_pointer(); + if (actual != 7){ + return UnitTestResult(expected_int("call through a function pointer", 7, actual)); + } + return true; + } +}; + + + +class Test_MoveOnlyFunction_Reassignment : public UnitTest{ +public: + Test_MoveOnlyFunction_Reassignment() + : UnitTest("Common::MoveOnlyFunction - Reassignment") + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + // The use count shows whether the wrapper still holds the first + // callable. + auto token = std::make_shared(1); + MoveOnlyFunction function = [token]{ + return *token; + }; + int actual = function(); + if (actual != 1){ + return UnitTestResult(expected_int("first callable", 1, actual)); + } + + function = []{ + return 2; + }; + actual = function(); + if (actual != 2){ + return UnitTestResult(expected_int("call after reassignment", 2, actual)); + } + actual = (int)token.use_count(); + if (actual != 1){ + return UnitTestResult(expected_int("token owners after reassignment", 1, actual)); + } + + function = nullptr; + if (function){ + return UnitTestResult("assigned nullptr: expected empty, got non-empty"); + } + if (function != nullptr){ + return UnitTestResult("assigned nullptr: expected == nullptr, got != nullptr"); + } + return true; + } +}; + + + +} // anonymous namespace + + + +void add_tests_MoveOnlyFunction(UnitTestDatabase& database){ + database.add(); + database.add(); + database.add(); + database.add(); +} + + + +} diff --git a/Common/Cpp/MoveOnlyFunction_Tests.h b/Common/Cpp/MoveOnlyFunction_Tests.h new file mode 100644 index 0000000000..c43f518bdc --- /dev/null +++ b/Common/Cpp/MoveOnlyFunction_Tests.h @@ -0,0 +1,21 @@ +/* Move-Only Function Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_MoveOnlyFunction_Tests_H +#define PokemonAutomation_MoveOnlyFunction_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ + + + +void add_tests_MoveOnlyFunction(UnitTestDatabase& database); + + + +} +#endif diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 61b81d1059..a0ba480194 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -5,6 +5,7 @@ */ #include "Common/Cpp/ListenerSet.h" +#include "Common/Cpp/MoveOnlyFunction_Tests.h" #include "Common/Cpp/ScopeExit.h" #include "Common/Cpp/PrettyPrint.h" #include "Common/Cpp/TestRunners/TestImageDistortionManager.h" @@ -52,6 +53,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ add_tests_QtEventThreadPool(ret, GlobalThreadPools::computation_normal()); add_tests_BlackBorderDetector(ret); add_tests_ListenerSet(ret); + add_tests_MoveOnlyFunction(ret); add_tests_AudioInfo(ret); add_tests_ChannelMixerMatrix(ret); add_tests_FFTStreamer(ret); diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 71c573cd13..f63860e5b5 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -118,6 +118,9 @@ file(GLOB CORE_LIBRARY_SOURCES ../Common/Cpp/Logging/MultiOutputLogger.h ../Common/Cpp/Logging/TaggedLogger.cpp ../Common/Cpp/Logging/TaggedLogger.h + ../Common/Cpp/MoveOnlyFunction.h + ../Common/Cpp/MoveOnlyFunction_Tests.cpp + ../Common/Cpp/MoveOnlyFunction_Tests.h ../Common/Cpp/Options/BatchOption.cpp ../Common/Cpp/Options/BatchOption.h ../Common/Cpp/Options/BooleanCheckBoxOption.cpp