package util import ( "bytes" "encoding/hex" "fmt" "log" "math" "path" "strconv" "strings" "golang.org/x/text/cases" "golang.org/x/text/language" ) func PrependToSliceStr(strs *[]string, prefix string) { for i, elm := range *strs { (*strs)[i] = prefix + elm } } func AppendToSliceStr(strs *[]string, suffix string) { for i, elm := range *strs { (*strs)[i] = elm + suffix } } func Str2int64(str string, base int, fallback int64) int64 { str = strings.TrimSuffix(str, "\n") num, err := strconv.ParseInt(str, base, 64) if err != nil { num = fallback } return num } func Str2int(str string, base int, fallback int) int { return int(Str2int64(str, base, int64(fallback))) } func CastStrings2ints(strs *[]string) []int { a := make([]int, len(*strs)) for i, elm := range *strs { var f int = Str2int(elm, 10, 0) a[i] = f } return a } func PrettyByteSize(b int64) string { bf := float64(b) for _, unit := range []string{"", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"} { if math.Abs(bf) < 1024.0 { return fmt.Sprintf("%3.2f%s", bf, unit) } bf /= 1024.0 } return fmt.Sprintf("%.2fYi", bf) } func Ucfirst(str *string) { caser := cases.Title(language.English) *str = caser.String(*str) } func RemoveExtension(fileName string) string { return strings.TrimSuffix(fileName, path.Ext(fileName)) } func GetBytesAsHex(key []byte) []byte { dst := make([]byte, hex.EncodedLen(len(key))) hex.Encode(dst, key) return dst } func GetBytesFromHex(key []byte) []byte { dst := make([]byte, hex.DecodedLen(len(key))) n, err := hex.Decode(dst, key) if err != nil { log.Fatal(err) } return dst[:n] } func Escape(str string, c rune) string { var buf bytes.Buffer for _, char := range str { switch char { case c: buf.WriteRune('\\') } buf.WriteRune(char) } return buf.String() } func EscapeBt(str string) string { return Escape(str, '`') } func EscapeDquote(str string) string { return Escape(str, '"') } func EscapeSquote(str string) string { return Escape(str, '\'') }