From c5df41b3fc0bcaf40d65d0c1081eae9d0dae817f Mon Sep 17 00:00:00 2001 From: jizhuozhi Date: Sun, 4 Aug 2024 01:43:57 +0800 Subject: [PATCH] feat: add `Done` to test state --- future.go | 8 ++++++++ future_test.go | 11 +++++++++++ 2 files changed, 19 insertions(+) diff --git a/future.go b/future.go index 8ae2a09..d361480 100644 --- a/future.go +++ b/future.go @@ -142,6 +142,10 @@ func (p *Promise[T]) Future() *Future[T] { return &Future[T]{state: &p.state} } +func (p *Promise[T]) Done() bool { + return isDone(atomic.LoadUint64(&p.state.state)) +} + func (f *Future[T]) Get() (T, error) { return f.state.get() } @@ -158,6 +162,10 @@ func (f *Future[T]) Subscribe(cb func(val T, err error)) { f.state.subscribe(cb) } +func (f *Future[T]) Done() bool { + return isDone(atomic.LoadUint64(&f.state.state)) +} + func isFree(st uint64) bool { return ((st & maskState) >> 32) == stateFree } diff --git a/future_test.go b/future_test.go index a536865..baad42f 100644 --- a/future_test.go +++ b/future_test.go @@ -74,6 +74,17 @@ func TestFutureSubscribe(t *testing.T) { assert.Equal(t, val2, 3) } +func TestPromiseFutureDone(t *testing.T) { + p := NewPromise[int]() + f := p.Future() + assert.False(t, p.Done()) + assert.False(t, f.Done()) + + p.Set(1, nil) + assert.True(t, p.Done()) + assert.True(t, f.Done()) +} + func Benchmark(b *testing.B) { b.Run("Promise", func(b *testing.B) { for i := 0; i < b.N; i++ {