parse_integral_number_unit.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. //go:build unit
  2. package service
  3. import (
  4. "encoding/json"
  5. "math"
  6. )
  7. // parseIntegralNumber 将 JSON 解码后的数字安全转换为 int。
  8. // 仅接受“整数值”的输入,小数/NaN/Inf/越界值都会返回 false。
  9. //
  10. // 说明:
  11. // - 该函数当前仅用于 unit 测试中的 map-based 解析逻辑验证,因此放在 unit build tag 下,
  12. // 避免在默认构建中触发 unused lint。
  13. func parseIntegralNumber(raw any) (int, bool) {
  14. switch v := raw.(type) {
  15. case float64:
  16. if math.IsNaN(v) || math.IsInf(v, 0) || v != math.Trunc(v) {
  17. return 0, false
  18. }
  19. if v > float64(math.MaxInt) || v < float64(math.MinInt) {
  20. return 0, false
  21. }
  22. return int(v), true
  23. case int:
  24. return v, true
  25. case int8:
  26. return int(v), true
  27. case int16:
  28. return int(v), true
  29. case int32:
  30. return int(v), true
  31. case int64:
  32. if v > int64(math.MaxInt) || v < int64(math.MinInt) {
  33. return 0, false
  34. }
  35. return int(v), true
  36. case json.Number:
  37. i64, err := v.Int64()
  38. if err != nil {
  39. return 0, false
  40. }
  41. if i64 > int64(math.MaxInt) || i64 < int64(math.MinInt) {
  42. return 0, false
  43. }
  44. return int(i64), true
  45. default:
  46. return 0, false
  47. }
  48. }