github.com/luckypickle/go-ethereum-vet@v1.14.2/event/filter/filter.go (about)

     1  // Copyright 2014 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum 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 go-ethereum 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 go-ethereum 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 (f *Filters) Start() {
    49  	go f.loop()
    50  }
    51  
    52  func (f *Filters) Stop() {
    53  	close(f.quit)
    54  }
    55  
    56  func (f *Filters) Notify(filter Filter, data interface{}) {
    57  	f.ch <- FilterEvent{filter, data}
    58  }
    59  
    60  func (f *Filters) Install(watcher Filter) int {
    61  	f.watchers[f.id] = watcher
    62  	f.id++
    63  
    64  	return f.id - 1
    65  }
    66  
    67  func (f *Filters) Uninstall(id int) {
    68  	delete(f.watchers, id)
    69  }
    70  
    71  func (f *Filters) loop() {
    72  out:
    73  	for {
    74  		select {
    75  		case <-f.quit:
    76  			break out
    77  		case event := <-f.ch:
    78  			for _, watcher := range f.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 (f *Filters) Match(a, b Filter) bool {
    90  	return reflect.TypeOf(a) == reflect.TypeOf(b) && a.Compare(b)
    91  }
    92  
    93  func (f *Filters) Get(i int) Filter {
    94  	return f.watchers[i]
    95  }