Compare commits
10
Commits
8e1a9882db
...
380643503b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
380643503b | ||
|
|
802efc7fad | ||
|
|
e32e8b0cac | ||
|
|
ae8196b4a1 | ||
|
|
e23ab691de | ||
|
|
f92d3a1940 | ||
|
|
2d1f038695 | ||
|
|
9733744a81 | ||
|
|
7eac0b6490 | ||
|
|
08fdf36dcb |
@@ -14,13 +14,14 @@
|
||||
# CollectAndAddSourceFiles(
|
||||
# common
|
||||
# ${CMAKE_CURRENT_SOURCE_DIR}
|
||||
# NO_INCLUDE_DIRECTORIES # if present, subdirectories will not be added to target include directories
|
||||
# EXCLUDE
|
||||
# ${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders
|
||||
# ${CMAKE_CURRENT_SOURCE_DIR}/Platform
|
||||
# HEADER_VISIBILITY PRIVATE) # default is PUBLIC, this controls whether other targets that have this target as dependency will be able to access its headers
|
||||
#
|
||||
function(CollectAndAddSourceFiles target_name current_dir)
|
||||
cmake_parse_arguments(PARSE_ARGV 2 arg "" "BASE_DIR;HEADER_VISIBILITY" "EXCLUDE")
|
||||
cmake_parse_arguments(PARSE_ARGV 2 arg "NO_INCLUDE_SUBDIRECTORIES" "BASE_DIR;HEADER_VISIBILITY" "EXCLUDE")
|
||||
if(NOT arg_BASE_DIR)
|
||||
set(arg_BASE_DIR "${current_dir}")
|
||||
endif()
|
||||
@@ -44,8 +45,13 @@ function(CollectAndAddSourceFiles target_name current_dir)
|
||||
${current_dir}/*.hh
|
||||
${current_dir}/*.hpp)
|
||||
|
||||
set(fileset_include_directory "${current_dir}")
|
||||
if(arg_NO_INCLUDE_SUBDIRECTORIES)
|
||||
set(fileset_include_directory "${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
endif()
|
||||
|
||||
target_sources(${target_name} PRIVATE ${private_source_files})
|
||||
target_sources(${target_name} ${arg_HEADER_VISIBILITY} FILE_SET "headers_${fileset_name}" TYPE HEADERS BASE_DIRS ${current_dir} FILES ${public_header_files})
|
||||
target_sources(${target_name} ${arg_HEADER_VISIBILITY} FILE_SET "headers_${fileset_name}" TYPE HEADERS BASE_DIRS ${fileset_include_directory} FILES ${public_header_files})
|
||||
|
||||
file(GLOB SUB_DIRECTORIES ${current_dir}/*)
|
||||
foreach(SUB_DIRECTORY ${SUB_DIRECTORIES})
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
DROP TABLE IF EXISTS `gossip_menu_option_addon`;
|
||||
CREATE TABLE `gossip_menu_option_addon` (
|
||||
MenuID INT UNSIGNED NOT NULL,
|
||||
OptionID INT UNSIGNED NOT NULL,
|
||||
DefaultAction TINYINT NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (MenuID, OptionID)
|
||||
) ENGINE = INNODB;
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -16,12 +16,19 @@ CollectAndAddSourceFiles(
|
||||
common
|
||||
${CMAKE_CURRENT_SOURCE_DIR}
|
||||
EXCLUDE
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/Threading/Coro
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/Debugging/Windows
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/Platform
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/mmaps_common
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/network)
|
||||
|
||||
CollectAndAddSourceFiles(
|
||||
common
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/Threading/Coro
|
||||
BASE_DIR ${CMAKE_CURRENT_SOURCE_DIR}
|
||||
NO_INCLUDE_SUBDIRECTORIES)
|
||||
|
||||
if(WIN32)
|
||||
CollectAndAddSourceFiles(
|
||||
common
|
||||
|
||||
@@ -139,9 +139,8 @@ void Metric::SendBatch()
|
||||
using namespace std::chrono;
|
||||
|
||||
std::stringstream batchedData;
|
||||
MetricData* data;
|
||||
bool firstLoop = true;
|
||||
while (_queuedData.Dequeue(data))
|
||||
while (MetricData* data = _queuedData.Dequeue())
|
||||
{
|
||||
if (!firstLoop)
|
||||
batchedData << "\n";
|
||||
@@ -237,9 +236,8 @@ void Metric::ScheduleSend()
|
||||
else
|
||||
{
|
||||
GetDataStream().close();
|
||||
MetricData* data;
|
||||
// Clear the queue
|
||||
while (_queuedData.Dequeue(data))
|
||||
while (MetricData* data = _queuedData.Dequeue())
|
||||
delete data;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef TRINITYCORE_CORO_ALL_OF_H
|
||||
#define TRINITYCORE_CORO_ALL_OF_H
|
||||
|
||||
#include "./Awaitable.h"
|
||||
#include "./CoroutineExecutionContext.h"
|
||||
#include "./CoroutineFwd.h"
|
||||
#include "Memory.h"
|
||||
#include "Types.h"
|
||||
#include "advstd.h"
|
||||
#include <tuple>
|
||||
|
||||
namespace Trinity::Coro
|
||||
{
|
||||
namespace Impl
|
||||
{
|
||||
template <typename... Awaitables>
|
||||
class AllOfAwaitable
|
||||
{
|
||||
public:
|
||||
template <typename Awaitable>
|
||||
using return_type_element = std::conditional_t<std::is_lvalue_reference_v<Awaitable>,
|
||||
std::add_lvalue_reference_t<typename std::remove_reference_t<Awaitable>::return_type>,
|
||||
std::remove_reference_t<typename std::remove_reference_t<Awaitable>::return_type>>;
|
||||
|
||||
explicit AllOfAwaitable(Awaitables&&... awaitables)
|
||||
: _awaitables(AllOfAwaitable::AwaitableWrapper<Awaitables>(this, std::forward<Awaitables>(awaitables))...) { }
|
||||
|
||||
bool await_ready() const noexcept { return _context && !_context->Handle.done(); }
|
||||
|
||||
template <std::derived_from<CoroutineExecutionContext> promise_type>
|
||||
void await_suspend(std::coroutine_handle<promise_type> coroutine) noexcept
|
||||
{
|
||||
_context = &coroutine.promise();
|
||||
auto startCoro = [](CoroutineExecutionContext* context, auto&& awaitable)
|
||||
{
|
||||
auto& promise = awaitable.promise();
|
||||
promise.CurrentExecutor = context->CurrentExecutor;
|
||||
promise.QueueCompletion();
|
||||
};
|
||||
std::apply([&](auto&&... awaitables) { (startCoro(_context, awaitables), ...); }, _awaitables);
|
||||
}
|
||||
|
||||
auto await_resume()
|
||||
{
|
||||
using InputTuple = std::tuple<Awaitables...>;
|
||||
|
||||
// call .get_result() on void returning awaitables to rethrow their exceptions
|
||||
auto voidsSequence = Trinity::filter_index_sequence(std::index_sequence_for<Awaitables...>{},
|
||||
[]<std::size_t I>(std::index_sequence<I>) constexpr { return std::is_void_v<return_type_element<std::tuple_element_t<I, InputTuple>>>; });
|
||||
[&]<std::size_t... I>(std::index_sequence<I...>)
|
||||
{
|
||||
(std::get<I>(_awaitables).promise().get_result(), ...);
|
||||
}(voidsSequence);
|
||||
|
||||
auto valuesSequence = Trinity::filter_index_sequence(std::index_sequence_for<Awaitables...>{},
|
||||
[]<std::size_t I>(std::index_sequence<I>) constexpr { return !std::is_void_v<return_type_element<std::tuple_element_t<I, InputTuple>>>; });
|
||||
|
||||
// return values from all awaitables
|
||||
// tuple element types are transformed like this
|
||||
// * if input awaitable was lvalue ref then tuple element is also lvalue ref
|
||||
// * if input awaitable was a rvalue ref or a value then tuple element is a value
|
||||
// * awaitables returning void are skipped in result tuple
|
||||
return [&]<std::size_t... I>(std::index_sequence<I...>)
|
||||
{
|
||||
return std::tuple<return_type_element<std::tuple_element_t<I, InputTuple>>...>(
|
||||
advstd::forward_like<return_type_element<std::tuple_element_t<I, InputTuple>>>(std::get<I>(_awaitables).promise()).get_result()...
|
||||
);
|
||||
}(valuesSequence);
|
||||
}
|
||||
|
||||
private:
|
||||
// this class takes ownership of rvalue awaitables by passing them by value to wrapper coroutine
|
||||
template <typename WrappedAwaitable>
|
||||
static Awaitable<return_type_element<WrappedAwaitable>> AwaitableWrapper(AllOfAwaitable* allOf,
|
||||
std::conditional_t<std::is_lvalue_reference_v<WrappedAwaitable>, WrappedAwaitable, std::remove_reference_t<WrappedAwaitable>> awaitable)
|
||||
{
|
||||
auto completionGuard = Trinity::make_unique_ptr_with_deleter<&AllOfAwaitable::OnChildComplete>(allOf);
|
||||
co_return co_await awaitable;
|
||||
}
|
||||
|
||||
void OnChildComplete()
|
||||
{
|
||||
if (_pending.fetch_sub(1, std::memory_order::acq_rel) == 1)
|
||||
_context->QueueCompletion();
|
||||
}
|
||||
|
||||
std::tuple<Awaitable<return_type_element<Awaitables>>...> _awaitables;
|
||||
std::atomic<std::size_t> _pending = sizeof...(Awaitables);
|
||||
CoroutineExecutionContext* _context = nullptr;
|
||||
};
|
||||
}
|
||||
|
||||
template <typename... Awaitables>
|
||||
inline auto AllOf(Awaitables&&... awaitables) -> Impl::AllOfAwaitable<decltype(awaitables)...>
|
||||
{
|
||||
return Impl::AllOfAwaitable<decltype(awaitables)...>(std::forward<Awaitables>(awaitables)...);
|
||||
}
|
||||
}
|
||||
|
||||
#endif // TRINITYCORE_CORO_ALL_OF_H
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "./Allocator.h"
|
||||
#include "./AllocatorImpl.h"
|
||||
|
||||
namespace Trinity::Coro::Impl
|
||||
{
|
||||
namespace CurrentAllocator
|
||||
{
|
||||
namespace
|
||||
{
|
||||
thread_local Allocator* Instance;
|
||||
}
|
||||
|
||||
Allocator* Get()
|
||||
{
|
||||
return Instance;
|
||||
}
|
||||
|
||||
void Set(Allocator* allocator)
|
||||
{
|
||||
Instance = allocator;
|
||||
}
|
||||
|
||||
void* Allocate(std::size_t size)
|
||||
{
|
||||
return Instance->allocate(size);
|
||||
}
|
||||
|
||||
void Free(void* data, std::size_t size)
|
||||
{
|
||||
Instance->deallocate(data, size);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef TRINITYCORE_CORO_ALLOCATOR_H
|
||||
#define TRINITYCORE_CORO_ALLOCATOR_H
|
||||
|
||||
#include "./CoroutineFwd.h"
|
||||
#include "Define.h"
|
||||
|
||||
namespace Trinity::Coro::Impl
|
||||
{
|
||||
struct Allocator;
|
||||
|
||||
namespace CurrentAllocator
|
||||
{
|
||||
TC_COMMON_API Allocator* Get();
|
||||
TC_COMMON_API void Set(Allocator* allocator);
|
||||
|
||||
TC_COMMON_API void* Allocate(std::size_t size);
|
||||
TC_COMMON_API void Free(void* data, std::size_t size);
|
||||
}
|
||||
}
|
||||
|
||||
#endif // TRINITYCORE_CORO_ALLOCATOR_H
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef TRINITYCORE_CORO_ALLOCATOR_IMPL_H
|
||||
#define TRINITYCORE_CORO_ALLOCATOR_IMPL_H
|
||||
|
||||
#include "./CoroutineFwd.h"
|
||||
#include <memory_resource>
|
||||
|
||||
namespace Trinity::Coro::Impl
|
||||
{
|
||||
struct Allocator final : std::pmr::unsynchronized_pool_resource
|
||||
{
|
||||
using unsynchronized_pool_resource::unsynchronized_pool_resource;
|
||||
};
|
||||
}
|
||||
|
||||
#endif // TRINITYCORE_CORO_ALLOCATOR_IMPL_H
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef TRINITYCORE_CORO_ASIO_EXECUTOR_ADAPTER_H
|
||||
#define TRINITYCORE_CORO_ASIO_EXECUTOR_ADAPTER_H
|
||||
|
||||
#include "./Executor.h"
|
||||
#include "AsioHacksFwd.h"
|
||||
|
||||
namespace Trinity::Coro
|
||||
{
|
||||
class TC_COMMON_API AsioExecutorAdapter final : public Executor
|
||||
{
|
||||
public:
|
||||
explicit AsioExecutorAdapter(Asio::IoContext& ioContext) : _ioContext(ioContext) { }
|
||||
|
||||
void QueueCompletion(CoroutineExecutionContext* context) override;
|
||||
|
||||
private:
|
||||
Asio::IoContext& _ioContext;
|
||||
};
|
||||
}
|
||||
|
||||
#endif // TRINITYCORE_CORO_ASIO_EXECUTOR_ADAPTER_H
|
||||
@@ -0,0 +1,223 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef TRINITYCORE_CORO_AWAITABLE_H
|
||||
#define TRINITYCORE_CORO_AWAITABLE_H
|
||||
|
||||
#include "./Allocator.h"
|
||||
#include "./CoroutineExecutionContext.h"
|
||||
#include "./CoroutineFwd.h"
|
||||
#include "./ResultValue.h"
|
||||
#include <concepts>
|
||||
#include <coroutine>
|
||||
#include <exception>
|
||||
#include <utility>
|
||||
|
||||
namespace Trinity::Coro
|
||||
{
|
||||
namespace Impl
|
||||
{
|
||||
class PromiseBase : public CoroutineExecutionContext
|
||||
{
|
||||
public:
|
||||
explicit PromiseBase(std::coroutine_handle<> handle) : CoroutineExecutionContext(handle) { }
|
||||
|
||||
struct FinalAwaitable
|
||||
{
|
||||
bool await_ready() const noexcept { return false; }
|
||||
|
||||
template <std::derived_from<PromiseBase> promise_type>
|
||||
std::coroutine_handle<> await_suspend(std::coroutine_handle<promise_type> coroutine) noexcept
|
||||
{
|
||||
promise_type& promise = coroutine.promise();
|
||||
return promise.Next ? promise.Next : std::noop_coroutine();
|
||||
}
|
||||
|
||||
void await_resume() noexcept { }
|
||||
};
|
||||
|
||||
template <std::derived_from<CoroutineExecutionContext> promise_type>
|
||||
void set_next(std::coroutine_handle<promise_type> next)
|
||||
{
|
||||
Next = next;
|
||||
CurrentExecutor = next.promise().CurrentExecutor;
|
||||
}
|
||||
|
||||
protected:
|
||||
std::coroutine_handle<> Next;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class Promise : public PromiseBase
|
||||
{
|
||||
public:
|
||||
Promise() : PromiseBase(std::coroutine_handle<Promise>::from_promise(*this)) { }
|
||||
|
||||
Awaitable<T> get_return_object() noexcept;
|
||||
|
||||
std::suspend_always initial_suspend() noexcept { return { }; }
|
||||
|
||||
FinalAwaitable final_suspend() noexcept { return { }; }
|
||||
|
||||
template <std::convertible_to<typename ResultValue<T>::value_holder> V>
|
||||
void return_value(V&& value) { _resultValue.set_value(std::forward<V>(value)); }
|
||||
|
||||
void unhandled_exception() { _resultValue.set_exception(std::current_exception()); }
|
||||
|
||||
T& get_result() & { return _resultValue.get(); }
|
||||
|
||||
T&& get_result() && { return std::move(_resultValue).get(); }
|
||||
|
||||
bool has_result() const { return _resultValue.has_value_or_exception(); }
|
||||
|
||||
void* operator new(std::size_t size)
|
||||
{
|
||||
return CurrentAllocator::Allocate(size);
|
||||
}
|
||||
|
||||
void operator delete(void* ptr, std::size_t size) noexcept
|
||||
{
|
||||
CurrentAllocator::Free(ptr, size);
|
||||
}
|
||||
|
||||
private:
|
||||
ResultValue<T> _resultValue;
|
||||
};
|
||||
|
||||
template <>
|
||||
class Promise<void> : public PromiseBase
|
||||
{
|
||||
public:
|
||||
Promise() : PromiseBase(std::coroutine_handle<Promise>::from_promise(*this)) { }
|
||||
|
||||
Awaitable<void> get_return_object() noexcept;
|
||||
|
||||
std::suspend_always initial_suspend() noexcept { return { }; }
|
||||
|
||||
FinalAwaitable final_suspend() noexcept { return { }; }
|
||||
|
||||
void return_void() { _resultValue.set_value(); }
|
||||
|
||||
void unhandled_exception() { _resultValue.set_exception(std::current_exception()); }
|
||||
|
||||
void get_result() { return _resultValue.get(); }
|
||||
|
||||
bool has_result() const { return _resultValue.has_value_or_exception(); }
|
||||
|
||||
void* operator new(std::size_t size)
|
||||
{
|
||||
return CurrentAllocator::Allocate(size);
|
||||
}
|
||||
|
||||
void operator delete(void* ptr, std::size_t size) noexcept
|
||||
{
|
||||
CurrentAllocator::Free(ptr, size);
|
||||
}
|
||||
|
||||
private:
|
||||
ResultValue<void> _resultValue;
|
||||
};
|
||||
|
||||
template <std::derived_from<PromiseBase> Promise>
|
||||
class AwaiterBase
|
||||
{
|
||||
public:
|
||||
explicit AwaiterBase(std::coroutine_handle<Promise> coroutine) noexcept : _coroutine(coroutine) { }
|
||||
|
||||
bool await_ready() const noexcept { return !_coroutine || _coroutine.done(); }
|
||||
|
||||
template <std::derived_from<CoroutineExecutionContext> promise_type>
|
||||
std::coroutine_handle<> await_suspend(std::coroutine_handle<promise_type> next) noexcept
|
||||
{
|
||||
Promise& promise = _coroutine.promise();
|
||||
promise.set_next(next);
|
||||
return _coroutine;
|
||||
}
|
||||
|
||||
protected:
|
||||
std::coroutine_handle<Promise> _coroutine;
|
||||
};
|
||||
|
||||
template <std::derived_from<PromiseBase> Promise, bool RValue>
|
||||
class Awaiter : public AwaiterBase<Promise>
|
||||
{
|
||||
public:
|
||||
using AwaiterBase<Promise>::AwaiterBase;
|
||||
|
||||
decltype(auto) await_resume()
|
||||
{
|
||||
if constexpr (RValue)
|
||||
return std::move(this->_coroutine.promise()).get_result();
|
||||
else
|
||||
return this->_coroutine.promise().get_result();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
class Awaitable
|
||||
{
|
||||
public:
|
||||
using promise_type = Impl::Promise<T>;
|
||||
using return_type = T;
|
||||
|
||||
Awaitable() noexcept = default;
|
||||
|
||||
explicit Awaitable(std::coroutine_handle<promise_type> coroutine) : _coroutine(coroutine) { }
|
||||
|
||||
Awaitable(Awaitable const&) = delete;
|
||||
Awaitable(Awaitable&& other) noexcept : _coroutine(std::exchange(other._coroutine, nullptr)) { }
|
||||
|
||||
Awaitable& operator=(Awaitable const&) = delete;
|
||||
Awaitable& operator=(Awaitable&& right) noexcept
|
||||
{
|
||||
if (this != &right)
|
||||
{
|
||||
if (_coroutine)
|
||||
_coroutine.destroy();
|
||||
|
||||
_coroutine = std::exchange(right._coroutine, nullptr);
|
||||
}
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
~Awaitable()
|
||||
{
|
||||
if (_coroutine)
|
||||
_coroutine.destroy();
|
||||
}
|
||||
|
||||
Impl::Awaiter<promise_type, false> operator co_await() const & noexcept { return Impl::Awaiter<promise_type, false>(_coroutine); }
|
||||
Impl::Awaiter<promise_type, true> operator co_await() const && noexcept { return Impl::Awaiter<promise_type, true>(_coroutine); }
|
||||
|
||||
promise_type& promise() const { return _coroutine.promise(); }
|
||||
|
||||
private:
|
||||
std::coroutine_handle<promise_type> _coroutine;
|
||||
};
|
||||
|
||||
namespace Impl
|
||||
{
|
||||
template <typename T>
|
||||
inline Awaitable<T> Promise<T>::get_return_object() noexcept { return Awaitable<T>(std::coroutine_handle<Promise>::from_promise(*this)); }
|
||||
|
||||
inline Awaitable<void> Promise<void>::get_return_object() noexcept { return Awaitable<void>(std::coroutine_handle<Promise>::from_promise(*this)); }
|
||||
}
|
||||
}
|
||||
|
||||
#endif // TRINITYCORE_CORO_AWAITABLE_H
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "./AwaitableValue.h"
|
||||
#include "./CoroutineExecutionContext.h"
|
||||
|
||||
namespace Trinity::Coro::Impl
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr AwaitableValueAwaiterData READY_MARKER;
|
||||
}
|
||||
|
||||
bool AwaitableValueAwaiterBase::await_ready() const noexcept
|
||||
{
|
||||
return Value._waitQueue.load(std::memory_order::acquire) == &READY_MARKER;
|
||||
}
|
||||
|
||||
bool AwaitableValueAwaiterBase::handle_suspend(CoroutineExecutionContext* coroutine) noexcept
|
||||
{
|
||||
Coroutine = coroutine;
|
||||
|
||||
AwaitableValueAwaiterData const* old = Value._waitQueue.load(std::memory_order::acquire);
|
||||
do
|
||||
{
|
||||
if (old == &READY_MARKER)
|
||||
return false; // value is now ready, don't suspend
|
||||
|
||||
Next = old;
|
||||
} while (!Value._waitQueue.compare_exchange_weak(old, this, std::memory_order::release, std::memory_order::acquire));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void AwaitableValueBase::notify_waiters()
|
||||
{
|
||||
AwaitableValueAwaiterData const* waiter = _waitQueue.exchange(&READY_MARKER, std::memory_order::acq_rel);
|
||||
if (waiter != &READY_MARKER)
|
||||
{
|
||||
while (waiter)
|
||||
{
|
||||
AwaitableValueAwaiterData const* next = waiter->Next;
|
||||
waiter->Coroutine->QueueCompletion();
|
||||
waiter = next;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool AwaitableValueBase::reset_waiters()
|
||||
{
|
||||
AwaitableValueAwaiterData const* old = &READY_MARKER;
|
||||
return _waitQueue.compare_exchange_strong(old, nullptr, std::memory_order::acquire);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef TRINITYCORE_CORO_AWAITABLE_VALUE_H
|
||||
#define TRINITYCORE_CORO_AWAITABLE_VALUE_H
|
||||
|
||||
#include "./CoroutineFwd.h"
|
||||
#include "./ResultValue.h"
|
||||
#include "Define.h"
|
||||
#include <atomic>
|
||||
#include <concepts>
|
||||
#include <coroutine>
|
||||
|
||||
namespace Trinity::Coro
|
||||
{
|
||||
namespace Impl
|
||||
{
|
||||
class AwaitableValueBase;
|
||||
|
||||
struct AwaitableValueAwaiterData
|
||||
{
|
||||
AwaitableValueAwaiterData const* Next = nullptr;
|
||||
CoroutineExecutionContext* Coroutine = nullptr;
|
||||
};
|
||||
|
||||
struct TC_COMMON_API AwaitableValueAwaiterBase : AwaitableValueAwaiterData
|
||||
{
|
||||
explicit AwaitableValueAwaiterBase(AwaitableValueBase& value) noexcept : Value(value) { }
|
||||
|
||||
bool await_ready() const noexcept;
|
||||
|
||||
template <std::derived_from<CoroutineExecutionContext> promise_type>
|
||||
bool await_suspend(std::coroutine_handle<promise_type> coroutine) noexcept
|
||||
{
|
||||
return this->handle_suspend(&coroutine.promise());
|
||||
}
|
||||
|
||||
private:
|
||||
bool handle_suspend(CoroutineExecutionContext* coroutine) noexcept;
|
||||
|
||||
protected:
|
||||
AwaitableValueBase& Value;
|
||||
};
|
||||
|
||||
class TC_COMMON_API AwaitableValueBase
|
||||
{
|
||||
protected:
|
||||
void notify_waiters();
|
||||
|
||||
bool reset_waiters();
|
||||
|
||||
friend AwaitableValueAwaiterBase;
|
||||
std::atomic<AwaitableValueAwaiterData const*> _waitQueue;
|
||||
};
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
class AwaitableValue : public Impl::AwaitableValueBase
|
||||
{
|
||||
public:
|
||||
template <bool RValue>
|
||||
struct Awaiter : Impl::AwaitableValueAwaiterBase
|
||||
{
|
||||
explicit Awaiter(AwaitableValue& value) noexcept : AwaitableValueAwaiterBase(value) { }
|
||||
|
||||
decltype(auto) await_resume()
|
||||
{
|
||||
if constexpr (RValue)
|
||||
return std::move(static_cast<AwaitableValue&>(Value)._resultValue).get();
|
||||
else
|
||||
return static_cast<AwaitableValue&>(Value)._resultValue.get();
|
||||
}
|
||||
};
|
||||
|
||||
explicit AwaitableValue() noexcept = default;
|
||||
AwaitableValue(AwaitableValue const&) = delete;
|
||||
AwaitableValue(AwaitableValue&&) = delete;
|
||||
AwaitableValue& operator=(AwaitableValue const&) = delete;
|
||||
AwaitableValue& operator=(AwaitableValue&&) = delete;
|
||||
~AwaitableValue() = default;
|
||||
|
||||
template <std::convertible_to<typename ResultValue<T>::value_holder> V>
|
||||
void set_value(V&& value) requires (!std::same_as<T, void>)
|
||||
{
|
||||
_resultValue.set_value(std::forward<V>(value));
|
||||
|
||||
this->notify_waiters();
|
||||
}
|
||||
|
||||
void set_value() requires (std::same_as<T, void>)
|
||||
{
|
||||
_resultValue.set_value();
|
||||
|
||||
this->notify_waiters();
|
||||
}
|
||||
|
||||
void reset() noexcept
|
||||
{
|
||||
if (this->reset_waiters())
|
||||
_resultValue.reset();
|
||||
}
|
||||
|
||||
Awaiter<false> operator co_await() & noexcept { return Awaiter<false>(*this); }
|
||||
Awaiter<true> operator co_await() && noexcept { return Awaiter<true>(*this); }
|
||||
|
||||
private:
|
||||
template <bool>
|
||||
friend struct Awaiter;
|
||||
ResultValue<T> _resultValue;
|
||||
};
|
||||
}
|
||||
|
||||
#endif // TRINITYCORE_CORO_AWAITABLE_VALUE_H
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef TRINITYCORE_CORO_EXECUTION_CONTEXT_H
|
||||
#define TRINITYCORE_CORO_EXECUTION_CONTEXT_H
|
||||
|
||||
#include "./Allocator.h"
|
||||
#include "./CoroutineFwd.h"
|
||||
#include "UniqueTrackablePtr.h"
|
||||
#include <atomic>
|
||||
#include <coroutine>
|
||||
|
||||
namespace Trinity::Coro
|
||||
{
|
||||
struct CoroutineExecutionContext
|
||||
{
|
||||
explicit CoroutineExecutionContext(std::coroutine_handle<> handle) noexcept : Handle(handle) { }
|
||||
|
||||
TC_COMMON_API void Resume() noexcept;
|
||||
TC_COMMON_API void QueueCompletion() noexcept;
|
||||
|
||||
std::atomic<CoroutineExecutionContext*> QueueLink;
|
||||
std::coroutine_handle<> Handle;
|
||||
unique_weak_ptr<Executor> CurrentExecutor;
|
||||
Impl::Allocator* CurrentAllocator = Impl::CurrentAllocator::Get();
|
||||
};
|
||||
}
|
||||
|
||||
#endif // TRINITYCORE_CORO_EXECUTION_CONTEXT_H
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef TRINITYCORE_COROUTINE_FWD_H
|
||||
#define TRINITYCORE_COROUTINE_FWD_H
|
||||
|
||||
namespace Trinity::Coro
|
||||
{
|
||||
template <typename T>
|
||||
class Awaitable;
|
||||
|
||||
struct CoroutineExecutionContext;
|
||||
|
||||
class Executor;
|
||||
class AsioExecutorAdapter;
|
||||
class MultiThreadedExecutor;
|
||||
class SingleThreadedExecutor;
|
||||
|
||||
template <typename T>
|
||||
class ResultValue;
|
||||
|
||||
template <typename T>
|
||||
class AwaitableValue;
|
||||
}
|
||||
|
||||
#endif // TRINITYCORE_COROUTINE_FWD_H
|
||||
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef TRINITYCORE_CURRENT_COROUTINE_H
|
||||
#define TRINITYCORE_CURRENT_COROUTINE_H
|
||||
|
||||
#include "./CoroutineExecutionContext.h"
|
||||
#include "./CoroutineFwd.h"
|
||||
|
||||
namespace Trinity::Coro
|
||||
{
|
||||
namespace Impl
|
||||
{
|
||||
struct CurrentCoroutineBaseAwaiter
|
||||
{
|
||||
bool await_ready() const noexcept { return false; }
|
||||
|
||||
template <std::derived_from<CoroutineExecutionContext> promise_type>
|
||||
bool await_suspend(std::coroutine_handle<promise_type> coroutine) noexcept
|
||||
{
|
||||
Context = &coroutine.promise();
|
||||
return false;
|
||||
}
|
||||
|
||||
CoroutineExecutionContext* Context = nullptr;
|
||||
};
|
||||
|
||||
struct CurrentExecutorAwaiter : CurrentCoroutineBaseAwaiter
|
||||
{
|
||||
unique_weak_ptr<Executor> await_resume() const noexcept { return Context->CurrentExecutor; }
|
||||
};
|
||||
}
|
||||
|
||||
struct CurrentExecutorAwaitable
|
||||
{
|
||||
Impl::CurrentExecutorAwaiter operator co_await() const noexcept { return { }; }
|
||||
} inline constexpr CurrentExecutor;
|
||||
}
|
||||
|
||||
#endif // TRINITYCORE_CURRENT_COROUTINE_H
|
||||
@@ -0,0 +1,153 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "./Executor.h"
|
||||
#include "./Allocator.h"
|
||||
#include "./AsioExecutorAdapter.h"
|
||||
#include "./MultiThreadedExecutor.h"
|
||||
#include "./SingleThreadedExecutor.h"
|
||||
#include "IoContext.h"
|
||||
|
||||
namespace Trinity::Coro
|
||||
{
|
||||
void CoroutineExecutionContext::Resume() noexcept
|
||||
{
|
||||
Impl::CurrentAllocator::Set(CurrentAllocator);
|
||||
Handle.resume();
|
||||
}
|
||||
|
||||
void CoroutineExecutionContext::QueueCompletion() noexcept
|
||||
{
|
||||
if (unique_strong_ref_ptr<Executor> executor = CurrentExecutor.lock())
|
||||
executor->QueueCompletion(this);
|
||||
else
|
||||
Handle.destroy();
|
||||
}
|
||||
|
||||
void Executor::QueueCompletion(CoroutineExecutionContext* context)
|
||||
{
|
||||
context->CurrentExecutor = weak_from_this();
|
||||
}
|
||||
|
||||
void AsioExecutorAdapter::QueueCompletion(CoroutineExecutionContext* context)
|
||||
{
|
||||
Executor::QueueCompletion(context);
|
||||
|
||||
Trinity::Asio::post(_ioContext, [context]
|
||||
{
|
||||
context->Resume();
|
||||
});
|
||||
}
|
||||
|
||||
void MultiThreadedExecutor::QueueCompletion(CoroutineExecutionContext* context)
|
||||
{
|
||||
Executor::QueueCompletion(context);
|
||||
|
||||
std::scoped_lock lock(_mutex);
|
||||
|
||||
_resumeQueue.push_back(*context);
|
||||
|
||||
_condition.notify_one();
|
||||
}
|
||||
|
||||
void MultiThreadedExecutor::ResumeReadyCoroutines()
|
||||
{
|
||||
do
|
||||
{
|
||||
CoroutineExecutionContext* coroutine;
|
||||
{
|
||||
std::scoped_lock lock(_mutex);
|
||||
if (_resumeQueue.empty())
|
||||
break;
|
||||
|
||||
coroutine = &_resumeQueue.front();
|
||||
_resumeQueue.pop_front();
|
||||
}
|
||||
|
||||
coroutine->Resume();
|
||||
|
||||
} while (true);
|
||||
}
|
||||
|
||||
void MultiThreadedExecutor::WaitForReadyCoroutinesAndResume()
|
||||
{
|
||||
do
|
||||
{
|
||||
CoroutineExecutionContext* coroutine;
|
||||
{
|
||||
std::unique_lock lock(_mutex);
|
||||
|
||||
_condition.wait(lock, [&] { return !_resumeQueue.empty() || _stopped.test(std::memory_order::relaxed); });
|
||||
if (_resumeQueue.empty())
|
||||
break;
|
||||
|
||||
coroutine = &_resumeQueue.front();
|
||||
_resumeQueue.pop_front();
|
||||
}
|
||||
|
||||
coroutine->Resume();
|
||||
|
||||
} while (true);
|
||||
}
|
||||
|
||||
bool MultiThreadedExecutor::WaitForReadyCoroutinesAndResume(Milliseconds timeout)
|
||||
{
|
||||
do
|
||||
{
|
||||
CoroutineExecutionContext* coroutine;
|
||||
{
|
||||
std::unique_lock lock(_mutex);
|
||||
|
||||
if (!_condition.wait_for(lock, timeout, [&] { return !_resumeQueue.empty() || _stopped.test(std::memory_order::relaxed); }))
|
||||
return false;
|
||||
|
||||
if (_resumeQueue.empty())
|
||||
break;
|
||||
|
||||
coroutine = &_resumeQueue.front();
|
||||
_resumeQueue.pop_front();
|
||||
}
|
||||
|
||||
coroutine->Resume();
|
||||
|
||||
} while (true);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void MultiThreadedExecutor::StopWaiting()
|
||||
{
|
||||
std::scoped_lock lock(_mutex);
|
||||
|
||||
_stopped.test_and_set(std::memory_order::relaxed);
|
||||
|
||||
_condition.notify_all();
|
||||
}
|
||||
|
||||
void SingleThreadedExecutor::QueueCompletion(CoroutineExecutionContext* context)
|
||||
{
|
||||
Executor::QueueCompletion(context);
|
||||
|
||||
_resumeQueue.Enqueue(context);
|
||||
}
|
||||
|
||||
void SingleThreadedExecutor::ResumeReadyCoroutines()
|
||||
{
|
||||
while (CoroutineExecutionContext* context = _resumeQueue.Dequeue())
|
||||
context->Resume();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef TRINITYCORE_CORO_EXECUTOR_H
|
||||
#define TRINITYCORE_CORO_EXECUTOR_H
|
||||
|
||||
#include "./CoroutineFwd.h"
|
||||
#include "Define.h"
|
||||
#include "UniqueTrackablePtr.h"
|
||||
|
||||
namespace Trinity::Coro
|
||||
{
|
||||
class TC_COMMON_API Executor : public enable_unique_weak_from_this<Executor>
|
||||
{
|
||||
public:
|
||||
Executor() = default;
|
||||
Executor(Executor const& other) = delete;
|
||||
Executor(Executor&& other) noexcept = delete;
|
||||
Executor& operator=(Executor const& other) = delete;
|
||||
Executor& operator=(Executor&& other) noexcept = delete;
|
||||
virtual ~Executor() = default;
|
||||
|
||||
virtual void QueueCompletion(CoroutineExecutionContext* context) = 0;
|
||||
};
|
||||
}
|
||||
|
||||
#endif // TRINITYCORE_CORO_EXECUTOR_H
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef TRINITYCORE_CORO_MULTITHREADED_EXECUTOR_H
|
||||
#define TRINITYCORE_CORO_MULTITHREADED_EXECUTOR_H
|
||||
|
||||
#include "./CoroutineExecutionContext.h"
|
||||
#include "./CoroutineFwd.h"
|
||||
#include "./Executor.h"
|
||||
#include "Duration.h"
|
||||
#include "IntrusiveForwardList.h"
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
|
||||
namespace Trinity::Coro
|
||||
{
|
||||
class TC_COMMON_API MultiThreadedExecutor final : public Executor
|
||||
{
|
||||
public:
|
||||
void QueueCompletion(CoroutineExecutionContext* context) override;
|
||||
|
||||
void ResumeReadyCoroutines();
|
||||
|
||||
void WaitForReadyCoroutinesAndResume();
|
||||
|
||||
bool WaitForReadyCoroutinesAndResume(Milliseconds timeout);
|
||||
|
||||
void StopWaiting();
|
||||
|
||||
private:
|
||||
std::mutex _mutex;
|
||||
Containers::IntrusiveForwardList<&CoroutineExecutionContext::QueueLink> _resumeQueue;
|
||||
std::condition_variable _condition;
|
||||
std::atomic_flag _stopped;
|
||||
};
|
||||
}
|
||||
|
||||
#endif // TRINITYCORE_CORO_MULTITHREADED_EXECUTOR_H
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "./ResultValue.h"
|
||||
#include <stdexcept>
|
||||
|
||||
void Trinity::Coro::Impl::ThrowNoValueException(std::exception_ptr exception)
|
||||
{
|
||||
if (exception)
|
||||
std::rethrow_exception(exception);
|
||||
else
|
||||
throw std::logic_error("No value or exception result for coroutine");
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef TRINITYCORE_CORO_RESULT_VALUE_H
|
||||
#define TRINITYCORE_CORO_RESULT_VALUE_H
|
||||
|
||||
#include "./CoroutineFwd.h"
|
||||
#include "Define.h"
|
||||
#include <exception>
|
||||
#include <type_traits>
|
||||
#include <variant>
|
||||
|
||||
namespace Trinity::Coro
|
||||
{
|
||||
namespace Impl
|
||||
{
|
||||
[[noreturn]] TC_COMMON_API void ThrowNoValueException(std::exception_ptr exception);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
class ResultValue
|
||||
{
|
||||
public:
|
||||
using value_holder = std::conditional_t<std::is_reference_v<T>, std::reference_wrapper<std::remove_reference_t<T>>, std::remove_const_t<T>>;
|
||||
|
||||
bool has_value_or_exception() const { return !std::holds_alternative<std::monostate>(_result); }
|
||||
|
||||
template <std::convertible_to<value_holder> V>
|
||||
void set_value(V&& value) { _result.template emplace<value_holder>(std::forward<V>(value)); }
|
||||
|
||||
void set_exception(std::exception_ptr exception) { _result.template emplace<std::exception_ptr>(std::move(exception)); }
|
||||
|
||||
T& get() &
|
||||
{
|
||||
if (std::holds_alternative<value_holder>(_result))
|
||||
return std::get<value_holder>(_result);
|
||||
|
||||
Impl::ThrowNoValueException(std::holds_alternative<std::exception_ptr>(_result)
|
||||
? std::get<std::exception_ptr>(std::move(_result)) : nullptr);
|
||||
}
|
||||
|
||||
T&& get() &&
|
||||
{
|
||||
if (std::holds_alternative<value_holder>(_result))
|
||||
return std::get<value_holder>(std::move(_result));
|
||||
|
||||
Impl::ThrowNoValueException(std::holds_alternative<std::exception_ptr>(_result)
|
||||
? std::get<std::exception_ptr>(std::move(_result)) : nullptr);
|
||||
}
|
||||
|
||||
void reset() { _result.template emplace<std::monostate>(); }
|
||||
|
||||
private:
|
||||
std::variant<std::monostate, value_holder, std::exception_ptr> _result;
|
||||
};
|
||||
|
||||
template <>
|
||||
class ResultValue<void>
|
||||
{
|
||||
public:
|
||||
bool has_value_or_exception() const { return !std::holds_alternative<std::monostate>(_result); }
|
||||
|
||||
void set_value() { _result.emplace<bool>(true); }
|
||||
|
||||
void set_exception(std::exception_ptr exception) { _result.emplace<std::exception_ptr>(std::move(exception)); }
|
||||
|
||||
void get()
|
||||
{
|
||||
if (std::holds_alternative<bool>(_result))
|
||||
return;
|
||||
|
||||
Impl::ThrowNoValueException(std::holds_alternative<std::exception_ptr>(_result)
|
||||
? std::get<std::exception_ptr>(std::move(_result)) : nullptr);
|
||||
}
|
||||
|
||||
void reset() { _result.emplace<std::monostate>(); }
|
||||
|
||||
private:
|
||||
std::variant<std::monostate /*incomplete*/, bool /*successful completion*/, std::exception_ptr> _result;
|
||||
};
|
||||
}
|
||||
|
||||
#endif // TRINITYCORE_CORO_RESULT_VALUE_H
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef TRINITYCORE_CORO_SINGLE_THREADED_EXECUTOR_H
|
||||
#define TRINITYCORE_CORO_SINGLE_THREADED_EXECUTOR_H
|
||||
|
||||
#include "./CoroutineExecutionContext.h"
|
||||
#include "./CoroutineFwd.h"
|
||||
#include "./Executor.h"
|
||||
#include "MPSCQueue.h"
|
||||
|
||||
namespace Trinity::Coro
|
||||
{
|
||||
class TC_COMMON_API SingleThreadedExecutor final : public Executor
|
||||
{
|
||||
public:
|
||||
void QueueCompletion(CoroutineExecutionContext* context) override;
|
||||
|
||||
void ResumeReadyCoroutines();
|
||||
|
||||
private:
|
||||
MPSCQueue<CoroutineExecutionContext, &CoroutineExecutionContext::QueueLink> _resumeQueue;
|
||||
};
|
||||
}
|
||||
|
||||
#endif // TRINITYCORE_CORO_SINGLE_THREADED_EXECUTOR_H
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "./Sleep.h"
|
||||
#include "DeadlineTimer.h"
|
||||
#include "IoContext.h"
|
||||
|
||||
namespace Trinity::Coro
|
||||
{
|
||||
namespace Impl
|
||||
{
|
||||
namespace
|
||||
{
|
||||
Asio::IoContext* TimerExecutor;
|
||||
}
|
||||
|
||||
void SleepAwaiter::handle_suspend(CoroutineExecutionContext* coroutine) noexcept
|
||||
{
|
||||
Asio::DeadlineTimer* timer = new Asio::DeadlineTimer(*TimerExecutor, Expiry);
|
||||
timer->async_wait([coroutine, timer = std::unique_ptr<Asio::DeadlineTimer>(timer)](boost::system::error_code const& error)
|
||||
{
|
||||
if (!error)
|
||||
coroutine->QueueCompletion();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void InitializeTimerExecutor(Asio::IoContext* executor)
|
||||
{
|
||||
Impl::TimerExecutor = executor;
|
||||
}
|
||||
|
||||
void ShutdownTimerExecutor()
|
||||
{
|
||||
Impl::TimerExecutor = nullptr;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef TRINITYCORE_CORO_SLEEP_H
|
||||
#define TRINITYCORE_CORO_SLEEP_H
|
||||
|
||||
#include "./CoroutineExecutionContext.h"
|
||||
#include "./CoroutineFwd.h"
|
||||
#include "AsioHacksFwd.h"
|
||||
#include "Define.h"
|
||||
#include "Duration.h"
|
||||
|
||||
namespace Trinity::Coro
|
||||
{
|
||||
namespace Impl
|
||||
{
|
||||
struct SleepAwaiter
|
||||
{
|
||||
bool await_ready() const noexcept { return Now >= Expiry; }
|
||||
|
||||
template <std::derived_from<CoroutineExecutionContext> promise_type>
|
||||
void await_suspend(std::coroutine_handle<promise_type> coroutine) noexcept
|
||||
{
|
||||
this->handle_suspend(&coroutine.promise());
|
||||
}
|
||||
|
||||
void await_resume() const noexcept { }
|
||||
|
||||
TC_COMMON_API void handle_suspend(CoroutineExecutionContext* coroutine) noexcept;
|
||||
|
||||
TimePoint Now;
|
||||
TimePoint Expiry;
|
||||
};
|
||||
|
||||
class SleepAwaitable
|
||||
{
|
||||
public:
|
||||
explicit SleepAwaitable(TimePoint expiry) : _now(TimePoint::clock::now()), _expiry(expiry) { }
|
||||
explicit SleepAwaitable(TimePoint::duration duration) : _now(TimePoint::clock::now()), _expiry(_now + duration) { }
|
||||
|
||||
SleepAwaiter operator co_await() const { return { .Now = _now, .Expiry = _expiry }; }
|
||||
|
||||
private:
|
||||
TimePoint _now;
|
||||
TimePoint _expiry;
|
||||
};
|
||||
}
|
||||
|
||||
// Initializes the global asio executor that handles all timers
|
||||
// This function must be called before using Coro::SleepFor and Coro::SleepUntil
|
||||
TC_COMMON_API void InitializeTimerExecutor(Asio::IoContext* executor);
|
||||
TC_COMMON_API void ShutdownTimerExecutor();
|
||||
|
||||
inline Impl::SleepAwaitable SleepFor(TimePoint::duration duration) { return Impl::SleepAwaitable(duration); }
|
||||
inline Impl::SleepAwaitable SleepUntil(TimePoint expiry) { return Impl::SleepAwaitable(expiry); }
|
||||
}
|
||||
|
||||
#endif // TRINITYCORE_CORO_SLEEP_H
|
||||
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "./Start.h"
|
||||
#include "./Allocator.h"
|
||||
#include "./AllocatorImpl.h"
|
||||
#include "./Executor.h"
|
||||
#include "Errors.h"
|
||||
#include "Memory.h"
|
||||
#include <array>
|
||||
|
||||
namespace Trinity::Coro::Impl
|
||||
{
|
||||
void CoroutineEntryPoint::promise_type::unhandled_exception() noexcept
|
||||
try
|
||||
{
|
||||
std::rethrow_exception(std::current_exception());
|
||||
}
|
||||
catch (std::exception const& e)
|
||||
{
|
||||
ABORT_MSG("Unhandled coroutine exception: %s", e.what());
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
ABORT_MSG("Unhandled coroutine exception: UNKNOWN");
|
||||
}
|
||||
|
||||
void CoroutineEntryPoint::Start(Executor& executor)
|
||||
{
|
||||
Context->CurrentExecutor = executor.weak_from_this();
|
||||
Context->QueueCompletion();
|
||||
}
|
||||
|
||||
CoroutineEntryPoint Start(std::function<Awaitable<void>()> awaitableSource) noexcept
|
||||
{
|
||||
Allocator allocator;
|
||||
CurrentAllocator::Set(&allocator);
|
||||
auto allocatorGuard = Trinity::make_unique_ptr_with_deleter<[](void*){ CurrentAllocator::Set(nullptr); }>(&allocator);
|
||||
|
||||
Awaitable<void> awaitable = awaitableSource();
|
||||
|
||||
co_await awaitable;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef TRINITYCORE_CORO_START_H
|
||||
#define TRINITYCORE_CORO_START_H
|
||||
|
||||
#include "./Awaitable.h"
|
||||
#include "./CoroutineExecutionContext.h"
|
||||
#include "./CoroutineFwd.h"
|
||||
#include "Concepts.h"
|
||||
#include "Define.h"
|
||||
#include <functional>
|
||||
|
||||
namespace Trinity::Coro
|
||||
{
|
||||
namespace Impl
|
||||
{
|
||||
struct CoroutineEntryPoint
|
||||
{
|
||||
struct promise_type : CoroutineExecutionContext
|
||||
{
|
||||
promise_type() : CoroutineExecutionContext(std::coroutine_handle<promise_type>::from_promise(*this)) { }
|
||||
|
||||
CoroutineEntryPoint get_return_object() noexcept;
|
||||
|
||||
std::suspend_always initial_suspend() noexcept { return { }; }
|
||||
|
||||
std::suspend_never final_suspend() noexcept { return { }; }
|
||||
|
||||
void return_void() noexcept { }
|
||||
|
||||
[[noreturn]] TC_COMMON_API void unhandled_exception() noexcept;
|
||||
};
|
||||
|
||||
TC_COMMON_API void Start(Executor& executor);
|
||||
|
||||
CoroutineExecutionContext* Context = nullptr;
|
||||
};
|
||||
|
||||
inline CoroutineEntryPoint CoroutineEntryPoint::promise_type::get_return_object() noexcept
|
||||
{
|
||||
return { .Context = this };
|
||||
}
|
||||
|
||||
TC_COMMON_API CoroutineEntryPoint Start(std::function<Awaitable<void>()> awaitableSource) noexcept;
|
||||
}
|
||||
|
||||
template <typename CoroutineInitFunc>
|
||||
requires (invocable_r<CoroutineInitFunc, Awaitable<void>>
|
||||
&& std::is_rvalue_reference_v<CoroutineInitFunc&&>
|
||||
&& !std::is_const_v<std::remove_reference_t<CoroutineInitFunc>>)
|
||||
void Start(Executor& executor, CoroutineInitFunc&& coroutineInit)
|
||||
{
|
||||
Impl::CoroutineEntryPoint entryPoint = Impl::Start(std::forward<CoroutineInitFunc>(coroutineInit));
|
||||
entryPoint.Start(executor);
|
||||
}
|
||||
}
|
||||
|
||||
#endif // TRINITYCORE_CORO_START_H
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "./SwitchExecutor.h"
|
||||
#include "./CoroutineExecutionContext.h"
|
||||
#include "./Executor.h"
|
||||
#include <stdexcept>
|
||||
|
||||
namespace Trinity::Coro
|
||||
{
|
||||
namespace Impl
|
||||
{
|
||||
void SwitchToExecutorAwaiter::handle_suspend(CoroutineExecutionContext* coroutine)
|
||||
{
|
||||
OldExecutor = coroutine->CurrentExecutor;
|
||||
NewExecutor.QueueCompletion(coroutine);
|
||||
}
|
||||
}
|
||||
|
||||
Executor& SwitchToExecutor::resolve_executor(unique_weak_ptr<Executor> const& executorRef)
|
||||
{
|
||||
if (unique_strong_ref_ptr<unique_weak_ptr<Executor>::element_type> executor = executorRef.lock())
|
||||
return *executor;
|
||||
|
||||
throw std::invalid_argument("Expired executor");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef TRINITYCORE_CORO_SWITCH_EXECUTOR_H
|
||||
#define TRINITYCORE_CORO_SWITCH_EXECUTOR_H
|
||||
|
||||
#include "./CoroutineFwd.h"
|
||||
#include "Define.h"
|
||||
#include "UniqueTrackablePtr.h"
|
||||
#include <coroutine>
|
||||
|
||||
namespace Trinity::Coro
|
||||
{
|
||||
namespace Impl
|
||||
{
|
||||
struct TC_COMMON_API SwitchToExecutorAwaiter
|
||||
{
|
||||
bool await_ready() const noexcept { return false; }
|
||||
|
||||
template <std::derived_from<CoroutineExecutionContext> promise_type>
|
||||
void await_suspend(std::coroutine_handle<promise_type> coroutine) noexcept
|
||||
{
|
||||
this->handle_suspend(&coroutine.promise());
|
||||
}
|
||||
|
||||
void handle_suspend(CoroutineExecutionContext* coroutine);
|
||||
|
||||
unique_weak_ptr<Coro::Executor>&& await_resume() noexcept { return std::move(OldExecutor); }
|
||||
|
||||
Coro::Executor& NewExecutor;
|
||||
unique_weak_ptr<Coro::Executor> OldExecutor;
|
||||
};
|
||||
}
|
||||
|
||||
class SwitchToExecutor
|
||||
{
|
||||
public:
|
||||
explicit SwitchToExecutor(Executor& executor) : _executor(executor) { }
|
||||
explicit SwitchToExecutor(unique_weak_ptr<Executor> const& executor) : _executor(resolve_executor(executor)) { }
|
||||
|
||||
Impl::SwitchToExecutorAwaiter operator co_await() const && noexcept { return { .NewExecutor = _executor }; }
|
||||
|
||||
private:
|
||||
TC_COMMON_API static Executor& resolve_executor(unique_weak_ptr<Executor> const& executorRef);
|
||||
|
||||
Executor& _executor;
|
||||
};
|
||||
}
|
||||
|
||||
#endif // TRINITYCORE_CORO_SWITCH_EXECUTOR_H
|
||||
@@ -40,9 +40,8 @@ public:
|
||||
|
||||
~MPSCQueueNonIntrusive()
|
||||
{
|
||||
T* output;
|
||||
while (Dequeue(output))
|
||||
delete output;
|
||||
while (Dequeue())
|
||||
; // delete only all Node objects, not their contents
|
||||
|
||||
Node* front = _head.load(std::memory_order_relaxed);
|
||||
delete front;
|
||||
@@ -55,17 +54,17 @@ public:
|
||||
prevHead->Next.store(node, std::memory_order_release);
|
||||
}
|
||||
|
||||
bool Dequeue(T*& result)
|
||||
T* Dequeue()
|
||||
{
|
||||
Node* tail = _tail.load(std::memory_order_relaxed);
|
||||
Node* next = tail->Next.load(std::memory_order_acquire);
|
||||
if (!next)
|
||||
return false;
|
||||
|
||||
result = next->Data;
|
||||
T* result = next->Data;
|
||||
_tail.store(next, std::memory_order_release);
|
||||
delete tail;
|
||||
return true;
|
||||
return result;
|
||||
}
|
||||
|
||||
private:
|
||||
@@ -106,10 +105,6 @@ public:
|
||||
|
||||
~MPSCQueueIntrusive()
|
||||
{
|
||||
T* output;
|
||||
while (Dequeue(output))
|
||||
delete output;
|
||||
|
||||
// destruct our dummy atomic
|
||||
(_dummyPtr->*IntrusiveLink).~Atomic();
|
||||
}
|
||||
@@ -121,14 +116,14 @@ public:
|
||||
(prevHead->*IntrusiveLink).store(input, std::memory_order_release);
|
||||
}
|
||||
|
||||
bool Dequeue(T*& result) noexcept
|
||||
T* Dequeue() noexcept
|
||||
{
|
||||
T* tail = _tail.load(std::memory_order_relaxed);
|
||||
T* next = (tail->*IntrusiveLink).load(std::memory_order_acquire);
|
||||
if (tail == _dummyPtr)
|
||||
{
|
||||
if (!next)
|
||||
return false;
|
||||
return nullptr;
|
||||
|
||||
_tail.store(next, std::memory_order_release);
|
||||
tail = next;
|
||||
@@ -138,23 +133,21 @@ public:
|
||||
if (next)
|
||||
{
|
||||
_tail.store(next, std::memory_order_release);
|
||||
result = tail;
|
||||
return true;
|
||||
return tail;
|
||||
}
|
||||
|
||||
T* head = _head.load(std::memory_order_acquire);
|
||||
if (tail != head)
|
||||
return false;
|
||||
return nullptr;
|
||||
|
||||
Enqueue(_dummyPtr);
|
||||
this->Enqueue(_dummyPtr);
|
||||
next = (tail->*IntrusiveLink).load(std::memory_order_acquire);
|
||||
if (next)
|
||||
{
|
||||
_tail.store(next, std::memory_order_release);
|
||||
result = tail;
|
||||
return true;
|
||||
return tail;
|
||||
}
|
||||
return false;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
@@ -125,7 +125,18 @@ namespace
|
||||
return result;
|
||||
}, chance * chance, 0.0f, chance, 6, iterationLimit);
|
||||
}
|
||||
} const ChanceCache;
|
||||
};
|
||||
|
||||
static std::array<float, 10000> const& Instance()
|
||||
{
|
||||
static PseudoRandomDistributionChanceTable const Cache;
|
||||
return Cache;
|
||||
}
|
||||
}
|
||||
|
||||
void PreloadPseudoRandomDistributionChances()
|
||||
{
|
||||
(void)PseudoRandomDistributionChanceTable::Instance();
|
||||
}
|
||||
|
||||
bool roll_chance(float chance, PseudoRandomDistributionState& state)
|
||||
@@ -134,7 +145,8 @@ bool roll_chance(float chance, PseudoRandomDistributionState& state)
|
||||
if (chanceIndex < 0)
|
||||
return false;
|
||||
|
||||
if (chanceIndex >= std::ssize(ChanceCache) || state.AccumulateChance(ChanceCache[chanceIndex]) > rand_norm())
|
||||
std::array<float, 10000> const& chances = PseudoRandomDistributionChanceTable::Instance();
|
||||
if (chanceIndex >= std::ssize(chances) || state.AccumulateChance(chances[chanceIndex]) > rand_norm())
|
||||
{
|
||||
state.Reset();
|
||||
return true;
|
||||
|
||||
@@ -93,6 +93,8 @@ private:
|
||||
float _progress = 0.0f;
|
||||
};
|
||||
|
||||
TC_COMMON_API void PreloadPseudoRandomDistributionChances();
|
||||
|
||||
/* Return true if a random roll fits in the specified chance (range 0-100) using pseudo random distribution that minimizes long good/bad luck streaks. */
|
||||
TC_COMMON_API bool roll_chance(float chance, PseudoRandomDistributionState& state);
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
#define TRINITYCORE_TYPES_H
|
||||
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
namespace Trinity
|
||||
{
|
||||
@@ -71,6 +72,42 @@ namespace Trinity
|
||||
|
||||
template <typename T>
|
||||
constexpr bool dependant_false_v = dependant_false<T>::value;
|
||||
|
||||
template <std::size_t... I, std::size_t... J, typename... Rest>
|
||||
constexpr auto concat_index_sequences(std::index_sequence<I...>, std::index_sequence<J...>, Rest...)
|
||||
{
|
||||
if constexpr (sizeof...(Rest) > 0)
|
||||
return Trinity::concat_index_sequences(std::index_sequence<I..., J...>(), Rest()...);
|
||||
else
|
||||
return std::index_sequence<I..., J...>();
|
||||
}
|
||||
|
||||
namespace Impl
|
||||
{
|
||||
template <std::size_t I, typename Predicate>
|
||||
constexpr auto apply_index_sequence_filter(std::index_sequence<I>, Predicate predicate)
|
||||
{
|
||||
if constexpr (predicate(std::index_sequence<I>()))
|
||||
return std::index_sequence<I>();
|
||||
else
|
||||
return std::index_sequence<>();
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Utility to filter std::index_sequence
|
||||
* Predicate must be callable in constexpr context with single element std::index_sequence<I>
|
||||
*
|
||||
* Example:
|
||||
* std::index_sequence<0, 1, 2, 3, 4> source;
|
||||
* // type of result is std::index_sequence<1, 3>
|
||||
* auto result = Trinity::filter_index_sequence(source, []<std::size_t I>(std::index_sequence<I>) constexpr { return I % 2 != 0; });
|
||||
*/
|
||||
template <std::size_t... I, typename Predicate>
|
||||
constexpr auto filter_index_sequence(std::index_sequence<I...>, Predicate predicate)
|
||||
{
|
||||
return Trinity::concat_index_sequences(Impl::apply_index_sequence_filter(std::index_sequence<I>(), predicate)...);
|
||||
}
|
||||
}
|
||||
|
||||
#endif // TRINITYCORE_TYPES_H
|
||||
|
||||
@@ -130,6 +130,14 @@ enum class GossipOptionFlags : int32
|
||||
PlayMovieLabelPrepend = 0x4
|
||||
};
|
||||
|
||||
enum class GossipOptionDefaultAction : uint8
|
||||
{
|
||||
PlayerCastSpellOnThemselves = 0, // The player will cast the SpellID of the option onto himself as instant cast
|
||||
PlayerUpdatesInteractions = 1, // NYI
|
||||
NpcCastsSpell = 2, // The gossip sender npc will cast the SpellID on the player
|
||||
GossipBeginsPetBattle = 4 // NYI - Initiates a pet battle
|
||||
};
|
||||
|
||||
struct GossipMenuItem
|
||||
{
|
||||
int32 GossipOptionID;
|
||||
|
||||
@@ -14507,9 +14507,27 @@ void Player::OnGossipSelect(WorldObject* source, int32 gossipOptionId, uint32 me
|
||||
switch (gossipOptionNpc)
|
||||
{
|
||||
case GossipOptionNpc::None:
|
||||
// Retail leaves Chromie Time via gossip SpellID (e.g. 335807 / effect 277 MiscValue 0)
|
||||
if (item->SpellID)
|
||||
if (GossipMenuItemsAddon const* addon = sObjectMgr->GetGossipMenuItemAddon(menuId, item->OrderIndex))
|
||||
{
|
||||
switch (addon->DefaultAction)
|
||||
{
|
||||
case GossipOptionDefaultAction::PlayerCastSpellOnThemselves:
|
||||
if (item->SpellID)
|
||||
CastSpell(this, *item->SpellID, TRIGGERED_IGNORE_CAST_TIME);
|
||||
break;
|
||||
case GossipOptionDefaultAction::NpcCastsSpell:
|
||||
if (item->SpellID)
|
||||
if (Creature* creature = Object::ToCreature(source))
|
||||
creature->CastSpell(this, *item->SpellID, TRIGGERED_IGNORE_CAST_TIME);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
PlayerTalkClass->SendCloseGossip();
|
||||
}
|
||||
else if (item->SpellID)
|
||||
{
|
||||
// Retail leaves Chromie Time via gossip SpellID (e.g. 335807 / effect 277 MiscValue 0)
|
||||
PlayerTalkClass->SendCloseGossip();
|
||||
CastSpell(this, uint32(*item->SpellID), true);
|
||||
}
|
||||
|
||||
@@ -242,6 +242,21 @@ ObjectMgr::~ObjectMgr()
|
||||
{
|
||||
}
|
||||
|
||||
GossipMenuItemsAddon const* ObjectMgr::GetGossipMenuItemAddon(uint32 menuId, uint32 orderIndex)
|
||||
{
|
||||
Trinity::IteratorPair<GossipMenuItemsAddonContainer::iterator> bounds = Trinity::Containers::MapEqualRange(_gossipMenuItemsAddonStore, menuId);
|
||||
|
||||
auto itr = std::ranges::find(bounds, orderIndex, [](std::pair<uint32 const, GossipMenuItemsAddon> const& itemPair)
|
||||
{
|
||||
return itemPair.second.OrderIndex;
|
||||
});
|
||||
|
||||
if (itr == bounds.end())
|
||||
return nullptr;
|
||||
|
||||
return &itr->second;
|
||||
}
|
||||
|
||||
void ObjectMgr::AddLocaleString(std::string_view value, LocaleConstant localeConstant, std::vector<std::string>& data)
|
||||
{
|
||||
if (data.size() <= size_t(localeConstant))
|
||||
@@ -9815,6 +9830,58 @@ void ObjectMgr::LoadGossipMenuAddon()
|
||||
TC_LOG_INFO("server.loading", ">> Loaded {} gossip_menu_addon IDs in {} ms", uint32(_gossipMenuAddonStore.size()), GetMSTimeDiffToNow(oldMSTime));
|
||||
}
|
||||
|
||||
void ObjectMgr::LoadGossipMenuItemsAddon()
|
||||
{
|
||||
uint32 oldMSTime = getMSTime();
|
||||
|
||||
_gossipMenuItemsAddonStore.clear();
|
||||
|
||||
QueryResult result = WorldDatabase.Query(
|
||||
// 0 1 2
|
||||
"SELECT MenuID, OptionID, DefaultAction "
|
||||
"FROM gossip_menu_option_addon ORDER BY MenuID, OptionID");
|
||||
|
||||
if (!result)
|
||||
{
|
||||
TC_LOG_INFO("server.loading", ">> Loaded 0 gossip_menu_option_addon entries. DB table `gossip_menu_option_addon` is empty!");
|
||||
return;
|
||||
}
|
||||
|
||||
do
|
||||
{
|
||||
Field* fields = result->Fetch();
|
||||
|
||||
GossipMenuItemsAddon gMenuItemAddon;
|
||||
|
||||
gMenuItemAddon.MenuID = fields[0].GetUInt32();
|
||||
gMenuItemAddon.OrderIndex = fields[1].GetUInt32();
|
||||
gMenuItemAddon.DefaultAction = GossipOptionDefaultAction(fields[2].GetUInt8());
|
||||
|
||||
Trinity::IteratorPair<GossipMenuItemsContainer::iterator> bounds = Trinity::Containers::MapEqualRange(_gossipMenuItemsStore, gMenuItemAddon.MenuID);
|
||||
auto itr = std::ranges::find(bounds, gMenuItemAddon.OrderIndex, [](std::pair<uint32 const, GossipMenuItems> const& itemPair)
|
||||
{
|
||||
return itemPair.second.OrderIndex;
|
||||
});
|
||||
|
||||
if (itr == bounds.end())
|
||||
{
|
||||
TC_LOG_ERROR("sql.sql", "Table `gossip_menu_option_addon` for menu {}, id {} contains no parent entry in table `gossip_menu_option`, ignoring.", gMenuItemAddon.MenuID, gMenuItemAddon.OrderIndex);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (gMenuItemAddon.DefaultAction > GossipOptionDefaultAction::GossipBeginsPetBattle)
|
||||
{
|
||||
TC_LOG_ERROR("sql.sql", "Table `gossip_menu_option_addon` for menu {}, id {} has an undefined DefaultAction ({}), ignoring.", gMenuItemAddon.MenuID, gMenuItemAddon.OrderIndex, gMenuItemAddon.DefaultAction);
|
||||
continue;
|
||||
}
|
||||
|
||||
_gossipMenuItemsAddonStore.insert(GossipMenuItemsAddonContainer::value_type(gMenuItemAddon.MenuID, gMenuItemAddon));
|
||||
|
||||
} while (result->NextRow());
|
||||
|
||||
TC_LOG_INFO("server.loading", ">> Loaded {} gossip_menu_option_addon entries in {} ms", _gossipMenuItemsAddonStore.size(), GetMSTimeDiffToNow(oldMSTime));
|
||||
}
|
||||
|
||||
Trainer::Trainer const* ObjectMgr::GetTrainer(uint32 trainerId) const
|
||||
{
|
||||
return Trinity::Containers::MapGetValuePtr(_trainers, trainerId);
|
||||
|
||||
@@ -51,6 +51,7 @@ class Vehicle;
|
||||
class Map;
|
||||
enum class GossipOptionFlags : int32;
|
||||
enum class GossipOptionNpc : uint8;
|
||||
enum class GossipOptionDefaultAction : uint8;
|
||||
enum class SummonPropertiesEffectValueType : uint8;
|
||||
struct AccessRequirement;
|
||||
struct DeclinedName;
|
||||
@@ -797,6 +798,13 @@ struct GossipMenuItems
|
||||
ConditionsReference Conditions;
|
||||
};
|
||||
|
||||
struct GossipMenuItemsAddon
|
||||
{
|
||||
uint32 MenuID;
|
||||
uint32 OrderIndex;
|
||||
GossipOptionDefaultAction DefaultAction;
|
||||
};
|
||||
|
||||
struct GossipMenus
|
||||
{
|
||||
uint32 MenuID;
|
||||
@@ -814,6 +822,7 @@ typedef std::multimap<uint32, GossipMenus> GossipMenusContainer;
|
||||
typedef std::pair<GossipMenusContainer::const_iterator, GossipMenusContainer::const_iterator> GossipMenusMapBounds;
|
||||
typedef std::pair<GossipMenusContainer::iterator, GossipMenusContainer::iterator> GossipMenusMapBoundsNonConst;
|
||||
typedef std::multimap<uint32, GossipMenuItems> GossipMenuItemsContainer;
|
||||
typedef std::multimap<uint32, GossipMenuItemsAddon> GossipMenuItemsAddonContainer;
|
||||
typedef std::unordered_map<uint32, GossipMenuAddon> GossipMenuAddonContainer;
|
||||
|
||||
struct QuestPOIBlobPoint
|
||||
@@ -1394,6 +1403,7 @@ class TC_GAME_API ObjectMgr
|
||||
void LoadGossipMenu();
|
||||
void LoadGossipMenuItems();
|
||||
void LoadGossipMenuAddon();
|
||||
void LoadGossipMenuItemsAddon();
|
||||
|
||||
void LoadVendors();
|
||||
void LoadTrainers();
|
||||
@@ -1699,6 +1709,8 @@ class TC_GAME_API ObjectMgr
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
GossipMenuItemsAddon const* GetGossipMenuItemAddon(uint32 menuId, uint32 orderIndex);
|
||||
|
||||
// for wintergrasp only
|
||||
GraveyardContainer GraveyardStore;
|
||||
|
||||
@@ -1821,6 +1833,7 @@ class TC_GAME_API ObjectMgr
|
||||
GossipMenusContainer _gossipMenusStore;
|
||||
GossipMenuItemsContainer _gossipMenuItemsStore;
|
||||
GossipMenuAddonContainer _gossipMenuAddonStore;
|
||||
GossipMenuItemsAddonContainer _gossipMenuItemsAddonStore;
|
||||
PointOfInterestContainer _pointsOfInterestStore;
|
||||
|
||||
QuestPOIContainer _questPOIStore;
|
||||
|
||||
@@ -111,6 +111,9 @@ struct RespawnInfoWithHandle : RespawnInfo
|
||||
|
||||
Map::~Map()
|
||||
{
|
||||
while (FarSpellCallback* callback = _farSpellCallbacks.Dequeue())
|
||||
delete callback;
|
||||
|
||||
// Delete all waiting spawns, else there will be a memory leak
|
||||
// This doesn't delete from database.
|
||||
UnloadAllRespawnInfos();
|
||||
@@ -2703,20 +2706,17 @@ ObjectGuidGenerator& Map::GetGuidSequenceGenerator(HighGuid high)
|
||||
return _guidGenerators.try_emplace(high, high).first->second;
|
||||
}
|
||||
|
||||
void Map::AddFarSpellCallback(FarSpellCallback&& callback)
|
||||
void Map::AddFarSpellCallback(std::function<void(Map*)>&& callback)
|
||||
{
|
||||
_farSpellCallbacks.Enqueue(new FarSpellCallback(std::move(callback)));
|
||||
_farSpellCallbacks.Enqueue(new FarSpellCallback{ .Func = std::move(callback) });
|
||||
}
|
||||
|
||||
void Map::DelayedUpdate(uint32 t_diff)
|
||||
{
|
||||
while (FarSpellCallback* callback = _farSpellCallbacks.Dequeue())
|
||||
{
|
||||
FarSpellCallback* callback;
|
||||
while (_farSpellCallbacks.Dequeue(callback))
|
||||
{
|
||||
(*callback)(this);
|
||||
delete callback;
|
||||
}
|
||||
callback->Func(this);
|
||||
delete callback;
|
||||
}
|
||||
|
||||
RemoveAllObjectsInRemoveList();
|
||||
|
||||
@@ -786,8 +786,12 @@ class TC_GAME_API Map : public GridRefManager<NGridType>
|
||||
SpawnedPoolData& GetPoolData() { return *_poolData; }
|
||||
SpawnedPoolData const& GetPoolData() const { return *_poolData; }
|
||||
|
||||
typedef std::function<void(Map*)> FarSpellCallback;
|
||||
void AddFarSpellCallback(FarSpellCallback&& callback);
|
||||
struct FarSpellCallback
|
||||
{
|
||||
std::function<void(Map*)> Func;
|
||||
std::atomic<FarSpellCallback*> QueueLink;
|
||||
};
|
||||
void AddFarSpellCallback(std::function<void(Map*)>&& callback);
|
||||
|
||||
void InitSpawnGroupState();
|
||||
void UpdateSpawnGroupConditions();
|
||||
@@ -857,7 +861,7 @@ class TC_GAME_API Map : public GridRefManager<NGridType>
|
||||
|
||||
std::unordered_set<BaseEntity*> _updateObjects;
|
||||
|
||||
MPSCQueue<FarSpellCallback> _farSpellCallbacks;
|
||||
MPSCQueue<FarSpellCallback, &FarSpellCallback::QueueLink> _farSpellCallbacks;
|
||||
|
||||
/*********************************************************/
|
||||
/*** Phasing ***/
|
||||
|
||||
@@ -631,8 +631,7 @@ public:
|
||||
void Update() final override
|
||||
{
|
||||
// Consume all messages
|
||||
ScriptReloaderMessage* message;
|
||||
while (_messages.Dequeue(message))
|
||||
while (ScriptReloaderMessage* message = _messages.Dequeue())
|
||||
{
|
||||
(*message)(this);
|
||||
delete message;
|
||||
@@ -1385,8 +1384,7 @@ private:
|
||||
void RemoveAllQueuedMessages()
|
||||
{
|
||||
// Delete all messages
|
||||
ScriptReloaderMessage* message;
|
||||
while (_messages.Dequeue(message))
|
||||
while (ScriptReloaderMessage* message = _messages.Dequeue())
|
||||
delete message;
|
||||
}
|
||||
|
||||
|
||||
@@ -70,6 +70,9 @@ WorldSocket::WorldSocket(Trinity::Net::IoContextTcpSocket&& socket) : BaseSocket
|
||||
|
||||
WorldSocket::~WorldSocket()
|
||||
{
|
||||
while (EncryptablePacket* queuedPacket = _bufferQueue.Dequeue())
|
||||
delete queuedPacket;
|
||||
|
||||
if (_compressionStream)
|
||||
{
|
||||
deflateEnd(_compressionStream);
|
||||
@@ -201,8 +204,7 @@ bool WorldSocket::InitializeCompression()
|
||||
|
||||
bool WorldSocket::Update()
|
||||
{
|
||||
EncryptablePacket* queued;
|
||||
if (_bufferQueue.Dequeue(queued))
|
||||
if (EncryptablePacket* queued = _bufferQueue.Dequeue())
|
||||
{
|
||||
// Allocate buffer only when it's needed but not on every Update() call.
|
||||
MessageBuffer buffer(_sendBufferSize);
|
||||
@@ -229,7 +231,7 @@ bool WorldSocket::Update()
|
||||
}
|
||||
|
||||
delete queued;
|
||||
} while (_bufferQueue.Dequeue(queued));
|
||||
} while ((queued = _bufferQueue.Dequeue()));
|
||||
|
||||
if (buffer.GetActiveSize() > 0)
|
||||
QueuePacket(std::move(buffer));
|
||||
|
||||
@@ -84,6 +84,7 @@
|
||||
#include "PoolMgr.h"
|
||||
#include "QuestMgr.h"
|
||||
#include "QuestPools.h"
|
||||
#include "Random.h"
|
||||
#include "RealmList.h"
|
||||
#include "ScenarioMgr.h"
|
||||
#include "ScriptMgr.h"
|
||||
@@ -1313,6 +1314,7 @@ bool World::SetInitialWorldSettings()
|
||||
|
||||
///- Initialize the random number generator
|
||||
srand((unsigned int)GameTime::GetGameTime());
|
||||
PreloadPseudoRandomDistributionChances();
|
||||
|
||||
///- Initialize detour memory management
|
||||
dtAllocSetCustom(dtCustomAlloc, dtCustomFree);
|
||||
@@ -1958,6 +1960,9 @@ bool World::SetInitialWorldSettings()
|
||||
TC_LOG_INFO("server.loading", "Loading Gossip menu addon...");
|
||||
sObjectMgr->LoadGossipMenuAddon();
|
||||
|
||||
TC_LOG_INFO("server.loading", "Loading Gossip menu options addon...");
|
||||
sObjectMgr->LoadGossipMenuItemsAddon();
|
||||
|
||||
TC_LOG_INFO("server.loading", "Loading Creature Template Gossip...");
|
||||
sObjectMgr->LoadCreatureTemplateGossip();
|
||||
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
/*
|
||||
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License as published by the
|
||||
* Free Software Foundation; either version 2 of the License, or (at your
|
||||
* option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
* more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along
|
||||
* with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "tc_catch2.h"
|
||||
|
||||
#include "Common.h"
|
||||
#include "Coro/AllOf.h"
|
||||
#include "Coro/AllocatorImpl.h"
|
||||
#include "Coro/Awaitable.h"
|
||||
#include "Coro/AwaitableValue.h"
|
||||
#include "Coro/CurrentCoroutine.h"
|
||||
#include "Coro/MultiThreadedExecutor.h"
|
||||
#include "Coro/Sleep.h"
|
||||
#include "Coro/Start.h"
|
||||
#include "Coro/SwitchExecutor.h"
|
||||
#include "Duration.h"
|
||||
#include "IoContext.h"
|
||||
#include <thread>
|
||||
|
||||
class CoroutineFixture
|
||||
{
|
||||
public:
|
||||
Trinity::unique_trackable_ptr<Trinity::Coro::MultiThreadedExecutor> executor = Trinity::make_unique_trackable<Trinity::Coro::MultiThreadedExecutor>();
|
||||
std::variant<bool, std::exception_ptr> testCoroutineStatus = false;
|
||||
Trinity::Asio::IoContext timerContext;
|
||||
boost::asio::executor_work_guard<Trinity::Asio::IoContextExecutor> timerWorkGuard = boost::asio::make_work_guard(timerContext);
|
||||
std::thread timerThread;
|
||||
|
||||
CoroutineFixture()
|
||||
{
|
||||
Trinity::Coro::InitializeTimerExecutor(&timerContext);
|
||||
timerThread = std::thread([this] { timerContext.run(); });
|
||||
}
|
||||
|
||||
~CoroutineFixture() noexcept(false)
|
||||
{
|
||||
bool timedOut = !executor->WaitForReadyCoroutinesAndResume(30s);
|
||||
|
||||
timerWorkGuard.reset();
|
||||
timerThread.join();
|
||||
Trinity::Coro::ShutdownTimerExecutor();
|
||||
|
||||
if (timedOut)
|
||||
FAIL("executor->WaitForReadyCoroutinesAndResume(30s) timed out");
|
||||
|
||||
if (std::holds_alternative<std::exception_ptr>(testCoroutineStatus))
|
||||
std::rethrow_exception(std::get<std::exception_ptr>(testCoroutineStatus));
|
||||
|
||||
if (!std::get<bool>(testCoroutineStatus))
|
||||
FAIL("Test coroutine not finished");
|
||||
}
|
||||
|
||||
CoroutineFixture(CoroutineFixture const& other) = delete;
|
||||
CoroutineFixture(CoroutineFixture&& other) noexcept = delete;
|
||||
CoroutineFixture& operator=(CoroutineFixture const& other) = delete;
|
||||
CoroutineFixture& operator=(CoroutineFixture&& other) noexcept = delete;
|
||||
};
|
||||
|
||||
template<std::derived_from<CoroutineFixture> TestFixture>
|
||||
struct std::coroutine_traits<void, TestFixture&>
|
||||
{
|
||||
struct promise_type : Trinity::Coro::CoroutineExecutionContext
|
||||
{
|
||||
promise_type(TestFixture& fixture) : CoroutineExecutionContext(std::coroutine_handle<promise_type>::from_promise(*this)),
|
||||
_testFixture(fixture)
|
||||
{
|
||||
CurrentExecutor = fixture.executor->weak_from_this();
|
||||
CurrentAllocator = &_allocator;
|
||||
Trinity::Coro::Impl::CurrentAllocator::Set(CurrentAllocator);
|
||||
}
|
||||
|
||||
~promise_type()
|
||||
{
|
||||
Trinity::Coro::Impl::CurrentAllocator::Set(nullptr);
|
||||
}
|
||||
|
||||
void get_return_object() noexcept { }
|
||||
|
||||
std::suspend_never initial_suspend() noexcept { return { }; }
|
||||
|
||||
std::suspend_never final_suspend() noexcept { return { }; }
|
||||
|
||||
void return_void() noexcept
|
||||
{
|
||||
_testFixture.testCoroutineStatus = true;
|
||||
_testFixture.executor->StopWaiting();
|
||||
}
|
||||
|
||||
void unhandled_exception() noexcept
|
||||
{
|
||||
_testFixture.testCoroutineStatus = std::current_exception();
|
||||
_testFixture.executor->StopWaiting();
|
||||
}
|
||||
|
||||
TestFixture& _testFixture;
|
||||
Trinity::Coro::Impl::Allocator _allocator;
|
||||
|
||||
promise_type(promise_type const& other) = delete;
|
||||
promise_type(promise_type&& other) noexcept = delete;
|
||||
promise_type& operator=(promise_type const& other) = delete;
|
||||
promise_type& operator=(promise_type&& other) noexcept = delete;
|
||||
};
|
||||
};
|
||||
|
||||
Trinity::Coro::Awaitable<int32> TestCoro1()
|
||||
{
|
||||
co_return 1;
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(CoroutineFixture, "Coro::Allocator is available to nested coroutines", "[Coroutine][Allocator]")
|
||||
{
|
||||
// test failure is a segfault
|
||||
REQUIRE(co_await TestCoro1() == 1);
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(CoroutineFixture, "Coro::AwaitableValue resumes coroutine after obtaining value", "[Coroutine][AwaitableValue]")
|
||||
{
|
||||
Trinity::Coro::AwaitableValue<int32> asyncValue;
|
||||
|
||||
std::thread thrd([&asyncValue]
|
||||
{
|
||||
std::this_thread::sleep_for(0.5s);
|
||||
asyncValue.set_value(1);
|
||||
});
|
||||
|
||||
int32 result = co_await asyncValue;
|
||||
|
||||
thrd.join();
|
||||
|
||||
REQUIRE(result == 1);
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(CoroutineFixture, "Coro::AwaitableValue doesn't suspend coroutine when value is ready before co_await", "[Coroutine][AwaitableValue]")
|
||||
{
|
||||
Trinity::Coro::AwaitableValue<int32> asyncValue;
|
||||
|
||||
asyncValue.set_value(1);
|
||||
|
||||
int32 result = co_await asyncValue;
|
||||
|
||||
REQUIRE(result == 1);
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(CoroutineFixture, "Coro::CurrentExecutor returns current executor associated with coroutine", "[Coroutine][AwaitableValue]")
|
||||
{
|
||||
Trinity::unique_weak_ptr<Trinity::Coro::Executor> result = co_await Trinity::Coro::CurrentExecutor;
|
||||
|
||||
REQUIRE(result.lock().get() == executor.get());
|
||||
}
|
||||
|
||||
TEST_CASE("Coro::Start starts a new coroutine", "[Coroutine][Start]")
|
||||
{
|
||||
Trinity::unique_trackable_ptr<Trinity::Coro::MultiThreadedExecutor> executor = Trinity::make_unique_trackable<Trinity::Coro::MultiThreadedExecutor>();
|
||||
bool executed = false;
|
||||
|
||||
Trinity::Coro::Start(*executor, [&executor, &executed]() -> Trinity::Coro::Awaitable<void>
|
||||
{
|
||||
executed = true;
|
||||
executor->StopWaiting();
|
||||
co_return;
|
||||
});
|
||||
|
||||
REQUIRE(executor->WaitForReadyCoroutinesAndResume(30s));
|
||||
REQUIRE(executed);
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(CoroutineFixture, "Coro::SwitchToExecutor changes executor associated with coroutine", "[Coroutine][SwitchToExecutor]")
|
||||
{
|
||||
Trinity::unique_trackable_ptr<Trinity::Coro::MultiThreadedExecutor> otherExecutor = Trinity::make_unique_trackable<Trinity::Coro::MultiThreadedExecutor>();
|
||||
std::thread otherExecutorThread([&otherExecutor] { otherExecutor->WaitForReadyCoroutinesAndResume(30s); });
|
||||
|
||||
co_await Trinity::Coro::SwitchToExecutor(*otherExecutor);
|
||||
|
||||
auto current = co_await Trinity::Coro::CurrentExecutor;
|
||||
|
||||
REQUIRE(current.lock().get() == otherExecutor.get());
|
||||
|
||||
co_await Trinity::Coro::SwitchToExecutor(*executor);
|
||||
|
||||
current = co_await Trinity::Coro::CurrentExecutor;
|
||||
|
||||
REQUIRE(current.lock().get() == executor.get());
|
||||
|
||||
otherExecutor->StopWaiting();
|
||||
otherExecutorThread.join();
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(CoroutineFixture, "Coro::SleepFor delays coroutine", "[Coroutine][Sleep]")
|
||||
{
|
||||
Seconds sleepDuration = 1s;
|
||||
|
||||
TimePoint start = TimePoint::clock::now();
|
||||
|
||||
co_await Trinity::Coro::SleepFor(sleepDuration);
|
||||
|
||||
TimePoint now = TimePoint::clock::now();
|
||||
|
||||
REQUIRE(now >= start + sleepDuration);
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(CoroutineFixture, "Coro::SleepUntil delays coroutine", "[Coroutine][Sleep]")
|
||||
{
|
||||
Seconds sleepDuration = 1s;
|
||||
|
||||
TimePoint expiry = TimePoint::clock::now() + sleepDuration;
|
||||
|
||||
co_await Trinity::Coro::SleepUntil(expiry);
|
||||
|
||||
TimePoint now = TimePoint::clock::now();
|
||||
|
||||
REQUIRE(now >= expiry);
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(CoroutineFixture, "Coro::AllOf starts all awaitables at the same time and finishes when all are done", "[Coroutine][AllOf]")
|
||||
{
|
||||
bool startedFlags[3] = { };
|
||||
|
||||
auto testCoro = [&]<typename T>(std::size_t flagIndex, std::type_identity<T>) -> Trinity::Coro::Awaitable<T>
|
||||
{
|
||||
startedFlags[flagIndex] = true;
|
||||
co_await Trinity::Coro::SleepFor(100ms);
|
||||
REQUIRE(advstd::ranges::contains(startedFlags, false) == false);
|
||||
|
||||
if constexpr (std::is_same_v<T, void>)
|
||||
co_return;
|
||||
else
|
||||
co_return static_cast<T>(flagIndex);
|
||||
};
|
||||
|
||||
Trinity::Coro::Awaitable<std::size_t> coro1 = testCoro(0, std::type_identity<std::size_t>());
|
||||
Trinity::Coro::Awaitable<std::size_t> coro2 = testCoro(1, std::type_identity<std::size_t>());
|
||||
Trinity::Coro::Awaitable<void> coro3 = testCoro(2, std::type_identity<void>());
|
||||
|
||||
auto allOf = co_await Trinity::Coro::AllOf(coro1, std::move(coro2), coro3);
|
||||
|
||||
using AllResultOfTuple = decltype(allOf);
|
||||
STATIC_REQUIRE(std::tuple_size_v<AllResultOfTuple> == 2);
|
||||
STATIC_REQUIRE(std::is_lvalue_reference_v<std::tuple_element_t<0, AllResultOfTuple>>);
|
||||
STATIC_REQUIRE(std::is_reference_v<std::tuple_element_t<1, AllResultOfTuple>> == false);
|
||||
REQUIRE(std::get<0>(allOf) == 0);
|
||||
REQUIRE(std::get<1>(allOf) == 1);
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(CoroutineFixture, "Coro::AllOf rethrows exception from one of its nested awaitables", "[Coroutine][AllOf]")
|
||||
{
|
||||
bool startedFlags[3] = { };
|
||||
|
||||
auto testCoro = [&]<typename T>(std::size_t flagIndex, std::type_identity<T>, bool throws = false) -> Trinity::Coro::Awaitable<T>
|
||||
{
|
||||
startedFlags[flagIndex] = true;
|
||||
co_await Trinity::Coro::SleepFor(100ms);
|
||||
REQUIRE(advstd::ranges::contains(startedFlags, false) == false);
|
||||
|
||||
if (throws)
|
||||
throw std::runtime_error("Controlled failure");
|
||||
|
||||
if constexpr (std::is_same_v<T, void>)
|
||||
co_return;
|
||||
else
|
||||
co_return flagIndex;
|
||||
};
|
||||
|
||||
Trinity::Coro::Awaitable<std::size_t> coro1 = testCoro(0, std::type_identity<std::size_t>());
|
||||
Trinity::Coro::Awaitable<std::size_t> coro2 = testCoro(1, std::type_identity<std::size_t>());
|
||||
Trinity::Coro::Awaitable<void> coro3 = testCoro(2, std::type_identity<void>(), true);
|
||||
|
||||
REQUIRE_THROWS_WITH(co_await Trinity::Coro::AllOf(coro1, std::move(coro2), coro3), Catch::Matchers::ContainsSubstring("Controlled failure"));
|
||||
}
|
||||
Reference in New Issue
Block a user