wp-go/helper/strings/strings.go

77 lines
1.3 KiB
Go
Raw Normal View History

2023-01-21 11:31:23 +00:00
package strings
2023-01-13 04:31:35 +00:00
import (
"crypto/md5"
2023-02-15 16:58:59 +00:00
"errors"
2023-01-13 04:31:35 +00:00
"fmt"
"golang.org/x/exp/constraints"
2023-01-13 04:31:35 +00:00
"io"
"strconv"
2023-01-13 04:31:35 +00:00
"strings"
)
2023-01-21 11:31:23 +00:00
func Join(s ...string) (str string) {
2023-01-13 04:31:35 +00:00
if len(s) == 1 {
return s[0]
} else if len(s) > 1 {
b := strings.Builder{}
for _, s2 := range s {
b.WriteString(s2)
}
str = b.String()
}
return
}
func ToInteger[T constraints.Integer](s string, defaults T) T {
if s == "" {
return defaults
}
i, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return defaults
}
return T(i)
}
2023-01-21 11:31:23 +00:00
func Md5(str string) string {
2023-01-13 04:31:35 +00:00
h := md5.New()
_, err := io.WriteString(h, str)
if err != nil {
return ""
}
return fmt.Sprintf("%x", h.Sum(nil))
}
2023-02-15 16:58:59 +00:00
func BuilderJoin(s *strings.Builder, str ...string) {
for _, ss := range str {
s.WriteString(ss)
}
}
func BuilderFormat(s *strings.Builder, format string, args ...any) {
s.WriteString(fmt.Sprintf(format, args...))
}
type Builder struct {
*strings.Builder
}
func NewBuilder() *Builder {
return &Builder{&strings.Builder{}}
}
func (b *Builder) WriteString(s ...string) (count int, err error) {
for _, ss := range s {
i, er := b.Builder.WriteString(ss)
if er != nil {
err = errors.Join(er)
}
count += i
}
return
}
func (b *Builder) Sprintf(format string, a ...any) (int, error) {
return b.WriteString(fmt.Sprintf(format, a...))
}