github.com/yandex/pandora@v0.5.32/lib/numbers/int.go (about)

     1  package numbers
     2  
     3  import (
     4  	"fmt"
     5  	"math"
     6  	"strconv"
     7  )
     8  
     9  func ParseInt(input any) (int64, error) {
    10  	switch v := input.(type) {
    11  	case int:
    12  		return int64(v), nil
    13  	case int8:
    14  		return int64(v), nil
    15  	case int16:
    16  		return int64(v), nil
    17  	case int32:
    18  		return int64(v), nil
    19  	case int64:
    20  		return v, nil
    21  	case uint:
    22  		if v > uint(math.MaxInt64) {
    23  			return 0, fmt.Errorf("uint value overflows int64")
    24  		}
    25  		return int64(v), nil
    26  	case uint8:
    27  		return int64(v), nil
    28  	case uint16:
    29  		return int64(v), nil
    30  	case uint32:
    31  		return int64(v), nil
    32  	case uint64:
    33  		if v > uint64(math.MaxInt64) {
    34  			return 0, fmt.Errorf("uint64 value overflows int64")
    35  		}
    36  		return int64(v), nil
    37  	case string:
    38  		f, err := strconv.ParseInt(v, 10, 64)
    39  		if err != nil {
    40  			return 0, fmt.Errorf("cannot parse '%v' as int64: %w", v, err)
    41  		}
    42  		return f, nil
    43  	default:
    44  		return 0, fmt.Errorf("unsupported type: %T", input)
    45  	}
    46  }
    47  
    48  func ParseFloat(input any) (float64, error) {
    49  	switch v := input.(type) {
    50  	case int:
    51  		return float64(v), nil
    52  	case int32:
    53  		return float64(v), nil
    54  	case int64:
    55  		return float64(v), nil
    56  	case uint:
    57  		return float64(v), nil
    58  	case uint32:
    59  		return float64(v), nil
    60  	case uint64:
    61  		if v > uint64(^uint(0)>>1) {
    62  			return 0, fmt.Errorf("uint64 value too large for precise conversion: %v", v)
    63  		}
    64  		return float64(v), nil
    65  	case float32:
    66  		return float64(v), nil
    67  	case float64:
    68  		return v, nil
    69  	case string:
    70  		f, err := strconv.ParseFloat(v, 64)
    71  		if err != nil {
    72  			return 0, fmt.Errorf("cannot parse '%v' as float64: %w", v, err)
    73  		}
    74  		return f, nil
    75  	default:
    76  		return 0, fmt.Errorf("unsupported type: %T", v)
    77  	}
    78  }