Skip to content

Commit 795ffda

Browse files
committed
fix(coderd/util/maps): ignore zero values in Subset
1 parent 700a453 commit 795ffda

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

coderd/util/maps/maps.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,14 @@ import (
88

99
// Subset returns true if all the keys of a are present
1010
// in b and have the same values.
11+
// If the corresponding value of a[k] is the zero value in
12+
// b, Subset will skip comparing that value.
13+
// This allows checking for the presence of map keys.
1114
func Subset[T, U comparable](a, b map[T]U) bool {
15+
var uz U
1216
for ka, va := range a {
13-
if vb, ok := b[ka]; !ok || va != vb {
17+
ignoreZeroValue := va == uz
18+
if vb, ok := b[ka]; !ok || (!ignoreZeroValue && va != vb) {
1419
return false
1520
}
1621
}

coderd/util/maps/maps_test.go

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,9 @@ func TestSubset(t *testing.T) {
1111
t.Parallel()
1212

1313
for idx, tc := range []struct {
14-
a map[string]string
15-
b map[string]string
14+
a map[string]string
15+
b map[string]string
16+
// expected value from Subset
1617
expected bool
1718
}{
1819
{
@@ -50,6 +51,24 @@ func TestSubset(t *testing.T) {
5051
b: map[string]string{"a": "1", "b": "3"},
5152
expected: false,
5253
},
54+
// Zero value
55+
{
56+
a: map[string]string{"a": "1", "b": ""},
57+
b: map[string]string{"a": "1", "b": "3"},
58+
expected: true,
59+
},
60+
// Zero value, but the other way round
61+
{
62+
a: map[string]string{"a": "1", "b": "3"},
63+
b: map[string]string{"a": "1", "b": ""},
64+
expected: false,
65+
},
66+
// Both zero values
67+
{
68+
a: map[string]string{"a": "1", "b": ""},
69+
b: map[string]string{"a": "1", "b": ""},
70+
expected: true,
71+
},
5372
} {
5473
tc := tc
5574
t.Run("#"+strconv.Itoa(idx), func(t *testing.T) {

0 commit comments

Comments
 (0)