From cd726560d846a31011d014c366ab6f4c964a8e45 Mon Sep 17 00:00:00 2001 From: Mikkel Krautz Date: Sat, 14 May 2011 00:09:51 +0200 Subject: [PATCH] Skip session ID 0 in grumble/sessionpool. --- pkg/sessionpool/sessionpool.go | 21 +++++++++++---------- pkg/sessionpool/sessionpool_test.go | 20 ++++++++++---------- 2 files changed, 21 insertions(+), 20 deletions(-) diff --git a/pkg/sessionpool/sessionpool.go b/pkg/sessionpool/sessionpool.go index cba63ca..a0091b7 100644 --- a/pkg/sessionpool/sessionpool.go +++ b/pkg/sessionpool/sessionpool.go @@ -16,7 +16,7 @@ type SessionPool struct { mutex sync.Mutex used map[uint32]bool unused []uint32 - next uint32 + cur uint32 } // Create a new SessionPool container. @@ -34,7 +34,7 @@ func New() (pool *SessionPool) { // the program will panic. // panic. func (pool *SessionPool) EnableUseTracking() { - if len(pool.unused) != 0 || pool.next != 0 { + if len(pool.unused) != 0 || pool.cur != 0 { panic("Attempt to enable use tracking on an existing SessionPool.") } pool.used = make(map[uint32]bool) @@ -61,17 +61,18 @@ func (pool *SessionPool) Get() (id uint32) { return } - // Check for session pool depletion. Note that this depletion - // check makes MaxUint32 an invalid next value, and thus limits - // the session pool to 2**32-2 distinct sessions. - if pool.next == math.MaxUint32 { + // Check for depletion. If cur is MaxUint32, + // there aren't any session IDs left, since the + // increment below would overflow us back to 0. + if pool.cur == math.MaxUint32 { panic("SessionPool depleted") } - // Return the current 'next' value and increment it - // for next time we're here. - id = pool.next - pool.next += 1 + // Increment the next session id and return it. + // Note: By incrementing and *then* returning, we skip 0. + // This is deliberate, as 0 is an invalid session ID in Mumble. + pool.cur += 1 + id = pool.cur return } diff --git a/pkg/sessionpool/sessionpool_test.go b/pkg/sessionpool/sessionpool_test.go index 48e1bd9..1f0b2c0 100644 --- a/pkg/sessionpool/sessionpool_test.go +++ b/pkg/sessionpool/sessionpool_test.go @@ -8,20 +8,20 @@ import ( func TestReclaim(t *testing.T) { pool := New() id := pool.Get() - if id != 0 { - t.Errorf("Got %v, expected 0 (first time)", id) + if id != 1 { + t.Errorf("Got %v, expected 1 (first time)", id) } - pool.Reclaim(0) - - id = pool.Get() - if id != 0 { - t.Errorf("Got %v, expected 0 (second time)", id) - } + pool.Reclaim(1) id = pool.Get() if id != 1 { - t.Errorf("Got %v, expected 1", id) + t.Errorf("Got %v, expected 1 (second time)", id) + } + + id = pool.Get() + if id != 2 { + t.Errorf("Got %v, expected 2", id) } } @@ -33,7 +33,7 @@ func TestDepletion(t *testing.T) { } }() pool := New() - pool.next = math.MaxUint32 + pool.cur = math.MaxUint32 pool.Get() }