From f86b4db3cede8354f1ce277cdbea087ea5046057 Mon Sep 17 00:00:00 2001 From: Josh Bleecher Snyder Date: Thu, 28 Jan 2021 14:23:22 -0800 Subject: [PATCH] add IPSet.Equal Signed-off-by: Josh Bleecher Snyder --- ipset.go | 15 +++++++++++++++ ipset_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/ipset.go b/ipset.go index 2b0151e..3dabf00 100644 --- a/ipset.go +++ b/ipset.go @@ -279,3 +279,18 @@ func (s *IPSet) ContainsFunc() (contains func(IP) bool) { return rv[i].contains(ip) } } + +// Equal reports whether s contains exactly the same IPs as t. +func (s *IPSet) Equal(t *IPSet) bool { + sr := s.Ranges() + tr := t.Ranges() + if len(sr) != len(tr) { + return false + } + for i := range sr { + if sr[i] != tr[i] { + return false + } + } + return true +} diff --git a/ipset_test.go b/ipset_test.go index deff67a..ff5250e 100644 --- a/ipset_test.go +++ b/ipset_test.go @@ -624,3 +624,35 @@ func TestPointLess(t *testing.T) { } } + +func TestIPSetEqual(t *testing.T) { + a := new(IPSet) + b := new(IPSet) + + assertEqual := func(want bool) { + t.Helper() + if got := a.Equal(b); got != want { + t.Errorf("%v.Equal(%v) = %v want %v", a, b, got, want) + } + } + + a.Add(MustParseIP("1.1.1.0")) + a.Add(MustParseIP("1.1.1.1")) + a.Add(MustParseIP("1.1.1.2")) + b.AddPrefix(MustParseIPPrefix("1.1.1.0/31")) + b.Add(MustParseIP("1.1.1.2")) + assertEqual(true) + + a.RemoveSet(a) + assertEqual(false) + b.RemoveSet(b) + assertEqual(true) + + a.Add(MustParseIP("1.1.1.0")) + a.Add(MustParseIP("1.1.1.1")) + a.Add(MustParseIP("1.1.1.2")) + + b.AddPrefix(MustParseIPPrefix("1.1.1.0/30")) + b.Remove(MustParseIP("1.1.1.3")) + assertEqual(true) +}