diff --git a/lib/events/events.go b/lib/events/events.go index 21dbcc0ae..07c6ccbe6 100644 --- a/lib/events/events.go +++ b/lib/events/events.go @@ -105,7 +105,7 @@ func (t EventType) MarshalText() ([]byte, error) { const BufferSize = 64 type Logger struct { - subs map[int]*Subscription + subs []*Subscription nextID int mutex sync.Mutex } @@ -119,7 +119,6 @@ type Event struct { type Subscription struct { mask EventType - id int events chan Event timeout *time.Timer } @@ -133,7 +132,6 @@ var ( func NewLogger() *Logger { return &Logger{ - subs: make(map[int]*Subscription), mutex: sync.NewMutex(), } } @@ -143,13 +141,13 @@ func (l *Logger) Log(t EventType, data interface{}) { if debug { dl.Debugln("log", l.nextID, t.String(), data) } + l.nextID++ e := Event{ ID: l.nextID, Time: time.Now(), Type: t, Data: data, } - l.nextID++ for _, s := range l.subs { if s.mask&t != 0 { select { @@ -169,12 +167,10 @@ func (l *Logger) Subscribe(mask EventType) *Subscription { } s := &Subscription{ mask: mask, - id: l.nextID, events: make(chan Event, BufferSize), timeout: time.NewTimer(0), } - l.nextID++ - l.subs[s.id] = s + l.subs = append(l.subs, s) l.mutex.Unlock() return s } @@ -184,7 +180,15 @@ func (l *Logger) Unsubscribe(s *Subscription) { if debug { dl.Debugln("unsubscribe") } - delete(l.subs, s.id) + for i, ss := range l.subs { + if s == ss { + last := len(l.subs) - 1 + l.subs[i] = l.subs[last] + l.subs[last] = nil + l.subs = l.subs[:last] + break + } + } close(s.events) l.mutex.Unlock() } diff --git a/lib/events/events_test.go b/lib/events/events_test.go index 2f91dafea..8b194b746 100644 --- a/lib/events/events_test.go +++ b/lib/events/events_test.go @@ -134,6 +134,7 @@ func TestIDs(t *testing.T) { s := l.Subscribe(events.AllEvents) defer l.Unsubscribe(s) l.Log(events.DeviceConnected, "foo") + _ = l.Subscribe(events.AllEvents) l.Log(events.DeviceConnected, "bar") ev, err := s.Poll(timeout) @@ -152,8 +153,8 @@ func TestIDs(t *testing.T) { if ev.Data.(string) != "bar" { t.Fatal("Incorrect event:", ev) } - if !(ev.ID > id) { - t.Fatalf("ID not incremented (%d !> %d)", ev.ID, id) + if ev.ID != id+1 { + t.Fatalf("ID not incremented (%d != %d)", ev.ID, id+1) } }