From 6a304b875aa84166f8baa7aa123421cd8e01001e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Schw=C3=B6rer?= Date: Wed, 30 Nov 2022 23:52:19 +0100 Subject: [PATCH] v0.0.28 --- syncext/channel.go | 43 +++++++++++++++++++++++++++++++++++++------ 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/syncext/channel.go b/syncext/channel.go index f76b9bd..e64a7cb 100644 --- a/syncext/channel.go +++ b/syncext/channel.go @@ -1,14 +1,45 @@ package syncext -import "time" +import ( + "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) { - afterCh := time.After(timeout) select { - case rv := <-c: - return rv, true - case <-afterCh: + 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 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 + } }