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.

60 lines
1.3 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. } else {
  12. return fmt.Sprintf(format, a...)
  13. }
  14. }
  15. // IsHex returns true for non-empty hex-string prefixed with "0x"
  16. func IsHex(s string) bool {
  17. if len(s) > 2 && strings.EqualFold(s[:2], "0x") {
  18. _, err := hex.DecodeString(s[2:])
  19. return err == nil
  20. }
  21. return false
  22. }
  23. // StripHex returns hex string without leading "0x"
  24. func StripHex(s string) string {
  25. if IsHex(s) {
  26. return s[2:]
  27. }
  28. return s
  29. }
  30. // StringInSlice returns true if a is found the list.
  31. func StringInSlice(a string, list []string) bool {
  32. for _, b := range list {
  33. if b == a {
  34. return true
  35. }
  36. }
  37. return false
  38. }
  39. // SplitAndTrim slices s into all subslices separated by sep and returns a
  40. // slice of the string s with all leading and trailing Unicode code points
  41. // contained in cutset removed. If sep is empty, SplitAndTrim splits after each
  42. // UTF-8 sequence. First part is equivalent to strings.SplitN with a count of
  43. // -1.
  44. func SplitAndTrim(s, sep, cutset string) []string {
  45. if s == "" {
  46. return []string{}
  47. }
  48. spl := strings.Split(s, sep)
  49. for i := 0; i < len(spl); i++ {
  50. spl[i] = strings.Trim(spl[i], cutset)
  51. }
  52. return spl
  53. }