github.com/aquanetwork/aquachain@v1.7.8/aqua/event/filter/filter.go (about)

     1  // Copyright 2014 The aquachain Authors
     2  // This file is part of the aquachain library.
     3  //
     4  // The aquachain library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The aquachain library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the aquachain library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // Package filter implements event filters.
    18  package filter
    19  
    20  import "reflect"
    21  
    22  type Filter interface {
    23  	Compare(Filter) bool
    24  	Trigger(data interface{})
    25  }
    26  
    27  type FilterEvent struct {
    28  	filter Filter
    29  	data   interface{}
    30  }
    31  
    32  type Filters struct {
    33  	id       int
    34  	watchers map[int]Filter
    35  	ch       chan FilterEvent
    36  
    37  	quit chan struct{}
    38  }
    39  
    40  func New() *Filters {
    41  	return &Filters{
    42  		ch:       make(chan FilterEvent),
    43  		watchers: make(map[int]Filter),
    44  		quit:     make(chan struct{}),
    45  	}
    46  }
    47  
    48  func (self *Filters) Start() {
    49  	go self.loop()
    50  }
    51  
    52  func (self *Filters) Stop() {
    53  	close(self.quit)
    54  }
    55  
    56  func (self *Filters) Notify(filter Filter, data interface{}) {
    57  	self.ch <- FilterEvent{filter, data}
    58  }
    59  
    60  func (self *Filters) Install(watcher Filter) int {
    61  	self.watchers[self.id] = watcher
    62  	self.id++
    63  
    64  	return self.id - 1
    65  }
    66  
    67  func (self *Filters) Uninstall(id int) {
    68  	delete(self.watchers, id)
    69  }
    70  
    71  func (self *Filters) loop() {
    72  out:
    73  	for {
    74  		select {
    75  		case <-self.quit:
    76  			break out
    77  		case event := <-self.ch:
    78  			for _, watcher := range self.watchers {
    79  				if reflect.TypeOf(watcher) == reflect.TypeOf(event.filter) {
    80  					if watcher.Compare(event.filter) {
    81  						watcher.Trigger(event.data)
    82  					}
    83  				}
    84  			}
    85  		}
    86  	}
    87  }
    88  
    89  func (self *Filters) Match(a, b Filter) bool {
    90  	return reflect.TypeOf(a) == reflect.TypeOf(b) && a.Compare(b)
    91  }
    92  
    93  func (self *Filters) Get(i int) Filter {
    94  	return self.watchers[i]
    95  }