1
0
Fork 0
mirror of https://github.com/Luzifer/rconfig.git synced 2024-11-09 16:30:04 +00:00
rconfig/strconv.go
Knut Ahlers 80dd107159
Fix: Ensure int/uint do not overflow
by utilizing correct parsing for the requested type in strconv

Signed-off-by: Knut Ahlers <knut@ahlers.me>
2024-08-27 15:47:47 +02:00

51 lines
1.2 KiB
Go

package rconfig
import (
"fmt"
"reflect"
"strconv"
)
func parseIntForType(s string, base int, fieldType reflect.Kind) (i int64, err error) {
switch fieldType {
case reflect.Int:
return strconv.ParseInt(s, base, strconv.IntSize) //nolint:wrapcheck
case reflect.Int8:
return strconv.ParseInt(s, base, 8) //nolint:wrapcheck
case reflect.Int16:
return strconv.ParseInt(s, base, 16) //nolint:wrapcheck
case reflect.Int32:
return strconv.ParseInt(s, base, 32) //nolint:wrapcheck
case reflect.Int64:
return strconv.ParseInt(s, base, 64) //nolint:wrapcheck
default:
return 0, fmt.Errorf("unsupported type: %v", fieldType)
}
}
func parseUintForType(s string, base int, fieldType reflect.Kind) (uint64, error) {
switch fieldType {
case reflect.Uint:
return strconv.ParseUint(s, base, strconv.IntSize) //nolint:wrapcheck
case reflect.Uint8:
return strconv.ParseUint(s, base, 8) //nolint:wrapcheck
case reflect.Uint16:
return strconv.ParseUint(s, base, 16) //nolint:wrapcheck
case reflect.Uint32:
return strconv.ParseUint(s, base, 32) //nolint:wrapcheck
case reflect.Uint64:
return strconv.ParseUint(s, base, 64) //nolint:wrapcheck
default:
return 0, fmt.Errorf("unsupported type: %v", fieldType)
}
}