channel/chan_io.go

33 lines
907 B
Go
Raw Permalink Normal View History

2022-02-09 12:10:02 +01:00
package channel
import (
"fmt"
"io"
"time"
)
// WriteInto writes all given values into the channel ch.
// Is is a shorthand for Forward(ch, AsChan(values...))
func WriteInto[T any](ch chan<- T, values ...T) {
2022-02-09 12:17:49 +01:00
Forward(ch, Of(values...))
2022-02-09 12:10:02 +01:00
}
// WriteIntoDelayed writes all given values into the channel ch.
// It sleeps after every write for the given amount of time.
// It is a shorthand for Forward(ch, AsChanDelayed(time, values...))
func WriteIntoDelayed[T any](ch chan<- T, delay time.Duration, values ...T) {
2022-02-09 12:17:49 +01:00
Forward(ch, OfDelayed(delay, values...))
2022-02-09 12:10:02 +01:00
}
// WriteIntoWriter reads all values from ch and writes them via fmt.Fprintln to all writers
func WriteIntoWriter[T any](ch <-chan T, writers ...io.Writer) {
2022-03-30 15:49:24 +02:00
w := io.MultiWriter(writers...)
2023-03-04 11:24:42 +01:00
EachSuccessive(ch, func(value T) {
2023-03-25 11:52:57 +01:00
if err, ok := any(value).(error); ok {
fmt.Fprintln(w, err.Error())
return
}
2022-03-30 15:49:24 +02:00
fmt.Fprintln(w, value)
})
2022-02-09 12:10:02 +01:00
}