tendermint/common/string.go

44 lines
800 B
Go
Raw Normal View History

2015-10-21 12:15:19 -07:00
package common
import (
2017-06-05 12:50:11 -07:00
"encoding/hex"
2015-10-21 12:15:19 -07:00
"fmt"
"strings"
)
// Like fmt.Sprintf, but skips formatting if args are empty.
var Fmt = func(format string, a ...interface{}) string {
if len(a) == 0 {
return format
} else {
return fmt.Sprintf(format, a...)
}
}
2015-10-21 12:15:19 -07:00
2017-06-05 13:22:01 -07:00
// IsHex returns true for non-empty hex-string prefixed with "0x"
2017-06-05 12:50:11 -07:00
func IsHex(s string) bool {
if len(s) > 2 && strings.EqualFold(s[:2], "0x") {
2017-06-05 12:50:11 -07:00
_, err := hex.DecodeString(s[2:])
return err == nil
2017-06-05 12:50:11 -07:00
}
return false
}
2017-06-05 13:22:01 -07:00
// StripHex returns hex string without leading "0x"
2017-06-05 12:50:11 -07:00
func StripHex(s string) string {
if IsHex(s) {
return s[2:]
}
return s
}
// StringInSlice returns true if a is found the list.
func StringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}