Skip to content

Commit

Permalink
Close #7 - add Set.New(size) constuctor
Browse files Browse the repository at this point in the history
  • Loading branch information
nickg committed May 18, 2020
1 parent 3f8dc29 commit b622f5f
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 21 deletions.
50 changes: 30 additions & 20 deletions set.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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 {
Expand All @@ -111,10 +100,31 @@ 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 {
out[i] = ToDots(val)
}
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]
}
2 changes: 1 addition & 1 deletion set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down

0 comments on commit b622f5f

Please sign in to comment.