wtclient: make addr iterator panic safe

Ensure that calling Next twice in a row without first calling Reset is
safe when the iterator is at the end of its list. Also alter the
towerListIterator to call Reset after hitting an error on Next.
This commit is contained in:
Elle Mouton 2023-03-30 11:49:58 +02:00
parent 1047514515
commit 9e4c8dd509
No known key found for this signature in database
GPG Key ID: D7D916376026F177
3 changed files with 6 additions and 7 deletions

View File

@ -162,6 +162,10 @@ func (a *addressIterator) next(lock bool) (net.Addr, error) {
a.mu.Lock()
defer a.mu.Unlock()
if a.currentTopAddr == nil {
return nil, ErrAddressesExhausted
}
// Set the next candidate to the subsequent element.
a.currentTopAddr = a.currentTopAddr.Next()

View File

@ -217,15 +217,9 @@ func TestAddrIterator(t *testing.T) {
require.False(t, iter.HasLocked())
})
t.Run("calling Next twice without Reset panics", func(t *testing.T) {
t.Run("calling Next twice without Reset is safe", func(t *testing.T) {
t.Parallel()
// This defer-function asserts that a panic does occur.
defer func() {
r := recover()
require.NotNilf(t, r, "the code did not panic")
}()
// Initialise the iterator with addr1.
iter, err := newAddressIterator(addr1)
require.NoError(t, err)

View File

@ -145,6 +145,7 @@ func (t *towerListIterator) AddCandidate(candidate *Tower) {
for {
next, err := candidate.Addresses.Next()
if err != nil {
candidate.Addresses.Reset()
break
}