Skip to content
This repository has been archived by the owner on Oct 4, 2019. It is now read-only.

Commit

Permalink
event: panic for duplicate type
Browse files Browse the repository at this point in the history
  • Loading branch information
fjl committed Oct 16, 2014
1 parent ade9809 commit fa84e50
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
6 changes: 5 additions & 1 deletion event/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package event

import (
"errors"
"fmt"
"reflect"
"sync"
)
Expand Down Expand Up @@ -40,6 +41,7 @@ var ErrMuxClosed = errors.New("event: mux closed")
func (mux *TypeMux) Subscribe(types ...interface{}) Subscription {
sub := newsub(mux)
mux.mutex.Lock()
defer mux.mutex.Unlock()
if mux.stopped {
close(sub.postC)
} else {
Expand All @@ -49,13 +51,15 @@ func (mux *TypeMux) Subscribe(types ...interface{}) Subscription {
for _, t := range types {
rtyp := reflect.TypeOf(t)
oldsubs := mux.subm[rtyp]
if find(oldsubs, sub) != -1 {
panic(fmt.Sprintf("event: duplicate type %s in Subscribe", rtyp))
}
subs := make([]*muxsub, len(oldsubs)+1)
copy(subs, oldsubs)
subs[len(oldsubs)] = sub
mux.subm[rtyp] = subs
}
}
mux.mutex.Unlock()
return sub
}

Expand Down
15 changes: 15 additions & 0 deletions event/event_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,21 @@ func TestUnsubscribeUnblockPost(t *testing.T) {
}
}

func TestSubscribeDuplicateType(t *testing.T) {
mux := new(TypeMux)
expected := "event: duplicate type event.testEvent in Subscribe"

defer func() {
err := recover()
if err == nil {
t.Errorf("Subscribe didn't panic for duplicate type")
} else if err != expected {
t.Errorf("panic mismatch: got %#v, expected %#v", err, expected)
}
}()
mux.Subscribe(testEvent(1), testEvent(2))
}

func TestMuxConcurrent(t *testing.T) {
rand.Seed(time.Now().Unix())
mux := new(TypeMux)
Expand Down

0 comments on commit fa84e50

Please sign in to comment.