tprint/utils.go

65 lines
1.1 KiB
Go
Raw Permalink Normal View History

2022-08-25 16:03:24 +02:00
package tprint
2022-08-25 16:00:13 +02:00
import (
"strings"
"unicode"
2022-08-25 22:47:11 +02:00
"github.com/mattn/go-runewidth"
2022-08-25 16:00:13 +02:00
)
func maxLengthStr(a, b string) string {
if strLen(a) > strLen(b) {
return a
}
return b
}
func maxLengthSlice[T any](a, b []T) []T {
if len(a) > len(b) {
return a
}
return b
}
func strLen(str string) int {
l := 0
runes := []rune(str)
for i := 0; i < len(runes); i++ {
2022-08-25 22:47:11 +02:00
rn := runes[i]
2022-08-25 16:55:19 +02:00
// skip control sequences
2022-08-25 22:47:11 +02:00
if unicode.IsControl(rn) {
2022-08-25 16:55:19 +02:00
for j := i; j < len(runes)-1 && runes[j] != 'm'; j++ {
i = j
2022-08-25 16:00:13 +02:00
}
2022-08-25 16:55:19 +02:00
i++
2022-08-25 16:00:13 +02:00
continue
}
2022-08-25 22:47:11 +02:00
if rn <= 0xFF || rn >= '─' && rn <= '╿' {
l++
} else {
l += runewidth.RuneWidth(rn)
}
2022-08-25 16:00:13 +02:00
}
return l
}
func padStringRight(str string, pad rune, length int) string {
padding := length - strLen(str)
return str + strings.Repeat(string(pad), padding)
}
2022-08-25 16:55:19 +02:00
func padStringLeft(str string, pad rune, length int) string {
padding := length - strLen(str)
return strings.Repeat(string(pad), padding) + str
}
func padStringCenter(str string, pad rune, length int) string {
l := strLen(str)
return padStringLeft(padStringRight(str, pad, (length-l)/2+l), pad, length)
}