xstr.go 930 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package xstr
  2. import (
  3. "bytes"
  4. "strconv"
  5. "strings"
  6. "sync"
  7. )
  8. var (
  9. bfPool = sync.Pool{
  10. New: func() interface{} {
  11. return bytes.NewBuffer([]byte{})
  12. },
  13. }
  14. )
  15. // JoinInts format int64 slice like:n1,n2,n3.
  16. func JoinInts(is []int64) string {
  17. if len(is) == 0 {
  18. return ""
  19. }
  20. if len(is) == 1 {
  21. return strconv.FormatInt(is[0], 10)
  22. }
  23. buf := bfPool.Get().(*bytes.Buffer)
  24. for _, i := range is {
  25. buf.WriteString(strconv.FormatInt(i, 10))
  26. buf.WriteByte(',')
  27. }
  28. if buf.Len() > 0 {
  29. buf.Truncate(buf.Len() - 1)
  30. }
  31. s := buf.String()
  32. buf.Reset()
  33. bfPool.Put(buf)
  34. return s
  35. }
  36. // SplitInts split string into int64 slice.
  37. func SplitInts(s string) ([]int64, error) {
  38. if s == "" {
  39. return nil, nil
  40. }
  41. sArr := strings.Split(s, ",")
  42. res := make([]int64, 0, len(sArr))
  43. for _, sc := range sArr {
  44. i, err := strconv.ParseInt(sc, 10, 64)
  45. if err != nil {
  46. return nil, err
  47. }
  48. res = append(res, i)
  49. }
  50. return res, nil
  51. }