diff --git a/go.mod b/go.mod index 12c9ce7..38dbb1c 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/fthvgb1/wp-go -go 1.19 +go 1.20 require ( github.com/dlclark/regexp2 v1.7.0 diff --git a/helper/strings/strings.go b/helper/strings/strings.go index 8252a48..ee0811d 100644 --- a/helper/strings/strings.go +++ b/helper/strings/strings.go @@ -2,6 +2,7 @@ package strings import ( "crypto/md5" + "errors" "fmt" "golang.org/x/exp/constraints" "io" @@ -41,3 +42,35 @@ func Md5(str string) string { } return fmt.Sprintf("%x", h.Sum(nil)) } + +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...)) +} diff --git a/helper/strings/strings_test.go b/helper/strings/strings_test.go index 636bb39..86d10f3 100644 --- a/helper/strings/strings_test.go +++ b/helper/strings/strings_test.go @@ -1,7 +1,9 @@ package strings import ( + "fmt" "golang.org/x/exp/constraints" + "strings" "testing" ) @@ -53,3 +55,46 @@ func TestToInteger(t *testing.T) { }) } } + +func TestBuilder_WriteString(t *testing.T) { + type fields struct { + Builder *strings.Builder + } + type args struct { + s []string + } + //s :=NewBuilder() + tests := []struct { + name string + fields fields + args args + wantCount int + wantErr bool + }{ + { + name: "t1", + fields: fields{ + Builder: &strings.Builder{}, + }, + args: args{s: []string{"11", "22", "不"}}, + wantErr: false, + wantCount: 7, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + b := &Builder{ + Builder: tt.fields.Builder, + } + gotCount, err := b.WriteString(tt.args.s...) + if (err != nil) != tt.wantErr { + t.Errorf("WriteString() error = %v, wantErr %v", err, tt.wantErr) + return + } + if gotCount != tt.wantCount { + t.Errorf("WriteString() gotCount = %v, want %v", gotCount, tt.wantCount) + } + fmt.Println(b.String()) + }) + } +}