goext/syncext/channel.go
Mike Schwörer 64f2cd7219
Some checks failed
Build Docker and Deploy / Run goext test-suite (push) Has been cancelled
v0.0.591 implement namespaced PubSub Broker in dataext
2025-07-16 12:44:55 +02:00

56 lines
1003 B
Go

package syncext
import (
"golang.org/x/net/context"
"time"
)
// https://gobyexample.com/non-blocking-channel-operations
// https://gobyexample.com/timeouts
// https://groups.google.com/g/golang-nuts/c/Oth9CmJPoqo
func ReadChannelWithTimeout[T any](c chan T, timeout time.Duration) (T, bool) {
select {
case msg := <-c:
return msg, true
case <-time.After(timeout):
return *new(T), false
}
}
func WriteChannelWithTimeout[T any](c chan T, msg T, timeout time.Duration) bool {
select {
case c <- msg:
return true
case <-time.After(timeout):
return false
}
}
func WriteChannelWithContext[T any](ctx context.Context, c chan T, msg T) error {
select {
case c <- msg:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func ReadNonBlocking[T any](c chan T) (T, bool) {
select {
case msg := <-c:
return msg, true
default:
return *new(T), false
}
}
func WriteNonBlocking[T any](c chan T, msg T) bool {
select {
case c <- msg:
return true
default:
return false
}
}