Skip to content

Commit a647495

Browse files
authored
Handle NaN - fixes #13 (#68)
1 parent 3a40da8 commit a647495

2 files changed

Lines changed: 25 additions & 0 deletions

File tree

sets.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,12 @@ func (s Set[T]) Clone() Set[T] {
4646
}
4747

4848
// Add items to the set.
49+
// Add and thus its callers will panic() if NaN is passed in.
4950
func (s Set[T]) Add(item ...T) {
5051
for _, i := range item {
52+
if i != i { //nolint:gocritic // on purpose to find NaN
53+
panic("NaN is not allowed in sets")
54+
}
5155
s[i] = struct{}{}
5256
}
5357
}

sets_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ package sets_test
55

66
import (
77
"encoding/json"
8+
"math"
89
"math/rand"
910
"testing"
1011

@@ -182,6 +183,26 @@ func TestGenerate(t *testing.T) {
182183
}, "should match triplets")
183184
}
184185

186+
func TestNotNaNFloats(t *testing.T) {
187+
// Normal floats:
188+
setA := sets.New(math.Pi, math.Pi, math.Pi, math.E)
189+
assert.Equal(t, 2, setA.Len())
190+
assert.True(t, setA.Has(math.Pi))
191+
assert.True(t, setA.Has(math.E))
192+
// order
193+
assert.Equal(t, []float64{math.E, math.Pi}, sets.Sort(setA))
194+
}
195+
196+
func TestNaNFloats(t *testing.T) {
197+
defer func() {
198+
if r := recover(); r == nil {
199+
t.Errorf("The code did not panic")
200+
}
201+
}()
202+
_ = sets.New(math.NaN(), math.NaN(), math.NaN(), math.NaN())
203+
t.Fatal("Shouldn't be reached, should have paniced")
204+
}
205+
185206
func TestBadJson(t *testing.T) {
186207
jsonStr := `[
187208
"a,b",

0 commit comments

Comments
 (0)