strutil.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Package strutil provides various utilities for manipulating strings
  2. package strutil
  3. import (
  4. "bytes"
  5. "github.com/mattn/go-runewidth"
  6. )
  7. // PadRight returns a new string of a specified length in which the end of the current string is padded with spaces or with a specified Unicode character.
  8. func PadRight(str string, length int, pad byte) string {
  9. slen := runewidth.StringWidth(str)
  10. if slen >= length {
  11. return str
  12. }
  13. buf := bytes.NewBufferString(str)
  14. for i := 0; i < length-slen; i++ {
  15. buf.WriteByte(pad)
  16. }
  17. return buf.String()
  18. }
  19. // PadLeft returns a new string of a specified length in which the beginning of the current string is padded with spaces or with a specified Unicode character.
  20. func PadLeft(str string, length int, pad byte) string {
  21. slen := runewidth.StringWidth(str)
  22. if slen >= length {
  23. return str
  24. }
  25. var buf bytes.Buffer
  26. for i := 0; i < length-slen; i++ {
  27. buf.WriteByte(pad)
  28. }
  29. buf.WriteString(str)
  30. return buf.String()
  31. }
  32. // Resize resizes the string with the given length. It ellipses with '...' when the string's length exceeds
  33. // the desired length or pads spaces to the right of the string when length is smaller than desired
  34. func Resize(s string, length uint, rightAlign bool) string {
  35. slen := runewidth.StringWidth(s)
  36. n := int(length)
  37. if slen == n {
  38. return s
  39. }
  40. // Pads only when length of the string smaller than len needed
  41. if rightAlign {
  42. s = PadLeft(s, n, ' ')
  43. } else {
  44. s = PadRight(s, n, ' ')
  45. }
  46. if slen > n {
  47. rs := []rune(s)
  48. var buf bytes.Buffer
  49. w := 0
  50. for _, r := range rs {
  51. buf.WriteRune(r)
  52. rw := runewidth.RuneWidth(r)
  53. if w+rw >= n-3 {
  54. break
  55. }
  56. w += rw
  57. }
  58. buf.WriteString("...")
  59. s = buf.String()
  60. }
  61. return s
  62. }
  63. // Join joins the list of the string with the delim provided
  64. func Join(list []string, delim string) string {
  65. var buf bytes.Buffer
  66. for i := 0; i < len(list)-1; i++ {
  67. buf.WriteString(list[i] + delim)
  68. }
  69. buf.WriteString(list[len(list)-1])
  70. return buf.String()
  71. }