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.

89 lines
1.9 KiB

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