vail/repeater.go

41 lines
630 B
Go
Raw Normal View History

package main
import (
"io"
)
2020-04-12 20:46:51 -06:00
// A Repeater is just a list of Writers.
type Repeater struct {
2020-04-12 20:46:51 -06:00
writers []io.Writer
}
func NewRepeater() *Repeater {
return &Repeater{
2020-04-12 20:46:51 -06:00
writers: make([]io.Writer, 0, 20),
}
}
func (r *Repeater) Join(w io.Writer) {
2020-04-12 20:46:51 -06:00
r.writers = append(r.writers, w)
}
func (r *Repeater) Part(w io.Writer) {
2020-04-12 20:46:51 -06:00
for i, s := range r.writers {
2020-04-12 20:40:52 -06:00
if s == w {
2020-04-12 20:46:51 -06:00
nsubs := len(r.writers)
r.writers[i] = r.writers[nsubs-1]
r.writers = r.writers[:nsubs-1]
2020-04-12 20:40:52 -06:00
}
}
}
func (r *Repeater) Send(p []byte) {
2020-04-12 20:46:51 -06:00
for _, s := range r.writers {
2020-04-12 20:40:52 -06:00
s.Write(p)
}
}
2020-04-12 20:46:51 -06:00
func (r *Repeater) Listeners() int {
return len(r.writers)
}