aboutsummaryrefslogtreecommitdiff
path: root/pkg/coroutine
diff options
context:
space:
mode:
authorGabriel Arakaki Giovanini <mail@gabrielgio.me>2023-06-24 00:34:57 +0200
committerGabriel Arakaki Giovanini <mail@gabrielgio.me>2023-06-25 15:18:12 +0200
commit57b41ad766b3c4505672c12f058f10c7a132dd5b (patch)
tree80aea95babc8f740e86dadc7469236bdffc78c26 /pkg/coroutine
parentd5261d7f121985f13f9d19e9efd5c2ae3d4b5609 (diff)
downloadlens-57b41ad766b3c4505672c12f058f10c7a132dd5b.tar.gz
lens-57b41ad766b3c4505672c12f058f10c7a132dd5b.tar.bz2
lens-57b41ad766b3c4505672c12f058f10c7a132dd5b.zip
feat: Remove unnecessary function
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)
+}