Skip to content

Commit

Permalink
fix issue #112: add new functions IsEmpty and IsTimeout
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilsk committed Oct 11, 2017
1 parent 49ec74b commit 6db8734
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 9 deletions.
19 changes: 12 additions & 7 deletions semaphore.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {}

Expand All @@ -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
}
Expand Down Expand Up @@ -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
}
}
4 changes: 2 additions & 2 deletions semaphore_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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)
}
}
Expand Down

0 comments on commit 6db8734

Please sign in to comment.