2020-04-12 16:37:58 -06:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
2020-04-12 20:46:51 -06:00
|
|
|
// A Repeater is just a list of Writers.
|
2020-04-12 16:37:58 -06:00
|
|
|
type Repeater struct {
|
2020-04-12 20:46:51 -06:00
|
|
|
writers []io.Writer
|
2020-04-12 16:37:58 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewRepeater() *Repeater {
|
|
|
|
return &Repeater{
|
2020-04-12 20:46:51 -06:00
|
|
|
writers: make([]io.Writer, 0, 20),
|
2020-04-12 16:37:58 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-12 17:30:00 -06:00
|
|
|
func (r *Repeater) Join(w io.Writer) {
|
2020-04-12 20:46:51 -06:00
|
|
|
r.writers = append(r.writers, w)
|
2020-04-12 17:30:00 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
}
|
|
|
|
}
|
2020-04-12 17:30:00 -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 16:37:58 -06:00
|
|
|
}
|
|
|
|
}
|
2020-04-12 20:46:51 -06:00
|
|
|
|
|
|
|
func (r *Repeater) Listeners() int {
|
|
|
|
return len(r.writers)
|
|
|
|
}
|