gitee.com/quant1x/num@v0.3.2/type_int32.go (about) 1 package num 2 3 import ( 4 "fmt" 5 "gitee.com/quant1x/gox/logger" 6 "gitee.com/quant1x/num/x32" 7 "gitee.com/quant1x/num/x64" 8 "math" 9 "strconv" 10 ) 11 12 const ( 13 MaxInt32 = int32(math.MaxInt32) 14 MinInt32 = int32(math.MinInt32) 15 Nil2Int32 = int32(0) // 空指针转int32 16 Int32NaN = int32(0) // int32 无效值 17 True2Int32 = int32(1) // true转int32 18 False2Int32 = int32(0) // false 转int32 19 StringBad2Int32 = int32(0) // 字符串解析int32异常 20 StringTrue2Int32 = int32(1) // 字符串true转int32 21 StringFalse2Int32 = int32(0) // 字符串false转int32 22 ) 23 24 // ParseInt32 解析int字符串, 尝试解析10进制和16进制 25 func ParseInt32(s string, v any) int32 { 26 defer func() { 27 // 解析失败以后输出日志, 以备检查 28 if err := recover(); err != nil { 29 logger.Errorf("ParseInt32 %+v, error=%+v\n", v, err) 30 } 31 }() 32 if IsEmpty(s) { 33 return Nil2Int32 34 } 35 if StringIsTrue(s) { 36 return StringTrue2Int32 37 } else if StringIsFalse(s) { 38 return StringFalse2Int32 39 } 40 if StringIsNaN(s) { 41 return StringFalse2Int32 42 } 43 i, err := strconv.ParseInt(s, 10, 32) 44 if err == nil { 45 return int32(i) 46 } 47 // 解析失败继续解析16进制 48 i, err = strconv.ParseInt(s, 16, 32) 49 if err == nil { 50 return int32(i) 51 } 52 logger.Errorf("%s, error=%+v\n", s, err) 53 if IgnoreParseExceptions { 54 i = int64(StringBad2Int32) 55 } else { 56 _ = v.(int32) // Intentionally panic 57 } 58 return int32(i) 59 } 60 61 func int32ToString(v int32) string { 62 if Float64IsNaN(float64(v)) { 63 return StringNaN 64 } 65 return fmt.Sprint(v) 66 } 67 68 // AnyToInt32 any转换int32 69 func AnyToInt32(v any) int32 { 70 if vv, ok := ExtractValueFromPointer(v); ok { 71 v = vv 72 } 73 74 f := valueToNumber[int32](v, Nil2Int32, BoolToInt32, ParseInt32) 75 return f 76 } 77 78 // SliceFloatToInt32 浮点转int32 79 func SliceFloatToInt32[T Float](x []T) []int32 { 80 switch values := any(x).(type) { 81 case []float32: 82 return x32.ToInt32(values) 83 case []float64: 84 return x64.ToInt32(values) 85 } 86 // 不可能走到这里 87 return []int32{} 88 }