Support different integer formats
In Go you can format numbers in different ways, as doucment in https://go.dev/ref/spec#Integer_literals. ParseInt with a base of 0 will infer the correct base for the number based on a prefix 0x, 0b etc, and also supports the use of the _ to separate digits. This can be helpful with long numbers, to make things easier to read. This switches the ParseInt() calls to use a base of 0, ensuring that if ParseValue is called with an int like 100_000 it'll parse correctly instead of throw an error.
This commit is contained in:
parent
b3bcd8035e
commit
08e5e4d956
|
@ -108,13 +108,13 @@ func ParseValue(v reflect.Value, s string) error {
|
||||||
}
|
}
|
||||||
v.SetBool(x)
|
v.SetBool(x)
|
||||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||||
x, err := strconv.ParseInt(s, 10, v.Type().Bits())
|
x, err := strconv.ParseInt(s, 0, v.Type().Bits())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
v.SetInt(x)
|
v.SetInt(x)
|
||||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
|
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
|
||||||
x, err := strconv.ParseUint(s, 10, v.Type().Bits())
|
x, err := strconv.ParseUint(s, 0, v.Type().Bits())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
|
@ -48,6 +48,7 @@ func TestParseValue(t *testing.T) {
|
||||||
|
|
||||||
// integers
|
// integers
|
||||||
assertParse(t, int(123), "123")
|
assertParse(t, int(123), "123")
|
||||||
|
assertParse(t, int(123), "1_2_3")
|
||||||
assertParse(t, int8(123), "123")
|
assertParse(t, int8(123), "123")
|
||||||
assertParse(t, int16(123), "123")
|
assertParse(t, int16(123), "123")
|
||||||
assertParse(t, int32(123), "123")
|
assertParse(t, int32(123), "123")
|
||||||
|
@ -55,6 +56,7 @@ func TestParseValue(t *testing.T) {
|
||||||
|
|
||||||
// unsigned integers
|
// unsigned integers
|
||||||
assertParse(t, uint(123), "123")
|
assertParse(t, uint(123), "123")
|
||||||
|
assertParse(t, uint(123), "1_2_3")
|
||||||
assertParse(t, byte(123), "123")
|
assertParse(t, byte(123), "123")
|
||||||
assertParse(t, uint8(123), "123")
|
assertParse(t, uint8(123), "123")
|
||||||
assertParse(t, uint16(123), "123")
|
assertParse(t, uint16(123), "123")
|
||||||
|
|
Loading…
Reference in New Issue