github.com/jonasnick/go-ethereum@v0.7.12-0.20150216215225-22176f05d387/event/filter/filter.go (about) 1 package filter 2 3 import "reflect" 4 5 type Filter interface { 6 Compare(Filter) bool 7 Trigger(data interface{}) 8 } 9 10 type FilterEvent struct { 11 filter Filter 12 data interface{} 13 } 14 15 type Filters struct { 16 id int 17 watchers map[int]Filter 18 ch chan FilterEvent 19 20 quit chan struct{} 21 } 22 23 func New() *Filters { 24 return &Filters{ 25 ch: make(chan FilterEvent), 26 watchers: make(map[int]Filter), 27 quit: make(chan struct{}), 28 } 29 } 30 31 func (self *Filters) Start() { 32 go self.loop() 33 } 34 35 func (self *Filters) Stop() { 36 close(self.quit) 37 } 38 39 func (self *Filters) Notify(filter Filter, data interface{}) { 40 self.ch <- FilterEvent{filter, data} 41 } 42 43 func (self *Filters) Install(watcher Filter) int { 44 self.watchers[self.id] = watcher 45 self.id++ 46 47 return self.id - 1 48 } 49 50 func (self *Filters) Uninstall(id int) { 51 delete(self.watchers, id) 52 } 53 54 func (self *Filters) loop() { 55 out: 56 for { 57 select { 58 case <-self.quit: 59 break out 60 case event := <-self.ch: 61 for _, watcher := range self.watchers { 62 if reflect.TypeOf(watcher) == reflect.TypeOf(event.filter) { 63 if watcher.Compare(event.filter) { 64 watcher.Trigger(event.data) 65 } 66 } 67 } 68 } 69 } 70 } 71 72 func (self *Filters) Match(a, b Filter) bool { 73 return reflect.TypeOf(a) == reflect.TypeOf(b) && a.Compare(b) 74 } 75 76 func (self *Filters) Get(i int) Filter { 77 return self.watchers[i] 78 }