Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion exporter/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,15 @@ func SanitizeValue(s string) (float64, error) {
func SanitizeIntValue(s string) (int64, error) {
var err error
var value int64
var cleanedString = s
var resultErr string

if value, err = strconv.ParseInt(s, 10, 64); err == nil {
// Check if the string ends with "u64" and strip it off.
if strings.HasSuffix(s, "u64") {
cleanedString = strings.TrimSuffix(s, "u64")
}

if value, err = strconv.ParseInt(cleanedString, 10, 64); err == nil {
return value, nil
}
resultErr = fmt.Sprintf("%s", err)
Expand Down
50 changes: 50 additions & 0 deletions exporter/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,53 @@ func TestSanitizeValueNaN(t *testing.T) {
t.Fatalf("Value sanitization test for %f fails unexpectedly.", math.NaN())
}
}

func TestSanitizeIntValue(t *testing.T) {
tests := []struct {
Input string
ExpectedOutput int64
ShouldSucceed bool
}{
// Baseline int64 parsing.
{"1234", 1234, true},
{"0", 0, true},
{"-1234", -1234, true},
{"9223372036854775807", 9223372036854775807, true}, // math.MaxInt64
{"-9223372036854775808", -9223372036854775808, true},

// Rust-style "u64" suffix should be stripped before parsing.
{"1234u64", 1234, true},
{"0u64", 0, true},
{"9223372036854775807u64", 9223372036854775807, true},

// Values exceeding int64 range must still fail even after stripping.
{"9223372036854775808u64", 0, false}, // math.MaxInt64 + 1
{"18446744073709551615u64", 0, false}, // math.MaxUint64

// Suffix stripping is exact: only trailing "u64", case-sensitive, whole suffix.
{"1234U64", 0, false}, // uppercase not stripped
{"1234u32", 0, false}, // only u64 handled
{"u641234", 0, false}, // suffix must be at end
{"u64", 0, false}, // empty after stripping

// Non-numeric and float inputs are not integers.
{"abcd", 0, false},
{"1234.5", 0, false},
{"1234.5u64", 0, false}, // stripped to "1234.5" - still not an int
{"", 0, false},
{"true", 0, false},
}

for i, test := range tests {
actualOutput, err := SanitizeIntValue(test.Input)
if err != nil && test.ShouldSucceed {
t.Fatalf("Int value sanitization test %d failed with an unexpected error.\nINPUT:\n%q\nERR:\n%s", i, test.Input, err)
}
if err == nil && !test.ShouldSucceed {
t.Fatalf("Int value sanitization test %d succeeded unexpectedly.\nINPUT:\n%q\nGOT:\n%d", i, test.Input, actualOutput)
}
if test.ShouldSucceed && actualOutput != test.ExpectedOutput {
t.Fatalf("Int value sanitization test %d fails unexpectedly.\nINPUT:\n%q\nGOT:\n%d\nEXPECTED:\n%d", i, test.Input, actualOutput, test.ExpectedOutput)
}
}
}