feat add Promise
Some checks failed
linux-x64-gcc / linux-gcc (Release) (push) Failing after 1m24s
linux-x64-gcc / linux-gcc (Debug) (push) Failing after 54s

This commit is contained in:
tqcq 2024-03-23 18:18:15 +08:00
parent 95845b14dc
commit c0a2b73d0d
5 changed files with 1411 additions and 9 deletions

View File

@ -124,6 +124,7 @@ if(SLED_BUILD_TESTS)
src/any_test.cc src/any_test.cc
src/filesystem/path_test.cc src/filesystem/path_test.cc
src/futures/future_test.cc src/futures/future_test.cc
src/futures/promise_test.cc
src/log/fmt_test.cc src/log/fmt_test.cc
# src/profiling/profiling_test.cc # src/profiling/profiling_test.cc
src/strings/base64_test.cc src/strings/base64_test.cc

File diff suppressed because it is too large Load Diff

View File

@ -134,11 +134,13 @@ public:
template<typename Predicate> template<typename Predicate>
inline bool WaitFor(MutexLock &lock, TimeDelta timeout, Predicate &&pred) inline bool WaitFor(MutexLock &lock, TimeDelta timeout, Predicate &&pred)
{ {
if (timeout.ns() < 0) { return pred(); }
if (timeout == TimeDelta::PlusInfinity()) { if (timeout == TimeDelta::PlusInfinity()) {
cv_.wait(lock.lock_, std::forward<Predicate>(pred)); cv_.wait(lock.lock_, std::forward<Predicate>(pred));
return true; return true;
} else { } else {
return cv_.wait_for(lock.lock_, std::chrono::milliseconds(timeout.ms()), std::forward<Predicate>(pred)); return cv_.wait_for(lock.lock_, std::chrono::microseconds(timeout.us()), std::forward<Predicate>(pred));
} }
} }

View File

@ -43,6 +43,12 @@ public:
return FromValue(value); return FromValue(value);
} }
template<typename T, typename V>
inline TimeDelta(std::chrono::duration<T, V> duration)
{
*this = Micros(std::chrono::duration_cast<std::chrono::microseconds>(duration));
}
TimeDelta() = delete; TimeDelta() = delete;
template<typename T = int64_t> template<typename T = int64_t>
@ -69,15 +75,9 @@ public:
return ToMultiple<1000, T>(); return ToMultiple<1000, T>();
} }
constexpr int64_t seconds_or(int64_t fallback_value) const constexpr int64_t seconds_or(int64_t fallback_value) const { return ToFractionOr<1000000>(fallback_value); }
{
return ToFractionOr<1000000>(fallback_value);
}
constexpr int64_t ms_or(int64_t fallback_value) const constexpr int64_t ms_or(int64_t fallback_value) const { return ToFractionOr<1000>(fallback_value); }
{
return ToFractionOr<1000>(fallback_value);
}
constexpr int64_t us_or(int64_t fallback_value) const { return ToValueOr(fallback_value); } constexpr int64_t us_or(int64_t fallback_value) const { return ToValueOr(fallback_value); }

View File

@ -0,0 +1,21 @@
#include <gtest/gtest.h>
#include <sled/futures/promise.h>
TEST(Promise, Basic)
{
auto p = sled::Promise<int>();
auto v = p.Then([](int v) {
EXPECT_EQ(v, 1);
return v + 10;
})
.Tap([](int v) {
EXPECT_EQ(v, 11);
// no effect
return v + 1;
})
.Then([](int v) {
EXPECT_EQ(v, 11);
return v + 10;
});
p.Resolve(1);
}