Skip to content

Commit 071dce1

Browse files
committed
fix: don't sort arguments in place in SetEquals, SetEqualsInt and Set2DEquals
1 parent 5341c6b commit 071dce1

1 file changed

Lines changed: 31 additions & 21 deletions

File tree

‎util/util.go‎

Lines changed: 31 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -158,31 +158,37 @@ func SetEquals(a []string, b []string) bool {
158158
return false
159159
}
160160

161-
sort.Strings(a)
162-
sort.Strings(b)
163-
164-
for i, v := range a {
165-
if v != b[i] {
161+
count := make(map[string]int, len(a))
162+
for _, v := range a {
163+
count[v]++
164+
}
165+
for _, v := range b {
166+
count[v]--
167+
if count[v] < 0 {
166168
return false
167169
}
168170
}
171+
169172
return true
170173
}
171174

172-
// SetEquals determines whether two int sets are identical.
175+
// SetEqualsInt determines whether two int sets are identical.
173176
func SetEqualsInt(a []int, b []int) bool {
174177
if len(a) != len(b) {
175178
return false
176179
}
177180

178-
sort.Ints(a)
179-
sort.Ints(b)
180-
181-
for i, v := range a {
182-
if v != b[i] {
181+
count := make(map[int]int, len(a))
182+
for _, v := range a {
183+
count[v]++
184+
}
185+
for _, v := range b {
186+
count[v]--
187+
if count[v] < 0 {
183188
return false
184189
}
185190
}
191+
186192
return true
187193
}
188194

@@ -192,18 +198,22 @@ func Set2DEquals(a [][]string, b [][]string) bool {
192198
return false
193199
}
194200

195-
var aa []string
196-
for _, v := range a {
197-
sort.Strings(v)
198-
aa = append(aa, strings.Join(v, ", "))
199-
}
200-
var bb []string
201-
for _, v := range b {
202-
sort.Strings(v)
203-
bb = append(bb, strings.Join(v, ", "))
201+
return SetEquals(setKeys(a), setKeys(b))
202+
}
203+
204+
// setKeys maps every row to an order-independent key, without touching the row.
205+
// The fields are joined on a NUL because a policy value may contain a comma.
206+
func setKeys(rows [][]string) []string {
207+
keys := make([]string, len(rows))
208+
209+
for i, row := range rows {
210+
fields := make([]string, len(row))
211+
copy(fields, row)
212+
sort.Strings(fields)
213+
keys[i] = strings.Join(fields, "\x00")
204214
}
205215

206-
return SetEquals(aa, bb)
216+
return keys
207217
}
208218

209219
// JoinSlice joins a string and a slice into a new slice.

0 commit comments

Comments
 (0)