github.com/sandwich-go/boost@v1.3.29/xconv/uint.go (about)

     1  package xconv
     2  
     3  import (
     4  	"strconv"
     5  )
     6  
     7  // Uint converts `any` to uint.
     8  func Uint(any interface{}) uint {
     9  	if any == nil {
    10  		return 0
    11  	}
    12  	if v, ok := any.(uint); ok {
    13  		return v
    14  	}
    15  	return uint(Uint64(any))
    16  }
    17  
    18  // Uint8 converts `any` to uint8.
    19  func Uint8(any interface{}) uint8 {
    20  	if any == nil {
    21  		return 0
    22  	}
    23  	if v, ok := any.(uint8); ok {
    24  		return v
    25  	}
    26  	return uint8(Uint64(any))
    27  }
    28  
    29  // Uint16 converts `any` to uint16.
    30  func Uint16(any interface{}) uint16 {
    31  	if any == nil {
    32  		return 0
    33  	}
    34  	if v, ok := any.(uint16); ok {
    35  		return v
    36  	}
    37  	return uint16(Uint64(any))
    38  }
    39  
    40  // Uint32 converts `any` to uint32.
    41  func Uint32(any interface{}) uint32 {
    42  	if any == nil {
    43  		return 0
    44  	}
    45  	if v, ok := any.(uint32); ok {
    46  		return v
    47  	}
    48  	return uint32(Uint64(any))
    49  }
    50  
    51  // Uint64 converts `any` to uint64.
    52  func Uint64(any interface{}) uint64 {
    53  	if any == nil {
    54  		return 0
    55  	}
    56  	switch value := any.(type) {
    57  	case int:
    58  		return uint64(value)
    59  	case int8:
    60  		return uint64(value)
    61  	case int16:
    62  		return uint64(value)
    63  	case int32:
    64  		return uint64(value)
    65  	case int64:
    66  		return uint64(value)
    67  	case uint:
    68  		return uint64(value)
    69  	case uint8:
    70  		return uint64(value)
    71  	case uint16:
    72  		return uint64(value)
    73  	case uint32:
    74  		return uint64(value)
    75  	case uint64:
    76  		return value
    77  	case float32:
    78  		return uint64(value)
    79  	case float64:
    80  		return uint64(value)
    81  	case bool:
    82  		if value {
    83  			return 1
    84  		}
    85  		return 0
    86  	case []byte:
    87  		return LittleEndianDecodeToUint64(value)
    88  	default:
    89  		if f, ok := value.(iUint64); ok {
    90  			return f.Uint64()
    91  		}
    92  		s := String(value)
    93  		// Hexadecimal
    94  		if len(s) > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X') {
    95  			if v, e := strconv.ParseUint(s[2:], 16, 64); e == nil {
    96  				return v
    97  			}
    98  		}
    99  		// Octal
   100  		if len(s) > 1 && s[0] == '0' {
   101  			if v, e := strconv.ParseUint(s[1:], 8, 64); e == nil {
   102  				return v
   103  			}
   104  		}
   105  		// Decimal
   106  		if v, e := strconv.ParseUint(s, 10, 64); e == nil {
   107  			return v
   108  		}
   109  		// Float64
   110  		return uint64(Float64(value))
   111  	}
   112  }