diff --git a/component/fakeip/pool.go b/component/fakeip/pool.go index 1d39b112..fa7fba05 100644 --- a/component/fakeip/pool.go +++ b/component/fakeip/pool.go @@ -21,7 +21,7 @@ type store interface { CloneTo(store) } -// Pool is a implementation about fake ip generator without storage +// Pool is an implementation about fake ip generator without storage type Pool struct { max uint32 min uint32 @@ -99,21 +99,21 @@ func (p *Pool) CloneFrom(o *Pool) { func (p *Pool) get(host string) net.IP { current := p.offset for { + ip := uintToIP(p.min + p.offset) + if !p.store.Exist(ip) { + break + } + p.offset = (p.offset + 1) % (p.max - p.min) // Avoid infinite loops if p.offset == current { p.offset = (p.offset + 1) % (p.max - p.min) - ip := uintToIP(p.min + p.offset - 1) + ip := uintToIP(p.min + p.offset) p.store.DelByIP(ip) break } - - ip := uintToIP(p.min + p.offset - 1) - if !p.store.Exist(ip) { - break - } } - ip := uintToIP(p.min + p.offset - 1) + ip := uintToIP(p.min + p.offset) p.store.PutByIP(ip, host) return ip } diff --git a/component/fakeip/pool_test.go b/component/fakeip/pool_test.go index 7e161d03..e5b7ec5d 100644 --- a/component/fakeip/pool_test.go +++ b/component/fakeip/pool_test.go @@ -1,7 +1,6 @@ package fakeip import ( - "fmt" "net" "os" "testing" @@ -106,15 +105,13 @@ func TestPool_CycleUsed(t *testing.T) { defer os.Remove(tempfile) for _, pool := range pools { - foo := pool.Lookup("foo.com") - bar := pool.Lookup("bar.com") - for i := 0; i < 3; i++ { - pool.Lookup(fmt.Sprintf("%d.com", i)) - } - baz := pool.Lookup("baz.com") - next := pool.Lookup("foo.com") - assert.True(t, foo.Equal(baz)) - assert.True(t, next.Equal(bar)) + assert.Equal(t, net.IP{192, 168, 0, 2}, pool.Lookup("2.com")) + assert.Equal(t, net.IP{192, 168, 0, 3}, pool.Lookup("3.com")) + assert.Equal(t, net.IP{192, 168, 0, 4}, pool.Lookup("4.com")) + assert.Equal(t, net.IP{192, 168, 0, 5}, pool.Lookup("5.com")) + assert.Equal(t, net.IP{192, 168, 0, 6}, pool.Lookup("6.com")) + assert.Equal(t, net.IP{192, 168, 0, 2}, pool.Lookup("12.com")) + assert.Equal(t, net.IP{192, 168, 0, 3}, pool.Lookup("3.com")) } }