diff --git a/set.go b/set.go index 082ab28..a6471e4 100644 --- a/set.go +++ b/set.go @@ -5,8 +5,17 @@ import ( ) // Set defines a unique set of IPv4 addresses using a simple []uint32 +// +// Since Set is a alias of []unit32, one can use +// `make(Set, length, capacity)` or use the NewSet constructor +// type Set []uint32 +// NewSet creates a Set with a given initial capacity. +func NewSet(capacity int) Set { + return make(Set, 0, capacity) +} + // Len returns a length, part of the Sort.Interface func (m Set) Len() int { return len(m) @@ -76,26 +85,6 @@ func (m *Set) AddAll(ipv4dots []string) bool { return true } -func (m *Set) sort() { - in := *m - sort.Sort(in) - - // inplace sort - // https://github.com/golang/go/wiki/SliceTricks#in-place-deduplicate-comparable - j := 0 - for i := 1; i < len(in); i++ { - if in[j] == in[i] { - continue - } - j++ - // preserve the original data - // in[i], in[j] = in[j], in[i] - // only set what is required - in[j] = in[i] - } - in = in[:j+1] -} - // Valid return true if the internal storage is in sorted form and unique func (m Set) Valid() bool { if len(m) == 0 { @@ -111,6 +100,7 @@ func (m Set) Valid() bool { return true } +// ToDots returns the IP set as a list of dotted-notation strings func (m Set) ToDots() []string { out := make([]string, len(m)) for i, val := range m { @@ -118,3 +108,23 @@ func (m Set) ToDots() []string { } return out } + +func (m *Set) sort() { + in := *m + sort.Sort(in) + + // inplace sort + // https://github.com/golang/go/wiki/SliceTricks#in-place-deduplicate-comparable + j := 0 + for i := 1; i < len(in); i++ { + if in[j] == in[i] { + continue + } + j++ + // preserve the original data + // in[i], in[j] = in[j], in[i] + // only set what is required + in[j] = in[i] + } + in = in[:j+1] +} diff --git a/set_test.go b/set_test.go index ba57150..968e3ae 100644 --- a/set_test.go +++ b/set_test.go @@ -86,7 +86,7 @@ func TestAdd(t *testing.T) { } func TestAddAll(t *testing.T) { - s := Set{} + s := NewSet(2) s.AddAll([]string{"127.0.0.1", "10.0.0.1"}) if !s.Valid() { t.Fatalf("AddAll is not valid")