From 20ec211d1b222943c81d5946c81a60a17d2296b1 Mon Sep 17 00:00:00 2001 From: Kyle Roth Date: Sat, 27 Mar 2021 13:12:59 -0700 Subject: [PATCH] allow limit to equal zero 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.) --- semaphore.go | 8 ++++---- semaphore_test.go | 19 +++---------------- 2 files changed, 7 insertions(+), 20 deletions(-) diff --git a/semaphore.go b/semaphore.go index 5fc3df1..ab82d56 100644 --- a/semaphore.go +++ b/semaphore.go @@ -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{ @@ -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) diff --git a/semaphore_test.go b/semaphore_test.go index ef0b4fc..a45ef30 100644 --- a/semaphore_test.go +++ b/semaphore_test.go @@ -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() { @@ -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) {