From 7492e9d5bb1c17eca4eafd44fc802d868c3cd4f6 Mon Sep 17 00:00:00 2001 From: Neale Pickett Date: Sun, 12 Apr 2020 20:46:51 -0600 Subject: [PATCH] repeater.Listeners() --- book.go | 2 +- repeater.go | 21 +++++++++++++-------- repeater_test.go | 2 +- 3 files changed, 15 insertions(+), 10 deletions(-) diff --git a/book.go b/book.go index 6e7f287..dfb587e 100644 --- a/book.go +++ b/book.go @@ -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: diff --git a/repeater.go b/repeater.go index 1f9003e..c0366f5 100644 --- a/repeater.go +++ b/repeater.go @@ -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) +} diff --git a/repeater_test.go b/repeater_test.go index 4b6a8f9..0f8b5be 100644 --- a/repeater_test.go +++ b/repeater_test.go @@ -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"))