From ea84dc01a1ef22fd5a1cc8684d23aaa01d46404f Mon Sep 17 00:00:00 2001 From: Laurent Demailly Date: Tue, 4 Jun 2024 10:26:48 -0700 Subject: [PATCH] Handle NaN - fixes #13 --- sets.go | 4 ++++ sets_test.go | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/sets.go b/sets.go index 83d77b2..014abb2 100644 --- a/sets.go +++ b/sets.go @@ -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{}{} } } diff --git a/sets_test.go b/sets_test.go index 1b911d5..971cc89 100644 --- a/sets_test.go +++ b/sets_test.go @@ -5,6 +5,7 @@ package sets_test import ( "encoding/json" + "math" "math/rand" "testing" @@ -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",