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.

59 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. }
  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. }