Skip to content

Commit

Permalink
feat: try_wait<>() -> expected<>{}
Browse files Browse the repository at this point in the history
  • Loading branch information
yulon committed Sep 6, 2023
1 parent c8c6e48 commit b6313d8
Showing 1 changed file with 15 additions and 11 deletions.
26 changes: 15 additions & 11 deletions include/rua/sync/wait.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

#include "await.hpp"

#include "../optional.hpp"
#include "../error.hpp"
#include "../thread/dozer.hpp"
#include "../time/tick.hpp"

Expand Down Expand Up @@ -39,8 +39,12 @@ inline Result operator*(Awaitable &&awaitable) {

} // namespace await_operators

RUA_CVAR strv_error err_waiting_timeout("waiting timeout");

template <typename Awaitable, typename Result = await_result_t<Awaitable &&>>
inline enable_if_t<!std::is_void<Result>::value, optional<Result>>
inline enable_if_t<
!std::is_void<Result>::value,
expected<unwarp_expected_t<Result>>>
try_wait(Awaitable &&awaitable, duration timeout = 0) {
if (timeout == duration_max()) {
return wait(std::forward<Awaitable>(awaitable));
Expand All @@ -51,7 +55,7 @@ try_wait(Awaitable &&awaitable, duration timeout = 0) {
return awaiter.await_resume();
}
if (!timeout) {
return nullopt;
return err_waiting_timeout;
}

dozer dzr;
Expand All @@ -74,24 +78,24 @@ try_wait(Awaitable &&awaitable, duration timeout = 0) {
break;
}
}
return nullopt;
return err_waiting_timeout;
}

template <typename Awaitable, typename Result = await_result_t<Awaitable &&>>
inline enable_if_t<std::is_void<Result>::value, bool>
inline enable_if_t<std::is_void<Result>::value, expected<Result>>
try_wait(Awaitable &&awaitable, duration timeout = 0) {
if (timeout == duration_max()) {
wait(std::forward<Awaitable>(awaitable));
return true;
return meet_expected;
}

auto &&awaiter = make_awaiter(std::forward<Awaitable>(awaitable));
if (awaiter.await_ready()) {
awaiter.await_resume();
return true;
return meet_expected;
}
if (!timeout) {
return false;
return err_waiting_timeout;
}

dozer dzr;
Expand All @@ -102,21 +106,21 @@ try_wait(Awaitable &&awaitable, duration timeout = 0) {
wkr_sp->wake();
})) {
awaiter.await_resume();
return true;
return meet_expected;
}

auto end_ti = tick() + timeout;
for (;;) {
auto ok = dzr.doze(timeout);
if (ok) {
awaiter.await_resume();
return true;
return meet_expected;
}
if (!ok || assign(timeout, end_ti - tick()) <= 0) {
break;
}
}
return false;
return err_waiting_timeout;
}

} // namespace rua
Expand Down

0 comments on commit b6313d8

Please sign in to comment.