#define MS_CLASS "DepLibUV"
#include "DepLibUV.hpp"
#include "Logger.hpp"
#include <cstdlib>
thread_local uv_loop_t* DepLibUV::loop{ nullptr };
inline static void onClose(uv_handle_t* handle)
{
delete handle;
}
inline static void onWalk(uv_handle_t* handle, void* arg)
{
MS_ERROR_STD(
"alive UV handle found (this shouldn't happen) [type:%d, active:%d, closing:%d, has_ref:%d]",
handle->type,
uv_is_active(handle),
uv_is_closing(handle),
uv_has_ref(handle));
if (!uv_is_closing(handle))
uv_close(handle, onClose);
}
void DepLibUV::ClassInit()
{
DepLibUV::loop = new uv_loop_t;
int err = uv_loop_init(DepLibUV::loop);
if (err != 0)
MS_ABORT("libuv loop initialization failed");
}
void DepLibUV::ClassDestroy()
{
MS_TRACE();
int err;
uv_stop(DepLibUV::loop);
uv_walk(DepLibUV::loop, onWalk, nullptr);
while (true)
{
err = uv_loop_close(DepLibUV::loop);
if (err != UV_EBUSY)
break;
uv_run(DepLibUV::loop, UV_RUN_NOWAIT);
}
if (err != 0)
MS_ERROR_STD("failed to close libuv loop: %s", uv_err_name(err));
delete DepLibUV::loop;
}
void DepLibUV::PrintVersion()
{
MS_TRACE();
MS_DEBUG_TAG(info, "libuv version: \"%s\"", uv_version_string());
}
void DepLibUV::RunLoop()
{
MS_TRACE();
MS_ASSERT(DepLibUV::loop != nullptr, "loop unset");
int ret = uv_run(DepLibUV::loop, UV_RUN_DEFAULT);
MS_ASSERT(ret == 0, "uv_run() returned %s", uv_err_name(ret));
}