-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
10f68fb
commit 47c3fb5
Showing
5 changed files
with
356 additions
and
154 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
package xrun | ||
|
||
import ( | ||
"context" | ||
"sync/atomic" | ||
) | ||
|
||
// SignalStarted signals that the component has started. | ||
func SignalStarted(ctx context.Context) { | ||
if n, ok := ctx.Value(ctxKeyNotify).(*notifyCtx); ok { | ||
n.start() | ||
} | ||
} | ||
|
||
type ctxKey int | ||
|
||
const ( | ||
ctxKeyNotify ctxKey = iota | ||
) | ||
|
||
type notifyCtx struct { | ||
parent context.Context | ||
_started atomic.Bool | ||
ch chan struct{} | ||
} | ||
|
||
func newNotifyCtx(parent context.Context) context.Context { | ||
return context.WithValue(parent, ctxKeyNotify, ¬ifyCtx{ | ||
parent: parent, | ||
ch: make(chan struct{}, 1), | ||
}) | ||
} | ||
|
||
func (n *notifyCtx) started() <-chan struct{} { return n.ch } | ||
|
||
func (n *notifyCtx) start() { | ||
if n._started.CompareAndSwap(false, true) { | ||
close(n.ch) | ||
} | ||
} | ||
|
||
func started(ctx context.Context) <-chan struct{} { | ||
if n, ok := ctx.Value(ctxKeyNotify).(*notifyCtx); ok { | ||
return n.started() | ||
} | ||
|
||
return closedCh() | ||
} | ||
|
||
func closedCh() <-chan struct{} { | ||
ch := make(chan struct{}, 1) | ||
defer close(ch) | ||
return ch | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
package xrun | ||
|
||
import ( | ||
"context" | ||
"testing" | ||
) | ||
|
||
func Test_started_with_no_notifyCtx(t *testing.T) { | ||
<-started(context.TODO()) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.