Files
EdgeNode/internal/utils/string.go

72 lines
1.6 KiB
Go
Raw Permalink Normal View History

2020-10-08 15:06:42 +08:00
package utils
import (
2022-05-18 21:03:51 +08:00
"sort"
2020-10-08 15:06:42 +08:00
"strings"
"unsafe"
)
// UnsafeBytesToString convert bytes to string
2020-10-08 15:06:42 +08:00
func UnsafeBytesToString(bs []byte) string {
return *(*string)(unsafe.Pointer(&bs))
}
// UnsafeStringToBytes convert string to bytes
2020-10-08 15:06:42 +08:00
func UnsafeStringToBytes(s string) []byte {
return *(*[]byte)(unsafe.Pointer(&s))
}
// FormatAddress format address
2020-10-08 15:06:42 +08:00
func FormatAddress(addr string) string {
if strings.HasSuffix(addr, "unix:") {
return addr
}
addr = strings.Replace(addr, " ", "", -1)
addr = strings.Replace(addr, "\t", "", -1)
addr = strings.Replace(addr, "", ":", -1)
addr = strings.TrimSpace(addr)
return addr
}
// FormatAddressList format address list
2020-10-08 15:06:42 +08:00
func FormatAddressList(addrList []string) []string {
result := []string{}
for _, addr := range addrList {
result = append(result, FormatAddress(addr))
}
return result
}
2022-05-18 21:03:51 +08:00
// ToValidUTF8string 去除字符串中的非UTF-8字符
func ToValidUTF8string(v string) string {
return strings.ToValidUTF8(v, "")
}
2022-05-18 21:03:51 +08:00
// EqualStrings 检查两个字符串slice内容是否一致
func EqualStrings(s1 []string, s2 []string) bool {
2022-05-18 21:03:51 +08:00
if len(s1) != len(s2) {
return false
}
sort.Strings(s1)
sort.Strings(s2)
for index, v1 := range s1 {
if v1 != s2[index] {
return false
}
}
return true
}
// CutPrefix returns s without the provided leading prefix string
// and reports whether it found the prefix.
// If s doesn't start with prefix, CutPrefix returns s, false.
// If prefix is the empty string, CutPrefix returns s, true.
//
// copy from go source
func CutPrefix(s, prefix string) (after string, found bool) {
if !strings.HasPrefix(s, prefix) {
return s, false
}
return s[len(prefix):], true
}