aboutsummaryrefslogtreecommitdiff
path: root/pkg/coroutine
diff options
context:
space:
mode:
Diffstat (limited to 'pkg/coroutine')
-rw-r--r--pkg/coroutine/coroutine.go33
-rw-r--r--pkg/coroutine/coroutine_test.go63
2 files changed, 96 insertions, 0 deletions
diff --git a/pkg/coroutine/coroutine.go b/pkg/coroutine/coroutine.go
new file mode 100644
index 0000000..96d149e
--- /dev/null
+++ b/pkg/coroutine/coroutine.go
@@ -0,0 +1,33 @@
+package coroutine
+
+import (
+ "context"
+)
+
+// WrapProcess wraps process into a go routine and make it cancelable through context
+func WrapProcess[V any](ctx context.Context, fun func() (V, error)) (V, error) {
+ c := make(chan V)
+ e := make(chan error)
+ go func() {
+ defer close(c)
+ defer close(e)
+
+ v, err := fun()
+ if err != nil {
+ e <- err
+ } else {
+ c <- v
+ }
+ }()
+
+ select {
+ case <-ctx.Done():
+ var zero V
+ return zero, ctx.Err()
+ case m := <-c:
+ return m, nil
+ case err := <-e:
+ var zero V
+ return zero, err
+ }
+}
diff --git a/pkg/coroutine/coroutine_test.go b/pkg/coroutine/coroutine_test.go
new file mode 100644
index 0000000..e876ec3
--- /dev/null
+++ b/pkg/coroutine/coroutine_test.go
@@ -0,0 +1,63 @@
+//go:build unit
+
+package coroutine
+
+import (
+ "context"
+ "errors"
+ "sync"
+ "testing"
+ "time"
+
+ "git.sr.ht/~gabrielgio/img/pkg/testkit"
+)
+
+var rError = errors.New("This is a error")
+
+func imediatReturn() (string, error) {
+ return "A string", nil
+}
+
+func imediatErrorReturn() (string, error) {
+ return "", rError
+}
+
+func haltedReturn() (string, error) {
+ time.Sleep(time.Hour)
+ return "", nil
+}
+
+func TestImediatReturn(t *testing.T) {
+ ctx := context.Background()
+ v, err := WrapProcess(ctx, imediatReturn)
+ testkit.TestError(t, "WrapProcess", nil, err)
+ testkit.TestValue(t, "WrapProcess", "A string", v)
+}
+
+func TestImediatErrorReturn(t *testing.T) {
+ ctx := context.Background()
+ v, err := WrapProcess(ctx, imediatErrorReturn)
+ testkit.TestError(t, "WrapProcess", rError, err)
+ testkit.TestValue(t, "WrapProcess", "", v)
+}
+
+func TestHaltedReturn(t *testing.T) {
+ ctx := context.Background()
+ ctx, cancel := context.WithCancel(ctx)
+
+ var (
+ err error
+ wg sync.WaitGroup
+ )
+
+ wg.Add(1)
+ go func(err *error) {
+ defer wg.Done()
+ _, *err = WrapProcess(ctx, haltedReturn)
+ }(&err)
+
+ cancel()
+ wg.Wait()
+
+ testkit.TestError(t, "WrapProcess", context.Canceled, err)
+}