Skip to content

Commit

Permalink
tpl/compare: Sort special float values as string
Browse files Browse the repository at this point in the history
When sorting strings a worng order is returned. This happens because the strings are first converted
to floating values to check whether or not they should be sorted as
floating values. When an error is returned the strings will be
handled as string literals.
No error will be returned when parsing Inf, Infinity or NaN (case insensitive) because they
will be coverted to special floating point values and therefore are
legal float values.
Now we check if the returned converted values are special floating
values and treat them as string literals.

Fixes #10389
  • Loading branch information
acclassic committed Jan 2, 2023
1 parent e754d5c commit f95fd57
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 31 deletions.
29 changes: 0 additions & 29 deletions .gitignore

This file was deleted.

7 changes: 5 additions & 2 deletions tpl/compare/compare.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package compare

import (
"fmt"
"math"
"reflect"
"strconv"
"time"
Expand Down Expand Up @@ -273,7 +274,8 @@ func (ns *Namespace) compareGetWithCollator(collator *langs.Collator, a any, b a
case reflect.String:
var err error
left, err = strconv.ParseFloat(av.String(), 64)
if err != nil {
// Check if float is a special floating value and cast value as string.
if math.IsInf(left, 0) || math.IsNaN(left) || err != nil {
str := av.String()
leftStr = &str
}
Expand All @@ -300,7 +302,8 @@ func (ns *Namespace) compareGetWithCollator(collator *langs.Collator, a any, b a
case reflect.String:
var err error
right, err = strconv.ParseFloat(bv.String(), 64)
if err != nil {
// Check if float is a special floating value and cast value as string.
if math.IsInf(right, 0) || math.IsNaN(right) || err != nil {
str := bv.String()
rightStr = &str
}
Expand Down
2 changes: 2 additions & 0 deletions tpl/compare/compare_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,8 @@ func doTestCompare(t *testing.T, tp tstCompareType, funcUnderTest func(a, b any)
{"a", "a", 0},
{"a", "b", -1},
{"b", "a", 1},
{"infinity", "infinity", 0},
{"nan", "nan", 0},
{tstEqerType1("a"), tstEqerType1("a"), 0},
{tstEqerType1("a"), tstEqerType2("a"), 0},
{tstEqerType2("a"), tstEqerType1("a"), 0},
Expand Down

0 comments on commit f95fd57

Please sign in to comment.