2015-10-06 17:24:49 +00:00
|
|
|
package broadcaster
|
2014-07-30 15:16:10 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
2015-10-06 17:24:49 +00:00
|
|
|
// Unbuffered accumulates multiple io.WriteCloser by stream.
|
|
|
|
type Unbuffered struct {
|
2015-08-21 12:51:28 +00:00
|
|
|
mu sync.Mutex
|
|
|
|
writers []io.WriteCloser
|
2014-07-30 15:16:10 +00:00
|
|
|
}
|
|
|
|
|
2015-10-06 17:24:49 +00:00
|
|
|
// Add adds new io.WriteCloser.
|
|
|
|
func (w *Unbuffered) Add(writer io.WriteCloser) {
|
2015-08-21 12:51:28 +00:00
|
|
|
w.mu.Lock()
|
|
|
|
w.writers = append(w.writers, writer)
|
|
|
|
w.mu.Unlock()
|
2014-07-30 15:16:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Write writes bytes to all writers. Failed writers will be evicted during
|
|
|
|
// this call.
|
2015-10-06 17:24:49 +00:00
|
|
|
func (w *Unbuffered) Write(p []byte) (n int, err error) {
|
2015-08-21 12:51:28 +00:00
|
|
|
w.mu.Lock()
|
|
|
|
var evict []int
|
|
|
|
for i, sw := range w.writers {
|
2015-07-09 16:00:03 +00:00
|
|
|
if n, err := sw.Write(p); err != nil || n != len(p) {
|
|
|
|
// On error, evict the writer
|
2015-08-21 12:51:28 +00:00
|
|
|
evict = append(evict, i)
|
2015-03-30 21:30:01 +00:00
|
|
|
}
|
2014-07-30 15:16:10 +00:00
|
|
|
}
|
2015-08-21 12:51:28 +00:00
|
|
|
for n, i := range evict {
|
|
|
|
w.writers = append(w.writers[:i-n], w.writers[i-n+1:]...)
|
|
|
|
}
|
|
|
|
w.mu.Unlock()
|
2014-07-30 15:16:10 +00:00
|
|
|
return len(p), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Clean closes and removes all writers. Last non-eol-terminated part of data
|
|
|
|
// will be saved.
|
2015-10-06 17:24:49 +00:00
|
|
|
func (w *Unbuffered) Clean() error {
|
2015-08-21 12:51:28 +00:00
|
|
|
w.mu.Lock()
|
|
|
|
for _, sw := range w.writers {
|
|
|
|
sw.Close()
|
2014-07-30 15:16:10 +00:00
|
|
|
}
|
2015-08-21 12:51:28 +00:00
|
|
|
w.writers = nil
|
|
|
|
w.mu.Unlock()
|
2014-07-30 15:16:10 +00:00
|
|
|
return nil
|
|
|
|
}
|