summaryrefslogtreecommitdiff
path: root/pkg/sync/chan.go
diff options
context:
space:
mode:
authorDJ O'Leary <dijitol@proton.me>2026-07-14 02:48:22 +0200
committerDJ O'Leary <dijitol@proton.me>2026-07-14 02:48:22 +0200
commit03878d151215277d948b0a1ce31c65d9305d3aa4 (patch)
treeac3136fa6f85f85c54a74e7acbd7c83c325bd594 /pkg/sync/chan.go
parent783ab544c03991419a7bf7ac033bdf5d34ff9cc3 (diff)
refactor(pkg): move packages that can be imported by others to pkg directory
Diffstat (limited to 'pkg/sync/chan.go')
-rw-r--r--pkg/sync/chan.go48
1 files changed, 48 insertions, 0 deletions
diff --git a/pkg/sync/chan.go b/pkg/sync/chan.go
new file mode 100644
index 0000000..91501f9
--- /dev/null
+++ b/pkg/sync/chan.go
@@ -0,0 +1,48 @@
+package sync
+
+import "context"
+
+func OrDone[T any](ctx context.Context, in <-chan T) <-chan T {
+ if in == nil {
+ // we only expect this to happen during development
+ panic("in-channel is nil")
+ }
+
+ out := make(chan T)
+ go func() {
+ defer close(out)
+ for {
+ v, ok := CancelOrReceive(ctx, in)
+ if !ok {
+ return
+ }
+
+ if !CancelOrSend(ctx, out, v) {
+ return
+ }
+ }
+ }()
+ return out
+}
+
+// CancelOrReceive is trying to solve the same problem as OrDone but does so
+// without an extra goroutine.
+func CancelOrReceive[T any](ctx context.Context, in <-chan T) (v T, ok bool) {
+ select {
+ case <-ctx.Done():
+ return // <zero value of type T>, false
+ case v, ok = <-in:
+ return // v, ok
+ }
+}
+
+// CancelOrSend is a helper function to simplify sending values to channels
+// while keeping the context in mind.
+func CancelOrSend[T any](ctx context.Context, out chan<- T, val T) bool {
+ select {
+ case <-ctx.Done():
+ return false
+ case out <- val:
+ return true
+ }
+}