feat(channel): adding lo.SafeClose()

This commit is contained in:
Samuel Berthe
2022-11-15 18:40:54 +01:00
parent a133373ee3
commit 9b13a52d5c
2 changed files with 24 additions and 0 deletions
+14
View File
@@ -304,3 +304,17 @@ func FanOut[T any](count int, channelsBufferCap int, upstream <-chan T) []<-chan
return channelsToReadOnly(downstreams)
}
// SafeClose protects against double-close panic.
// Returns true on first close, only.
// May be equivalent to calling `sync.Once{}.Do(func() { close(ch) })`.`
func SafeClose[T any](ch chan<- T) (justClosed bool) {
defer func() {
if recover() != nil {
justClosed = false
}
}()
close(ch) // may panic
return true
}
+10
View File
@@ -388,3 +388,13 @@ func TestFanOut(t *testing.T) {
is.Equal(0, msg)
}
}
func TestSafeClose(t *testing.T) {
t.Parallel()
is := assert.New(t)
ch := make(chan int)
is.True(SafeClose(ch))
is.False(SafeClose(ch))
}