repeater.Listeners()

This commit is contained in:
Neale Pickett 2020-04-12 20:46:51 -06:00
parent cdf3869454
commit 7492e9d5bb
3 changed files with 15 additions and 10 deletions

View File

@ -79,7 +79,7 @@ func (b Book) loop() {
break
}
repeater.Part(event.w)
if len(repeater.subscribers) == 0 {
if repeater.Listeners() == 0 {
delete(b.entries, event.name)
}
case sendEvent:

View File

@ -4,32 +4,37 @@ import (
"io"
)
// A Repeater is just a list of Writers.
type Repeater struct {
subscribers []io.Writer
writers []io.Writer
}
func NewRepeater() *Repeater {
return &Repeater{
subscribers: make([]io.Writer, 0, 20),
writers: make([]io.Writer, 0, 20),
}
}
func (r *Repeater) Join(w io.Writer) {
r.subscribers = append(r.subscribers, w)
r.writers = append(r.writers, w)
}
func (r *Repeater) Part(w io.Writer) {
for i, s := range r.subscribers {
for i, s := range r.writers {
if s == w {
nsubs := len(r.subscribers)
r.subscribers[i] = r.subscribers[nsubs-1]
r.subscribers = r.subscribers[:nsubs-1]
nsubs := len(r.writers)
r.writers[i] = r.writers[nsubs-1]
r.writers = r.writers[:nsubs-1]
}
}
}
func (r *Repeater) Send(p []byte) {
for _, s := range r.subscribers {
for _, s := range r.writers {
s.Write(p)
}
}
func (r *Repeater) Listeners() int {
return len(r.writers)
}

View File

@ -10,7 +10,7 @@ func TestRepeater(t *testing.T) {
buf1 := bytes.NewBufferString("buf1")
r.Join(buf1)
if len(r.subscribers) != 1 {
if r.Listeners() != 1 {
t.Error("Joining did nothing")
}
r.Send([]byte("moo"))