adding apicontext package to add IsNotDone check for context to infinite for loops

This commit is contained in:
William Dillon 2025-05-07 20:09:40 -04:00
parent 3306e3b5ce
commit 712f4cff69
3 changed files with 12 additions and 5 deletions

View File

@ -4,6 +4,8 @@ import (
"context"
"errors"
"sync"
"code.wmdillon.com/GoApi/apicontext"
)
var (
@ -16,7 +18,7 @@ func ProcessChannelThroughFunction[T any](ctx context.Context, c <-chan T, workC
results := make(chan T, cap(c))
go func() {
defer close(results)
for {
for apicontext.ContextIsNotDone(ctx) {
if t, err := TrySelectFromChannel(ctx, c); err != nil {
return
} else if err := TryAddToChannel(ctx, results, workCallback(t)); err != nil {
@ -39,7 +41,7 @@ func MergeChannelsWithContext[T any](ctx context.Context, bufferSize int, channe
wg.Add(1)
go func() {
defer wg.Done()
for {
for apicontext.ContextIsNotDone(ctx) {
if t, err := TrySelectFromChannel(ctx, c); err != nil {
return
} else if err := TryAddToChannel(ctx, results, t); err != nil {
@ -84,7 +86,7 @@ func TrySelectFromChannel[T any](ctx context.Context, c <-chan T) (T, error) {
func ChannelToSliceWithContext[T any](ctx context.Context, c <-chan T) []T {
results := make([]T, 0, cap(c))
loop:
for {
for apicontext.ContextIsNotDone(ctx) {
if t, err := TrySelectFromChannel(ctx, c); err != nil {
break loop
} else {
@ -122,7 +124,7 @@ func CopyChannelWithContext[T any](ctx context.Context, c <-chan T) (a, b <-chan
close(left)
close(right)
}()
for {
for apicontext.ContextIsNotDone(ctx) {
if t, err := TrySelectFromChannel(ctx, c); err != nil {
return
} else if err := TryAddToChannel(ctx, left, t); err != nil {

5
go.mod
View File

@ -2,4 +2,7 @@ module code.wmdillon.com/GoApi/channels
go 1.24.3
require code.wmdillon.com/GoApi/set v0.0.0-20250507164311-92b5c07cfe79 // indirect
require (
code.wmdillon.com/GoApi/apicontext v0.0.0-20250508000638-2147470e1341 // indirect
code.wmdillon.com/GoApi/set v0.0.0-20250507164311-92b5c07cfe79 // indirect
)

2
go.sum
View File

@ -1,2 +1,4 @@
code.wmdillon.com/GoApi/apicontext v0.0.0-20250508000638-2147470e1341 h1:PIbSiQXjNGyWpm9NhiqDtzm6frjl1xdYTthwEqZOiJ4=
code.wmdillon.com/GoApi/apicontext v0.0.0-20250508000638-2147470e1341/go.mod h1:+wC4Wh9l7xhVEL2thuHMT+IDEqXw+s4DpHDO89Nev60=
code.wmdillon.com/GoApi/set v0.0.0-20250507164311-92b5c07cfe79 h1:wZ8m8hNBcbloOf8eMXBLQx3XVoUscp9eXa0LUK2geOM=
code.wmdillon.com/GoApi/set v0.0.0-20250507164311-92b5c07cfe79/go.mod h1:plTVmwcnxECX/pgFB1kWemxqPrWm/K/8wV6TWDgWlLY=