Skip to content

Commit 4fa0b49

Browse files
committed
Minor improvements for implicit errgroup initialization
Should be coverage friendly
1 parent a5b84a6 commit 4fa0b49

File tree

1 file changed

+15
-16
lines changed

1 file changed

+15
-16
lines changed

internal/errgroup/errgroup.go

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -30,21 +30,15 @@ func WithContext(ctx context.Context) (*Group, context.Context) {
3030
// Go runs the provided f function in a dedicated goroutine and waits for its
3131
// completion or for the parent context cancellation.
3232
func (g *Group) Go(f func() error) {
33-
if g.grp == nil {
34-
g.grp = &errgroup.Group{}
35-
}
36-
g.grp.Go(g.wrap(f))
33+
g.getErrGroup().Go(g.wrap(f))
3734
}
3835

3936
// Wait blocks until all function calls from the Go method have returned, then
4037
// returns the first non-nil error (if any) from them.
4138
// If the error group was created via WithContext then the Wait returns error
4239
// of cancelled parent context prior any functions calls complete.
4340
func (g *Group) Wait() error {
44-
if g.grp == nil {
45-
g.grp = &errgroup.Group{}
46-
}
47-
return g.grp.Wait()
41+
return g.getErrGroup().Wait()
4842
}
4943

5044
// SetLimit limits the number of active goroutines in this group to at most n.
@@ -55,21 +49,15 @@ func (g *Group) Wait() error {
5549
//
5650
// The limit must not be modified while any goroutines in the group are active.
5751
func (g *Group) SetLimit(n int) {
58-
if g.grp == nil {
59-
g.grp = &errgroup.Group{}
60-
}
61-
g.grp.SetLimit(n)
52+
g.getErrGroup().SetLimit(n)
6253
}
6354

6455
// TryGo calls the given function in a new goroutine only if the number of
6556
// active goroutines in the group is currently below the configured limit.
6657
//
6758
// The return value reports whether the goroutine was started.
6859
func (g *Group) TryGo(f func() error) bool {
69-
if g.grp == nil {
70-
g.grp = &errgroup.Group{}
71-
}
72-
return g.grp.TryGo(g.wrap(f))
60+
return g.getErrGroup().TryGo(g.wrap(f))
7361
}
7462

7563
func (g *Group) wrap(f func() error) func() error {
@@ -106,3 +94,14 @@ func (g *Group) wrap(f func() error) func() error {
10694
}
10795
}
10896
}
97+
98+
// The getErrGroup returns actual x/sync/errgroup.Group.
99+
// If the group is not allocated it would implicitly allocate it.
100+
// Thats allows the internal/errgroup.Group be fully
101+
// compatible to x/sync/errgroup.Group
102+
func (g *Group) getErrGroup() *errgroup.Group {
103+
if g.grp == nil {
104+
g.grp = &errgroup.Group{}
105+
}
106+
return g.grp
107+
}

0 commit comments

Comments
 (0)