github.com/tickstep/library-go@v0.1.1/converter/converter.go (about) 1 // Package converter 格式, 类型转换包 2 package converter 3 4 import ( 5 "github.com/mattn/go-runewidth" 6 "reflect" 7 "strconv" 8 "strings" 9 "unicode" 10 "unsafe" 11 ) 12 13 const ( 14 // InvalidChars 文件名中的非法字符 15 InvalidChars = `\/:*?"<>|` 16 ) 17 18 // ToString unsafe 转换, 将 []byte 转换为 string 19 func ToString(p []byte) string { 20 return *(*string)(unsafe.Pointer(&p)) 21 } 22 23 // ToBytes unsafe 转换, 将 string 转换为 []byte 24 func ToBytes(str string) []byte { 25 strHeader := (*reflect.StringHeader)(unsafe.Pointer(&str)) 26 return *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{ 27 Data: strHeader.Data, 28 Len: strHeader.Len, 29 Cap: strHeader.Len, 30 })) 31 } 32 33 // ToBytesUnsafe unsafe 转换, 请确保转换后的 []byte 不涉及 cap() 操作, 将 string 转换为 []byte 34 func ToBytesUnsafe(str string) []byte { 35 return *(*[]byte)(unsafe.Pointer(&str)) 36 } 37 38 // IntToBool int 类型转换为 bool 39 func IntToBool(i int) bool { 40 return i != 0 41 } 42 43 // SliceInt64ToString []int64 转换为 []string 44 func SliceInt64ToString(si []int64) (ss []string) { 45 ss = make([]string, 0, len(si)) 46 for k := range si { 47 ss = append(ss, strconv.FormatInt(si[k], 10)) 48 } 49 return ss 50 } 51 52 // SliceStringToInt64 []string 转换为 []int64 53 func SliceStringToInt64(ss []string) (si []int64) { 54 si = make([]int64, 0, len(ss)) 55 var ( 56 i int64 57 err error 58 ) 59 for k := range ss { 60 i, err = strconv.ParseInt(ss[k], 10, 64) 61 if err != nil { 62 continue 63 } 64 si = append(si, i) 65 } 66 return 67 } 68 69 // SliceStringToInt []string 转换为 []int 70 func SliceStringToInt(ss []string) (si []int) { 71 si = make([]int, 0, len(ss)) 72 var ( 73 i int 74 err error 75 ) 76 for k := range ss { 77 i, err = strconv.Atoi(ss[k]) 78 if err != nil { 79 continue 80 } 81 si = append(si, i) 82 } 83 return 84 } 85 86 // MustInt 将string转换为int, 忽略错误 87 func MustInt(s string) (n int) { 88 n, _ = strconv.Atoi(s) 89 return 90 } 91 92 // MustInt64 将string转换为int64, 忽略错误 93 func MustInt64(s string) (i int64) { 94 i, _ = strconv.ParseInt(s, 10, 64) 95 return 96 } 97 98 // ShortDisplay 缩略显示字符串s, 显示长度为num, 缩略的内容用"..."填充 99 func ShortDisplay(s string, num int) string { 100 var ( 101 sb = strings.Builder{} 102 n int 103 ) 104 for _, v := range s { 105 if unicode.Is(unicode.C, v) { // 去除无效字符 106 continue 107 } 108 n += runewidth.RuneWidth(v) 109 if n > num { 110 sb.WriteString("...") 111 break 112 } 113 sb.WriteRune(v) 114 } 115 116 return sb.String() 117 } 118 119 // TrimPathInvalidChars 清除文件名中的非法字符 120 func TrimPathInvalidChars(fpath string) string { 121 buf := make([]byte, 0, len(fpath)) 122 123 for _, c := range ToBytesUnsafe(fpath) { 124 if strings.ContainsRune(InvalidChars, rune(c)) { 125 continue 126 } 127 128 buf = append(buf, c) 129 } 130 131 return ToString(buf) 132 }