filter.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. // Package filter implements event filters.
  17. package filter
  18. import "reflect"
  19. type Filter interface {
  20. Compare(Filter) bool
  21. Trigger(data interface{})
  22. }
  23. type FilterEvent struct {
  24. filter Filter
  25. data interface{}
  26. }
  27. type Filters struct {
  28. id int
  29. watchers map[int]Filter
  30. ch chan FilterEvent
  31. quit chan struct{}
  32. }
  33. func New() *Filters {
  34. return &Filters{
  35. ch: make(chan FilterEvent),
  36. watchers: make(map[int]Filter),
  37. quit: make(chan struct{}),
  38. }
  39. }
  40. func (f *Filters) Start() {
  41. go f.loop()
  42. }
  43. func (f *Filters) Stop() {
  44. close(f.quit)
  45. }
  46. func (f *Filters) Notify(filter Filter, data interface{}) {
  47. f.ch <- FilterEvent{filter, data}
  48. }
  49. func (f *Filters) Install(watcher Filter) int {
  50. f.watchers[f.id] = watcher
  51. f.id++
  52. return f.id - 1
  53. }
  54. func (f *Filters) Uninstall(id int) {
  55. delete(f.watchers, id)
  56. }
  57. func (f *Filters) loop() {
  58. out:
  59. for {
  60. select {
  61. case <-f.quit:
  62. break out
  63. case event := <-f.ch:
  64. for _, watcher := range f.watchers {
  65. if reflect.TypeOf(watcher) == reflect.TypeOf(event.filter) {
  66. if watcher.Compare(event.filter) {
  67. watcher.Trigger(event.data)
  68. }
  69. }
  70. }
  71. }
  72. }
  73. }
  74. func (f *Filters) Match(a, b Filter) bool {
  75. return reflect.TypeOf(a) == reflect.TypeOf(b) && a.Compare(b)
  76. }
  77. func (f *Filters) Get(i int) Filter {
  78. return f.watchers[i]
  79. }