Skip to content

Commit

Permalink
fixing size check
Browse files Browse the repository at this point in the history
  • Loading branch information
Mzack9999 committed Apr 29, 2024
1 parent f9776e1 commit f4bcedb
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 14 deletions.
26 changes: 13 additions & 13 deletions sync/adaptivewaitgroup.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,11 @@ type AdaptiveWaitGroup struct {
mu sync.Mutex // Mutex to protect access to the Size and semaphore
}

// WithSize sets the initial size of the waitgroup ()
func WithSize(size int) AdaptiveGroupOption {
// size is 0 based
size = zeroBased(size)
return func(wg *AdaptiveWaitGroup) error {
if size < 0 {
return errors.New("size must be positive")
if err := validateSize(size); err != nil {
return err
}
sem, err := semaphore.New(int64(size))
if err != nil {
Expand All @@ -39,6 +38,13 @@ func WithSize(size int) AdaptiveGroupOption {
}
}

func validateSize(size int) error {
if size < 1 {
return errors.New("size must be at least 1")
}
return nil
}

func New(options ...AdaptiveGroupOption) (*AdaptiveWaitGroup, error) {
wg := &AdaptiveWaitGroup{}
for _, option := range options {
Expand Down Expand Up @@ -87,8 +93,9 @@ func (s *AdaptiveWaitGroup) Resize(ctx context.Context, size int) error {
s.mu.Lock()
defer s.mu.Unlock()

// size is 0 based
size = zeroBased(size)
if err := validateSize(size); err != nil {
return err
}

// Resize the semaphore with the provided context and handle any errors
if err := s.sem.Resize(ctx, int64(size)); err != nil {
Expand All @@ -101,10 +108,3 @@ func (s *AdaptiveWaitGroup) Resize(ctx context.Context, size int) error {
func (s *AdaptiveWaitGroup) Current() int {
return int(s.current.Load())
}

func zeroBased(size int) int {
if size > 1 {
size = size - 1
}
return size
}
2 changes: 1 addition & 1 deletion sync/adaptivewaitgroup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func TestThrottling(t *testing.T) {
defer swg.Done()

c.Add(1)
require.False(t, swg.Current() > 4, "not the good amount of routines spawned.", swg.Current())
require.False(t, swg.Current() > 5, "not the good amount of routines spawned.", swg.Current())
}()
}

Expand Down

0 comments on commit f4bcedb

Please sign in to comment.