File: watcher.go

package info (click to toggle)
golang-github-protonmail-gluon 0.17.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 16,020 kB
  • sloc: sh: 55; makefile: 5
file content (47 lines) | stat: -rw-r--r-- 856 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package watcher

import (
	"reflect"

	"github.com/ProtonMail/gluon/async"
)

type Watcher[T any] struct {
	types   map[reflect.Type]struct{}
	eventCh *async.QueuedChannel[T]
}

func New[T any](panicHandler async.PanicHandler, ofType ...T) *Watcher[T] {
	types := make(map[reflect.Type]struct{}, len(ofType))

	for _, t := range ofType {
		types[reflect.TypeOf(t)] = struct{}{}
	}

	return &Watcher[T]{
		types:   types,
		eventCh: async.NewQueuedChannel[T](1, 1, panicHandler),
	}
}

func (w *Watcher[T]) IsWatching(event T) bool {
	if len(w.types) == 0 {
		return true
	}

	_, ok := w.types[reflect.TypeOf(event)]

	return ok
}

func (w *Watcher[T]) GetChannel() <-chan T {
	return w.eventCh.GetChannel()
}

func (w *Watcher[T]) Send(event T) bool {
	return w.eventCh.Enqueue(event)
}

func (w *Watcher[T]) Close() {
	w.eventCh.CloseAndDiscardQueued()
}