Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 118 additions & 0 deletions Common/Cpp/MoveOnlyFunction.h
Original file line number Diff line number Diff line change
@@ -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 <version>
#include <functional>

#ifndef __cpp_lib_move_only_function
#include <cstddef>
#include <memory>
#include <type_traits>
#include <utility>
#endif

namespace PokemonAutomation{



#ifdef __cpp_lib_move_only_function

template <typename Signature>
using MoveOnlyFunction = std::move_only_function<Signature>;

#else

template <typename Signature>
class MoveOnlyFunction;

template <typename R, typename... Args>
class MoveOnlyFunction<R(Args...)>{
public:
MoveOnlyFunction() noexcept = default;
MoveOnlyFunction(std::nullptr_t) noexcept {}

template <typename Function>
requires (
!std::is_same_v<std::remove_cvref_t<Function>, MoveOnlyFunction> &&
std::is_invocable_r_v<R, std::decay_t<Function>&, Args...>
)
MoveOnlyFunction(Function&& function){
using Stored = std::decay_t<Function>;
// Like std::move_only_function, a null function pointer makes an
// empty wrapper.
if constexpr (std::is_pointer_v<Stored> || std::is_member_pointer_v<Stored>){
if (function == nullptr){
return;
}
}
m_callable = std::make_unique<Holder<Stored>>(std::forward<Function>(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>(args)...);
}


private:
class Callable{
public:
virtual ~Callable() = default;
virtual R call(Args&&... args) = 0;
};

template <typename Stored>
class Holder final : public Callable{
public:
template <typename Source>
explicit Holder(Source&& source)
: m_stored(std::forward<Source>(source))
{}
virtual R call(Args&&... args) override{
return std::invoke_r<R>(m_stored, std::forward<Args>(args)...);
}

private:
Stored m_stored;
};

std::unique_ptr<Callable> m_callable;
};

#endif



}
#endif
190 changes: 190 additions & 0 deletions Common/Cpp/MoveOnlyFunction_Tests.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
/* Move-Only Function Tests
*
* From: https://github.com/PokemonAutomation/
*
*/

#include <format>
#include <memory>
#include <string>
#include <type_traits>
#include <utility>
#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<MoveOnlyFunction<void()>>);
static_assert(!std::is_copy_assignable_v<MoveOnlyFunction<void()>>);
static_assert(std::is_nothrow_move_constructible_v<MoveOnlyFunction<void()>>);



std::string expected_int(const char* what, int expected, int actual){
return std::format("{}: expected {}, got {}", what, expected, 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<int>(42);
MoveOnlyFunction<int(int)> 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<int(int)> 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<int()> 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<int()> constructed = std::move(counter);
actual = constructed();
if (actual != 2){
return UnitTestResult(expected_int("call after a move construction", 2, actual));
}

MoveOnlyFunction<int()> 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<int()> defaulted;
if (defaulted){
return UnitTestResult("default constructed: expected empty, got non-empty");
}
MoveOnlyFunction<int()> from_nullptr = nullptr;
if (from_nullptr){
return UnitTestResult("constructed from nullptr: expected empty, got non-empty");
}
int (*null_pointer)() = nullptr;
MoveOnlyFunction<int()> from_null_pointer = null_pointer;
if (from_null_pointer){
return UnitTestResult("constructed from a null function pointer: expected empty, got non-empty");
}

MoveOnlyFunction<int()> 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<int>(1);
MoveOnlyFunction<int()> 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<Test_MoveOnlyFunction_MoveOnlyCapture>();
database.add<Test_MoveOnlyFunction_StateNotForked>();
database.add<Test_MoveOnlyFunction_Empty>();
database.add<Test_MoveOnlyFunction_Reassignment>();
}



}
21 changes: 21 additions & 0 deletions Common/Cpp/MoveOnlyFunction_Tests.h
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -51,6 +52,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);
Expand Down
3 changes: 3 additions & 0 deletions SerialPrograms/cmake/SourceFiles.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading