ParseIntValue strictly parses numeric types (int, int64, uint64, float64) to int, returning (value, true) on success and (0, false) for any unrecognized or non-numeric type. Use this when the caller needs to distinguish a missing/invalid value from a legitimate zero, or when string inputs are not e
(value any)
| 46 | // For lenient conversion that also handles string inputs and returns 0 on failure, |
| 47 | // use ConvertToInt instead. |
| 48 | func ParseIntValue(value any) (int, bool) { |
| 49 | switch v := value.(type) { |
| 50 | case int: |
| 51 | return v, true |
| 52 | case int64: |
| 53 | return int(v), true |
| 54 | case uint64: |
| 55 | // Check for overflow before converting uint64 to int |
| 56 | const maxInt = int(^uint(0) >> 1) |
| 57 | if v > uint64(maxInt) { |
| 58 | typeutilLog.Printf("uint64 value %d exceeds max int value, returning 0", v) |
| 59 | return 0, false |
| 60 | } |
| 61 | return int(v), true |
| 62 | case float64: |
| 63 | intVal := int(v) |
| 64 | // Warn if truncation occurs (value has fractional part) |
| 65 | if v != float64(intVal) { |
| 66 | typeutilLog.Printf("Float value %.2f truncated to integer %d", v, intVal) |
| 67 | } |
| 68 | return intVal, true |
| 69 | default: |
| 70 | return 0, false |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | // SafeUint64ToInt converts uint64 to int, returning 0 if overflow would occur. |
| 75 | func SafeUint64ToInt(u uint64) int { |