You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
1.6 KiB

9 years ago
  1. package common
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. // StringInSlice returns true if a is found the list.
  7. func StringInSlice(a string, list []string) bool {
  8. for _, b := range list {
  9. if b == a {
  10. return true
  11. }
  12. }
  13. return false
  14. }
  15. // SplitAndTrim slices s into all subslices separated by sep and returns a
  16. // slice of the string s with all leading and trailing Unicode code points
  17. // contained in cutset removed. If sep is empty, SplitAndTrim splits after each
  18. // UTF-8 sequence. First part is equivalent to strings.SplitN with a count of
  19. // -1.
  20. func SplitAndTrim(s, sep, cutset string) []string {
  21. if s == "" {
  22. return []string{}
  23. }
  24. spl := strings.Split(s, sep)
  25. for i := 0; i < len(spl); i++ {
  26. spl[i] = strings.Trim(spl[i], cutset)
  27. }
  28. return spl
  29. }
  30. // Returns true if s is a non-empty printable non-tab ascii character.
  31. func IsASCIIText(s string) bool {
  32. if len(s) == 0 {
  33. return false
  34. }
  35. for _, b := range []byte(s) {
  36. if 32 <= b && b <= 126 {
  37. // good
  38. } else {
  39. return false
  40. }
  41. }
  42. return true
  43. }
  44. // NOTE: Assumes that s is ASCII as per IsASCIIText(), otherwise panics.
  45. func ASCIITrim(s string) string {
  46. r := make([]byte, 0, len(s))
  47. for _, b := range []byte(s) {
  48. if b == 32 {
  49. continue // skip space
  50. } else if 32 < b && b <= 126 {
  51. r = append(r, b)
  52. } else {
  53. panic(fmt.Sprintf("non-ASCII (non-tab) char 0x%X", b))
  54. }
  55. }
  56. return string(r)
  57. }
  58. // StringSliceEqual checks if string slices a and b are equal
  59. func StringSliceEqual(a, b []string) bool {
  60. if len(a) != len(b) {
  61. return false
  62. }
  63. for i := 0; i < len(a); i++ {
  64. if a[i] != b[i] {
  65. return false
  66. }
  67. }
  68. return true
  69. }