github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/f/convert_int.go (about) 1 package f 2 3 import ( 4 "encoding/binary" 5 "github.com/angenalZZZ/gofunc/g" 6 "github.com/cespare/xxhash/v2" 7 "github.com/klauspost/crc32" 8 "reflect" 9 "strconv" 10 "strings" 11 "unsafe" 12 ) 13 14 // Int32Sum returns the CRC-32 checksum of data using the IEEE polynomial. 15 var Int32Sum = crc32.ChecksumIEEE 16 17 // Int32SumString returns the CRC-32 checksum of data using the IEEE polynomial. 18 var Int32SumString = func(s string) uint32 { 19 var b []byte 20 bh := (*reflect.SliceHeader)(unsafe.Pointer(&b)) 21 bh.Data = (*reflect.StringHeader)(unsafe.Pointer(&s)).Data 22 bh.Len = len(s) 23 bh.Cap = len(s) 24 return crc32.ChecksumIEEE(b) 25 } 26 27 // Int64Sum xx.hash is a Go implementation of the 64-bit xxHash algorithm, XXH64. 28 var Int64Sum = xxhash.Sum64 29 30 // Int64SumString xx.hash is a Go implementation of the 64-bit xxHash algorithm, XXH64. 31 var Int64SumString = xxhash.Sum64String 32 33 // Int64MemHash is the hash function used by go map, 34 // it utilizes available hardware instructions(behaves as aes.hash if aes instruction is available). 35 // NOTE: The hash seed changes for every process. So, this cannot be used as a persistent hash. 36 var Int64MemHash = g.MemHash 37 38 // Int64MemHashString is the hash function used by go map, 39 // it utilizes available hardware instructions (behaves as aes.hash if aes instruction is available). 40 // NOTE: The hash seed changes for every process. So, this cannot be used as a persistent hash. 41 var Int64MemHashString = g.MemHashString 42 43 var Uint16Bytes = binary.BigEndian.Uint16 44 var Uint32Bytes = binary.BigEndian.Uint32 45 var Uint64Bytes = binary.BigEndian.Uint64 46 47 func BytesUint16(v uint16) []byte { 48 b := make([]byte, 2) 49 binary.BigEndian.PutUint16(b, v) 50 return b 51 } 52 53 func BytesUint32(v uint32) []byte { 54 b := make([]byte, 4) 55 binary.BigEndian.PutUint32(b, v) 56 return b 57 } 58 59 func BytesUint64(v uint64) []byte { 60 b := make([]byte, 8) 61 binary.BigEndian.PutUint64(b, v) 62 return b 63 } 64 65 // Int convert string to int64, or return 0. 66 func Int(v interface{}) (i int64) { 67 i, _ = ToInt(v) 68 return 69 } 70 71 // ToInt parse string to int64, or return ErrConvertFail. 72 func ToInt(v interface{}) (i int64, err error) { 73 switch t := v.(type) { 74 case string: 75 i, err = strconv.ParseInt(strings.TrimSpace(t), 10, 0) // strconv.ParseInt(t, 0, 64) 76 case int: 77 i = int64(t) 78 case int8: 79 i = int64(t) 80 case int16: 81 i = int64(t) 82 case int32: 83 i = int64(t) 84 case int64: 85 i = t 86 case uint: 87 i = int64(t) 88 case uint8: 89 i = int64(t) 90 case uint16: 91 i = int64(t) 92 case uint32: 93 i = int64(t) 94 case uint64: 95 i = int64(t) 96 case float32: 97 i = int64(t) 98 case float64: 99 i = int64(t) 100 default: 101 err = ErrConvertFail 102 } 103 return 104 }