]> Sergey Matveev's repositories - btrtrc.git/blob - internal/chansync/set-once.go
Apply next request state asynchronously
[btrtrc.git] / internal / chansync / set-once.go
1 package chansync
2
3 import "sync"
4
5 // SetOnce is a boolean value that can only be flipped from false to true.
6 type SetOnce struct {
7         ch        chan struct{}
8         initOnce  sync.Once
9         closeOnce sync.Once
10 }
11
12 // Returns a channel that is closed when the event is flagged.
13 func (me *SetOnce) Done() Done {
14         me.init()
15         return me.ch
16 }
17
18 func (me *SetOnce) init() {
19         me.initOnce.Do(func() {
20                 me.ch = make(chan struct{})
21         })
22 }
23
24 // Set only returns true the first time it is called.
25 func (me *SetOnce) Set() (first bool) {
26         me.closeOnce.Do(func() {
27                 me.init()
28                 first = true
29                 close(me.ch)
30         })
31         return
32 }
33
34 func (me *SetOnce) IsSet() bool {
35         me.init()
36         select {
37         case <-me.ch:
38                 return true
39         default:
40                 return false
41         }
42 }