core/util/util.go
mahdi c869dfc0eb
Some checks failed
continuous-integration/drone/push Build is failing
devops - drone test error build
2023-12-14 23:48:23 +01:00

142 lines
2.7 KiB
Go

package util
import (
"bytes"
"encoding/hex"
"fmt"
"log"
"math"
"path"
"reflect"
"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{"", "Kio", "Mio", "Gio", "Tio", "Pio", "Eio", "Zio"} {
if math.Abs(bf) < 1024.0 {
return fmt.Sprintf("%3.2f%s", bf, unit)
}
bf /= 1024.0
}
return fmt.Sprintf("%.2fYio", 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
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, '\'')
}
func InspectStruct(a any) (map[string]string, bool) {
done := false
rs := make(map[string]string)
n := reflect.ValueOf(a)
for {
if n.Kind() == reflect.Ptr {
n = n.Elem()
} else if n.Kind() == reflect.Struct {
break
} else {
return rs, done
}
}
for i := 0; i < n.NumField(); i++ {
rs[n.Type().Field(i).Name] = n.Field(i).Type().String()
}
done = true
return rs, done
}
func InArray(v interface{}, arr interface{}) int {
values := reflect.ValueOf(arr)
if reflect.TypeOf(arr).Kind() == reflect.Slice || values.Len() > 0 {
for i := 0; i < values.Len(); i++ {
if reflect.DeepEqual(v, values.Index(i).Interface()) {
return i
}
}
}
return -1
}