Create & Init Project...

This commit is contained in:
2019-04-22 18:49:16 +08:00
commit fc4fa37393
25440 changed files with 4054998 additions and 0 deletions

35
library/xstr/BUILD Normal file
View File

@@ -0,0 +1,35 @@
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
package(default_visibility = ["//visibility:public"])
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)
go_library(
name = "go_default_library",
srcs = ["xstr.go"],
importpath = "go-common/library/xstr",
tags = ["automanaged"],
)
go_test(
name = "go_default_test",
srcs = ["xstr_test.go"],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
)

55
library/xstr/xstr.go Normal file
View File

@@ -0,0 +1,55 @@
package xstr
import (
"bytes"
"strconv"
"strings"
"sync"
)
var (
bfPool = sync.Pool{
New: func() interface{} {
return bytes.NewBuffer([]byte{})
},
}
)
// JoinInts format int64 slice like:n1,n2,n3.
func JoinInts(is []int64) string {
if len(is) == 0 {
return ""
}
if len(is) == 1 {
return strconv.FormatInt(is[0], 10)
}
buf := bfPool.Get().(*bytes.Buffer)
for _, i := range is {
buf.WriteString(strconv.FormatInt(i, 10))
buf.WriteByte(',')
}
if buf.Len() > 0 {
buf.Truncate(buf.Len() - 1)
}
s := buf.String()
buf.Reset()
bfPool.Put(buf)
return s
}
// SplitInts split string into int64 slice.
func SplitInts(s string) ([]int64, error) {
if s == "" {
return nil, nil
}
sArr := strings.Split(s, ",")
res := make([]int64, 0, len(sArr))
for _, sc := range sArr {
i, err := strconv.ParseInt(sc, 10, 64)
if err != nil {
return nil, err
}
res = append(res, i)
}
return res, nil
}

60
library/xstr/xstr_test.go Normal file
View File

@@ -0,0 +1,60 @@
package xstr
import (
"testing"
)
func TestJoinInts(t *testing.T) {
// test empty slice
is := []int64{}
s := JoinInts(is)
if s != "" {
t.Errorf("input:%v,output:%s,result is incorrect", is, s)
} else {
t.Logf("input:%v,output:%s", is, s)
}
// test len(slice)==1
is = []int64{1}
s = JoinInts(is)
if s != "1" {
t.Errorf("input:%v,output:%s,result is incorrect", is, s)
} else {
t.Logf("input:%v,output:%s", is, s)
}
// test len(slice)>1
is = []int64{1, 2, 3}
s = JoinInts(is)
if s != "1,2,3" {
t.Errorf("input:%v,output:%s,result is incorrect", is, s)
} else {
t.Logf("input:%v,output:%s", is, s)
}
}
func TestSplitInts(t *testing.T) {
// test empty slice
s := ""
is, err := SplitInts(s)
if err != nil || len(is) != 0 {
t.Error(err)
}
// test split int64
s = "1,2,3"
is, err = SplitInts(s)
if err != nil || len(is) != 3 {
t.Error(err)
}
}
func BenchmarkJoinInts(b *testing.B) {
is := make([]int64, 10000, 10000)
for i := int64(0); i < 10000; i++ {
is[i] = i
}
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
JoinInts(is)
}
})
}