Skip to content

Commit

Permalink
allow limit to equal zero
Browse files Browse the repository at this point in the history
It's reasonable for the number of resources to be set to zero. (The
limit could later be increased once resources are available, for
example.)
  • Loading branch information
kylrth committed Mar 27, 2021
1 parent ee99b20 commit 20ec211
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 20 deletions.
8 changes: 4 additions & 4 deletions semaphore.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ type semaphore struct {

// New initializes a new instance of the Semaphore, specifying the maximum number of concurrent entries.
func New(limit int) Semaphore {
if limit <= 0 {
panic("semaphore limit must be greater than 0")
if limit < 0 {
panic("semaphore limit must not be negative")
}
broadcastCh := make(chan struct{})
return &semaphore{
Expand Down Expand Up @@ -189,8 +189,8 @@ func (s *semaphore) Release(n int) int {
}

func (s *semaphore) SetLimit(limit int) {
if limit <= 0 {
panic("semaphore limit must be greater than 0")
if limit < 0 {
panic("semaphore limit must not be negative")
}
for {
state := atomic.LoadUint64(&s.state)
Expand Down
19 changes: 3 additions & 16 deletions semaphore_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,8 @@ func TestNew(t *testing.T) {
checkLimitAndCount(t, sem, 1, 0)
},
func() {
defer func() {
if recover() == nil {
t.Error("Panic expected")
}
}()
_ = New(0)
sem := New(0)
checkLimitAndCount(t, sem, 0, 0)
},
func() {
defer func() {
Expand Down Expand Up @@ -359,18 +355,9 @@ func TestSemaphore_SetLimit(t *testing.T) {

sem.SetLimit(1)
checkLimitAndCount(t, sem, 1, 0)
}

func TestSemaphore_SetLimit_zero_limit_panic_expected(t *testing.T) {
sem := New(1)
checkLimitAndCount(t, sem, 1, 0)

defer func() {
if recover() == nil {
t.Error("Panic expected")
}
}()
sem.SetLimit(0)
checkLimitAndCount(t, sem, 0, 0)
}

func TestSemaphore_SetLimit_negative_limit_panic_expected(t *testing.T) {
Expand Down

0 comments on commit 20ec211

Please sign in to comment.