2021-06-02 17:25:04 +02:00
|
|
|
package txt
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strconv"
|
2021-09-20 23:32:35 +02:00
|
|
|
"strings"
|
2021-06-02 17:25:04 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
// Int converts a string to a signed integer or 0 if invalid.
|
|
|
|
func Int(s string) int {
|
|
|
|
if s == "" {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
2021-09-20 23:32:35 +02:00
|
|
|
result, err := strconv.ParseInt(strings.TrimSpace(s), 10, 32)
|
2021-06-02 17:25:04 +02:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
|
|
|
return int(result)
|
|
|
|
}
|
|
|
|
|
2022-03-25 16:31:09 +01:00
|
|
|
// IntVal converts a string to a validated integer or a default if invalid.
|
2022-07-22 12:38:25 +02:00
|
|
|
func IntVal(s string, min, max, def int) (i int) {
|
2022-03-25 16:31:09 +01:00
|
|
|
if s == "" {
|
2022-07-22 12:38:25 +02:00
|
|
|
return def
|
2022-04-01 13:25:25 +02:00
|
|
|
} else if s[0] == ' ' {
|
|
|
|
s = strings.TrimSpace(s)
|
2022-03-25 16:31:09 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
result, err := strconv.ParseInt(s, 10, 32)
|
|
|
|
|
|
|
|
if err != nil {
|
2022-07-22 12:38:25 +02:00
|
|
|
return def
|
2022-03-25 16:31:09 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
i = int(result)
|
|
|
|
|
|
|
|
if i < min {
|
2022-07-22 12:38:25 +02:00
|
|
|
return def
|
2022-03-25 16:31:09 +01:00
|
|
|
} else if max != 0 && i > max {
|
2022-07-22 12:38:25 +02:00
|
|
|
return def
|
2022-03-25 16:31:09 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return i
|
|
|
|
}
|
|
|
|
|
2021-06-02 17:25:04 +02:00
|
|
|
// UInt converts a string to an unsigned integer or 0 if invalid.
|
|
|
|
func UInt(s string) uint {
|
|
|
|
if s == "" {
|
|
|
|
return 0
|
2022-04-01 13:25:25 +02:00
|
|
|
} else if s[0] == ' ' {
|
|
|
|
s = strings.TrimSpace(s)
|
2021-06-02 17:25:04 +02:00
|
|
|
}
|
|
|
|
|
2022-04-01 13:25:25 +02:00
|
|
|
result, err := strconv.ParseInt(s, 10, 32)
|
2021-06-02 17:25:04 +02:00
|
|
|
|
|
|
|
if err != nil || result < 0 {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
|
|
|
return uint(result)
|
|
|
|
}
|
|
|
|
|
|
|
|
// IsUInt tests if a string represents an unsigned integer.
|
|
|
|
func IsUInt(s string) bool {
|
|
|
|
if s == "" {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, r := range s {
|
|
|
|
if r < 48 || r > 57 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
2022-03-24 18:30:59 +01:00
|
|
|
|
|
|
|
// IsPosInt checks if a string represents an integer greater than 0.
|
|
|
|
func IsPosInt(s string) bool {
|
|
|
|
if s == "" || s == " " || s == "0" || s == "-1" {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, r := range s {
|
|
|
|
if r < 48 || r > 57 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|