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.

81 lines
1.7 KiB

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