Skip to content

Commit b622f5f

Browse files
author
nickg
committed
Close #7 - add Set.New(size) constuctor
1 parent 3f8dc29 commit b622f5f

File tree

2 files changed

+31
-21
lines changed

2 files changed

+31
-21
lines changed

set.go

Lines changed: 30 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,17 @@ import (
55
)
66

77
// Set defines a unique set of IPv4 addresses using a simple []uint32
8+
//
9+
// Since Set is a alias of []unit32, one can use
10+
// `make(Set, length, capacity)` or use the NewSet constructor
11+
//
812
type Set []uint32
913

14+
// NewSet creates a Set with a given initial capacity.
15+
func NewSet(capacity int) Set {
16+
return make(Set, 0, capacity)
17+
}
18+
1019
// Len returns a length, part of the Sort.Interface
1120
func (m Set) Len() int {
1221
return len(m)
@@ -76,26 +85,6 @@ func (m *Set) AddAll(ipv4dots []string) bool {
7685
return true
7786
}
7887

79-
func (m *Set) sort() {
80-
in := *m
81-
sort.Sort(in)
82-
83-
// inplace sort
84-
// https://github.com/golang/go/wiki/SliceTricks#in-place-deduplicate-comparable
85-
j := 0
86-
for i := 1; i < len(in); i++ {
87-
if in[j] == in[i] {
88-
continue
89-
}
90-
j++
91-
// preserve the original data
92-
// in[i], in[j] = in[j], in[i]
93-
// only set what is required
94-
in[j] = in[i]
95-
}
96-
in = in[:j+1]
97-
}
98-
9988
// Valid return true if the internal storage is in sorted form and unique
10089
func (m Set) Valid() bool {
10190
if len(m) == 0 {
@@ -111,10 +100,31 @@ func (m Set) Valid() bool {
111100
return true
112101
}
113102

103+
// ToDots returns the IP set as a list of dotted-notation strings
114104
func (m Set) ToDots() []string {
115105
out := make([]string, len(m))
116106
for i, val := range m {
117107
out[i] = ToDots(val)
118108
}
119109
return out
120110
}
111+
112+
func (m *Set) sort() {
113+
in := *m
114+
sort.Sort(in)
115+
116+
// inplace sort
117+
// https://github.com/golang/go/wiki/SliceTricks#in-place-deduplicate-comparable
118+
j := 0
119+
for i := 1; i < len(in); i++ {
120+
if in[j] == in[i] {
121+
continue
122+
}
123+
j++
124+
// preserve the original data
125+
// in[i], in[j] = in[j], in[i]
126+
// only set what is required
127+
in[j] = in[i]
128+
}
129+
in = in[:j+1]
130+
}

set_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ func TestAdd(t *testing.T) {
8686
}
8787

8888
func TestAddAll(t *testing.T) {
89-
s := Set{}
89+
s := NewSet(2)
9090
s.AddAll([]string{"127.0.0.1", "10.0.0.1"})
9191
if !s.Valid() {
9292
t.Fatalf("AddAll is not valid")

0 commit comments

Comments
 (0)