字符builder
This commit is contained in:
parent
a6f80c2639
commit
c60c11769a
2
go.mod
2
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
|
||||
|
@ -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...))
|
||||
}
|
||||
|
@ -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())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user