Skip to content

Commit

Permalink
Handle NaN - fixes #13
Browse files Browse the repository at this point in the history
  • Loading branch information
ldemailly committed Jun 4, 2024
1 parent 3a40da8 commit ea84dc0
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
4 changes: 4 additions & 0 deletions sets.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,12 @@ func (s Set[T]) Clone() Set[T] {
}

// Add items to the set.
// Add and thus its callers will panic() if NaN is passed in.
func (s Set[T]) Add(item ...T) {
for _, i := range item {
if i != i { //nolint:gocritic // on purpose to find NaN
panic("NaN is not allowed in sets")
}
s[i] = struct{}{}
}
}
Expand Down
21 changes: 21 additions & 0 deletions sets_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package sets_test

import (
"encoding/json"
"math"
"math/rand"
"testing"

Expand Down Expand Up @@ -182,6 +183,26 @@ func TestGenerate(t *testing.T) {
}, "should match triplets")
}

func TestNotNaNFloats(t *testing.T) {
// Normal floats:
setA := sets.New(math.Pi, math.Pi, math.Pi, math.E)
assert.Equal(t, 2, setA.Len())
assert.True(t, setA.Has(math.Pi))
assert.True(t, setA.Has(math.E))
// order
assert.Equal(t, []float64{math.E, math.Pi}, sets.Sort(setA))
}

func TestNaNFloats(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Errorf("The code did not panic")
}
}()
_ = sets.New(math.NaN(), math.NaN(), math.NaN(), math.NaN())
t.Fatal("Shouldn't be reached, should have paniced")
}

func TestBadJson(t *testing.T) {
jsonStr := `[
"a,b",
Expand Down

0 comments on commit ea84dc0

Please sign in to comment.