字符builder

This commit is contained in:
xing 2023-02-16 00:58:59 +08:00
parent a6f80c2639
commit c60c11769a
3 changed files with 79 additions and 1 deletions

2
go.mod
View File

@ -1,6 +1,6 @@
module github.com/fthvgb1/wp-go module github.com/fthvgb1/wp-go
go 1.19 go 1.20
require ( require (
github.com/dlclark/regexp2 v1.7.0 github.com/dlclark/regexp2 v1.7.0

View File

@ -2,6 +2,7 @@ package strings
import ( import (
"crypto/md5" "crypto/md5"
"errors"
"fmt" "fmt"
"golang.org/x/exp/constraints" "golang.org/x/exp/constraints"
"io" "io"
@ -41,3 +42,35 @@ func Md5(str string) string {
} }
return fmt.Sprintf("%x", h.Sum(nil)) 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...))
}

View File

@ -1,7 +1,9 @@
package strings package strings
import ( import (
"fmt"
"golang.org/x/exp/constraints" "golang.org/x/exp/constraints"
"strings"
"testing" "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())
})
}
}