Handle numbers with underscores #2039

This commit is contained in:
Mike Farah 2024-06-16 11:05:27 +10:00
parent d58870b056
commit 68aafb6a53
2 changed files with 20 additions and 2 deletions

View File

@ -135,8 +135,12 @@ func recursiveNodeEqual(lhs *CandidateNode, rhs *CandidateNode) bool {
return false
}
// yaml numbers can be hex and octal encoded...
// yaml numbers can have underscores, be hex and octal encoded...
func parseInt64(numberString string) (string, int64, error) {
if strings.Contains(numberString, "_") {
numberString = strings.ReplaceAll(numberString, "_", "")
}
if strings.HasPrefix(numberString, "0x") ||
strings.HasPrefix(numberString, "0X") {
num, err := strconv.ParseInt(numberString[2:], 16, 64)

View File

@ -106,6 +106,7 @@ func TestParseSnippet(t *testing.T) {
type parseInt64Scenario struct {
numberString string
expectedParsedNumber int64
expectedFormatString string
}
var parseInt64Scenarios = []parseInt64Scenario{
@ -113,10 +114,20 @@ var parseInt64Scenarios = []parseInt64Scenario{
numberString: "34",
expectedParsedNumber: 34,
},
{
numberString: "10_000",
expectedParsedNumber: 10000,
expectedFormatString: "10000",
},
{
numberString: "0x10",
expectedParsedNumber: 16,
},
{
numberString: "0x10_000",
expectedParsedNumber: 65536,
expectedFormatString: "0x10000",
},
{
numberString: "0o10",
expectedParsedNumber: 8,
@ -132,7 +143,10 @@ func TestParseInt64(t *testing.T) {
t.Error(err)
}
test.AssertResultComplexWithContext(t, tt.expectedParsedNumber, actualNumber, tt.numberString)
if tt.expectedFormatString == "" {
tt.expectedFormatString = tt.numberString
}
test.AssertResultComplexWithContext(t, tt.numberString, fmt.Sprintf(format, actualNumber), fmt.Sprintf("Formatting of: %v", tt.numberString))
test.AssertResultComplexWithContext(t, tt.expectedFormatString, fmt.Sprintf(format, actualNumber), fmt.Sprintf("Formatting of: %v", tt.numberString))
}
}