Debian Codegraph @

diode/internal/diodes/waiter.go

raw
1 package diodes
2
3 import (
4 "context"
5 "sync"
6 )
7
8 // Waiter will use a conditional mutex to alert the reader to when data is
9 // available.
10 type Waiter struct {
11 Diode
12 mu sync.Mutex
13 c *sync.Cond
14 ctx context.Context
15 }
16
17 // WaiterConfigOption can be used to setup the waiter.
18 type WaiterConfigOption func(*Waiter)
19
20 // WithWaiterContext sets the context to cancel any retrieval (Next()). It
21 // will not change any results for adding data (Set()). Default is
22 // context.Background().
23 func WithWaiterContext(ctx context.Context) WaiterConfigOption {
24 return func(c *Waiter) {
25 c.ctx = ctx
26 }
27 }
28
29 // NewWaiter returns a new Waiter that wraps the given diode.
30 func NewWaiter(d Diode, opts ...WaiterConfigOption) *Waiter {
31 w := new(Waiter)
32 w.Diode = d
33 w.c = sync.NewCond(&w.mu)
34 w.ctx = context.Background()
35
36 for _, opt := range opts {
37 opt(w)
38 }
39
40 go func() {
41 <-w.ctx.Done()
42
43 // Mutex is strictly necessary here to avoid a race in Next() (between
44 // w.isDone() and w.c.Wait()) and w.c.Broadcast() here.
45 w.mu.Lock()
46 w.c.Broadcast()
47 w.mu.Unlock()
48 }()
49
50 return w
51 }
52
53 // Set invokes the wrapped diode's Set with the given data and uses Broadcast
54 // to wake up any readers.
55 func (w *Waiter) Set(data GenericDataType) {
56 w.Diode.Set(data)
57 w.c.Broadcast()
58 }
59
60 // Next returns the next data point on the wrapped diode. If there is not any
61 // new data, it will Wait for set to be called or the context to be done.
62 // If the context is done, then nil will be returned.
63 func (w *Waiter) Next() GenericDataType {
64 w.mu.Lock()
65 defer w.mu.Unlock()
66
67 for {
68 data, ok := w.Diode.TryNext()
69 if !ok {
70 if w.isDone() {
71 return nil
72 }
73
74 w.c.Wait()
75 continue
76 }
77 return data
78 }
79 }
80
81 func (w *Waiter) isDone() bool {
82 select {
83 case <-w.ctx.Done():
84 return true
85 default:
86 return false
87 }
88 }