diff --git a/netutil/ipmap.go b/netutil/ipmap.go index 08704f0..b62e966 100644 --- a/netutil/ipmap.go +++ b/netutil/ipmap.go @@ -39,6 +39,20 @@ func NewIPMap(hint int) (m *IPMap) { } } +// Clear clears the map but retains its allocated storage. Calling Clear on +// a nil *IPMap has no effect, just like calling delete in a loop on an empty +// map doesn't. +func (m *IPMap) Clear() { + if m == nil { + return + } + + // This is optimized, see https://github.com/golang/go/issues/20138. + for k := range m.m { + delete(m.m, k) + } +} + // Del deletes ip from the map. Calling Del on a nil *IPMap has no effect, just // like delete on an empty map doesn't. func (m *IPMap) Del(ip net.IP) { diff --git a/netutil/ipmap_test.go b/netutil/ipmap_test.go index 23be3ce..ab5b538 100644 --- a/netutil/ipmap_test.go +++ b/netutil/ipmap_test.go @@ -53,6 +53,10 @@ func TestIPMap(t *testing.T) { t.Run("nil", func(t *testing.T) { var m *netutil.IPMap + assert.NotPanics(t, func() { + m.Clear() + }) + assert.NotPanics(t, func() { m.Del(ip4) m.Del(ip6)