xstr.go
1.0 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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)
joinWithDelim(buf,is,byte(','))
s := buf.String()
buf.Reset()
bfPool.Put(buf)
return s
}
func joinWithDelim(buf *bytes.Buffer,is []int64,delim byte){
for _, i := range is {
buf.WriteString(strconv.FormatInt(i, 10))
buf.WriteByte(',')
}
if buf.Len() > 0 {
buf.Truncate(buf.Len() - 1)
}
}
// 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
}