aim-oscar-server/util/util.go

76 lines
1.3 KiB
Go
Raw Normal View History

package util
2021-12-16 19:45:32 -05:00
import (
"encoding/binary"
2021-12-16 19:45:32 -05:00
"encoding/hex"
"fmt"
"strconv"
"strings"
)
// splitBy splits string in chunks of n
// taken from: https://stackoverflow.com/a/69403603
func SplitBy(s string, n int) []string {
2021-12-16 19:45:32 -05:00
var ss []string
for i := 1; i < len(s); i++ {
if i%n == 0 {
ss = append(ss, s[:i])
s = s[i:]
i = 1
}
}
ss = append(ss, s)
return ss
}
func PrettyBytes(bytes []byte) string {
2021-12-16 19:45:32 -05:00
hexStr := hex.EncodeToString(bytes)
rows := SplitBy(hexStr, 16)
2021-12-16 19:45:32 -05:00
res := ""
for _, row := range rows {
byteGroups := SplitBy(row, 2)
2021-12-16 19:45:32 -05:00
// Align string view to full 16 bytes + spaces
res += fmt.Sprintf("%-23s", strings.Join(byteGroups, " "))
res += " |"
for _, r := range byteGroups {
n, err := strconv.ParseInt(r, 16, 8)
if err != nil || (n < 32 || n > 126) {
res += "."
} else {
res += string(rune(n))
}
}
res += "|\n"
}
return strings.TrimSpace(res)
}
func PanicIfError(err error) {
2021-12-16 19:45:32 -05:00
if err != nil {
panic(err)
}
}
func Word(x uint16) []byte {
b := make([]byte, 2)
binary.BigEndian.PutUint16(b, x)
return b
2021-12-16 19:45:32 -05:00
}
func Dword(x uint32) []byte {
b := make([]byte, 4)
binary.BigEndian.PutUint32(b, x)
return b
2021-12-16 19:45:32 -05:00
}
2021-12-19 17:17:47 -05:00
func LPString(x string) []byte {
return append([]byte{uint8(len(x))}, []byte(x)...)
}
func LPUint16String(x string) []byte {
2021-12-19 17:17:47 -05:00
return append(Word(uint16(len(x))), []byte(x)...)
}