diff --git a/semaphore.go b/semaphore.go index eff80e0..120f627 100644 --- a/semaphore.go +++ b/semaphore.go @@ -56,6 +56,16 @@ func New(capacity int) Semaphore { return make(semaphore, capacity) } +// IsEmpty checks if passed error is related to call Release on empty semaphore. +func IsEmpty(err error) bool { + return err == errEmpty +} + +// IsTimeout checks if passed error is related to call Acquire on full semaphore. +func IsTimeout(err error) bool { + return err == errTimeout +} + var ( nothing ReleaseFunc = func() {} @@ -68,7 +78,8 @@ type semaphore chan struct{} func (sem semaphore) Acquire(deadline <-chan struct{}) (ReleaseFunc, error) { select { case sem <- struct{}{}: - return releaser(sem), nil + //nolint: gas + return func() { _ = sem.Release() }, nil case <-deadline: return nothing, errTimeout } @@ -101,9 +112,3 @@ func (sem semaphore) Signal(deadline <-chan struct{}) <-chan ReleaseFunc { }() return ch } - -func releaser(releaser Releaser) ReleaseFunc { - return func() { - _ = releaser.Release() //nolint: gas - } -} diff --git a/semaphore_test.go b/semaphore_test.go index 0a3e60c..422eda0 100644 --- a/semaphore_test.go +++ b/semaphore_test.go @@ -23,7 +23,7 @@ func TestSemaphore_Acquire_Timeout(t *testing.T) { } { sem := semaphore.New(0) release, err := sem.Acquire(semaphore.WithTimeout(tc.timeout)) - if err.Error() != expected { + if !semaphore.IsTimeout(err) { t.Errorf("an unexpected error in test case %q. expected: %s; obtained: %v", tc.name, expected, err) } _ = release.Release() @@ -66,7 +66,7 @@ func TestSemaphore_Occupied_Linearity(t *testing.T) { func TestSemaphore_Release_TryToGetDeadLock(t *testing.T) { sem := semaphore.New(0) - if err, expected := sem.Release(), "semaphore is empty"; err.Error() != expected { + if err, expected := sem.Release(), "semaphore is empty"; !semaphore.IsEmpty(err) { t.Errorf("an unexpected error. expected: %s; obtained: %v", expected, err) } }